How to set default umask in Ubuntu 17.04?

Question: In the past, I have always set umask at ~/.profile. I set a umask of 077 so my documents get a permission of 600 (rw-------). But setting this at ~/.profile no longer works in Ubuntu 17.04.
So as new documents get created in a gnome session on Ubuntu 17.04, where can I configure so that they get created with permission 600?
Answer: To set permissions for all directories and files that are created day-forward by any user:

sudo nano /etc/pam.d/common-session
Find the line with "session optional pam_umask.so"
Change this to "session optional pam_umask.so umask=0077"
Save the file.
Reboot.

New files will be 600.
New directories will be 700.
Comment: Except for the bug in the default GNOME terminal linked to in Daniel's answer, this works, but I'm curious why you're suggesting modifying `/etc/pam.d/common-session` directly, given that the value is primarily defined in `/etc/login.defs` (at least as of 18.04 - has that changed)?
Comment: @mklement0 Probably because of the comment in the default `.profile`: _"for setting the umask for ssh logins, install and configure the libpam-umask package"_
Comment: The OP ask for a per user setting, not for any user.
Answer: tl; dr: Replace UMASK 022 by e.g. UMASK 027 in file /etc/login.defs but doesn't work 100%.

Documentation
See the man pages (20.04) for info on this. There are several places where it can be set: I used /etc/pam.d/login or /etc/default/login in the past but stopped working so now I'm using /etc/login.defs which partially works.

The PAM module tries to get the umask value from the following places in the following order:
·   umask= entry in the user's GECOS field
·   umask= argument
·   UMASK entry from /etc/login.defs (influenced by USERGROUPS_ENAB in /etc/login.defs)
·   UMASK= entry from /etc/default/login
(...)
EXAMPLES
Add the following line to /etc/pam.d/login to set the user specific umask at login:
    session optional pam_umask.so umask=0022

Ubuntu 18.04, Ubuntu 20.04
In file /etc/login.defs there is an entry UMASK      022 that can be replaced by, in my case, UMASK        027. Then reboot. This yields:
Ubuntu 18.04:
$ umask
0022
$ more /etc/login.defs | grep ^UMASK
UMASK       027

$ echo foo > terminal

NOTE:  Open gedit from Dock and write file `dock`
       Open gedit from Menu and write file `menu`

$ ls -l dock menu terminal
-rw-r--r-- 1 daniel daniel 4 nov  4 16:11 dock
-rw-rw---- 1 daniel daniel 4 nov  4 16:11 menu
-rw-r--r-- 1 daniel daniel 4 nov  4 16:11 terminal

Ubuntu 20.04:
$ umask
0007
$ more /etc/login.defs | grep ^UMASK
UMASK       027

$ ls -l foo bar
ls: cannot access 'foo': No such file or directory
ls: cannot access 'bar': No such file or directory

$ touch foo
$ echo hello > bar
$ ls -l foo bar
-rw-rw---- 1 daniel daniel 6 nov  4 17:20 bar
-rw-rw---- 1 daniel daniel 0 nov  4 17:20 foo

Might work in 17.04
Note this file does not exist on my version of Ubuntu, in which case we can create it.
$ sudo sh -c "echo 'session optional pam_umask.so umask=0027' >> /etc/default/login"

$ more /etc/default/login
session optional pam_umask.so umask=0027

Evil Bug
Now if we restart and ask for the umask in the terminal we still get 0022 (in the case of Ubuntu 18.04) and not the 0027 that was set. See Bug #1685754.
But if we open an application, for example the Text Editor, and save a file we'll notice the new umask affected permissions. Open it from the menu, not from the terminal as it seems to pick up the (bad) umask from the terminal.
References

Ubuntu 18.04 Manpage for pam_umask
Bug #1685754, since 17.04
Comment: @mklement0, I don't remember the reason. I used `/etc/default/login` or `/etc/pam.d/login` in the past and these seemed to somehow work for some time, but not anymore. I now did a new installation with Ubuntu 20.04 and the same issue come up, I'm now using `/etc/login.defs`. The man page states all of these configuration files affect permissions.
Comment: The OP asked for a per-user configuration. The man page only talks about "GECOS fields" without any link or explanation how to modify them.
Comment: Good to know about the bug. Is there a reason you're not modifying the `UMASK` value directly in the preexisting `/etc/login.defs` file (or does that work differently in 17.04)? Also, you mention `/etc/pam.d/login` in the text, but your command modifies `/etc/default/login`.
Comment: thats because in /etc/logindefs; if 'USERGROUPS_ENAB yes' then user and private user group permissions (uid= , gid = ) will be same. i.e. 022 will be implemented as 002, or 027 as 007, 077 as 007...so on
Answer: I have recently came across this on Ubuntu 20.04 TLS and found the solution.
$ man -k umask
$ man pam_umask

This will get us the location of manual pages that discuss umask - all information can be found there.
From /etc/pam.d/common-session:

The pam_umask module will set the umask according to the system
default in /etc/login.defs and user settings.
This solves the problem of different umask settings with different
shells, display managers, remote sessions etc.

From PAM_UMASK(8):

pam_umask is a PAM module to set the file mode creation mask of the
current environment. The PAM module tries to get the umask value from
the following places in the following order:
umask= entry in the user's GECOS field
umask= argument UMASK entry
from /etc/login.defs (influenced by USERGROUPS_ENAB in
/etc/login.defs)
UMASK= entry from /etc/default/login

Notice the text in the brackets: influenced by USERGROUPS_ENAB in /etc/login.defs.
What is USERGROUPS_ENAB?
From /etc/login.defs:

If USERGROUPS_ENAB is set to "yes", that will modify this UMASK
default value
for private user groups, i. e. the uid is the same as gid, and username is
the same as the primary group name: for these, the user permissions will be
used as group permissions, e. g. 022 will become 002.
In not specified, the permission mask (umask) is initialized to 022.

You can now run this:
$ sudo nl /etc/login.defs | grep USERGROUPS_ENAB

to double-check if you have USERGROUPS_ENAB set to "yes", if it's uncommented (default), and on which line of the document can you find it.
Therefore, when you change the default "UMASK  022" to "UMASK  027", if USERGROUPS_ENAB is set to "yes", you will see that your umask has been set to 007 (not 027) - as it ignores the 2nd position (group permissions).
The solution to this is simple: uncomment the line where "USERGROUPS_ENAB" is set to "yes". If you have changed umask value to "UMASK  027", you will have umask set to 027 after the reboot.
You can verify this by running this in your shell.
$ umask

To summarize, the only config file that matters is /etc/login.defs.
Set your umask to desired value and make sure to uncomment USERGROUPS_ENAB line to change group permissions as well.
Hope this helps.
Answer: # the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
#umask 022

That's literally what your ~/.profile says. Did you relogin once changed? It should work fine.
Also:
This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login exists.

Actually confirmed the issue on a freshly installed ubuntu 17.04. Even fully updating still causes this issue to arise and even ~/.bash_profileis ignored, there seems to be an issue with the command interpreter not reading those files after login.
You can use ~/.bashrc for now, which still works fine and is read during login.
So after digging a little into it, it seems bash is not run by default with the --login anymore which means it doesn't read the ~/.profile. Starting a new bash with the umask in ~/.profile with bash --login sets the umask correctly starting a bash without it though ignores the ~/.profile. Not sure what was changed but this seems like a bug to me unless it was intentionally changed.
Comment: Yes, I relogged in.
Comment: And the only ~/.bash files I have are .bashrc, .bash_logout, .bash_history. I ran a find search. .bash_profile and .bash_login do NOT exist on machine.
Comment: Oh, I'm sorry you are actually right. I just freshly installed a 17.04 to test it on a new installation and it actually isn't read from ~/.profile for some reason. I haven't digged into it yet. But you can add your umask into `~/.bashrc` for now this is still read during startup.
Comment: Ziazis, setting umask in .bashrc only works for docs created in terminal. I'm looking to get umask applied for example from doc created in gedit. You have found a fix with `bash -login`? How do I implement this exactly? Or is this unfixable until a bug is fixed?
Answer: If you're using GDM, it doesn't read ~/.profile like LightDM does. And the terminal normally opens a non-login shell. The net effect is that ~/.profile is not loaded at all when you open a terminal after logging in using GDM.
Either:

put your settings in ~/.bashrc, or
set your terminal to start a login shell, or
switch to LightDM
Comment: Actually I just confirmed his issue on a freshly installed 17.04 version. Has nothing to do with GDM since by default lightDM is still used.
Comment: OK, so? Did I say his issue doesn't exist?
Answer: On Ubuntu 18.04.3 I have tried to create /etc/default/login with session optional pam_umask.so umask=0027 as Daniel says but not worked for me, instead I have changed the umask in /etc/login.defs and it worked.
I have changed umask value in 002 and now all the users create files with full permission also for their own group.
Answer: I have the workaround at least on Fedora 31:
sudo vi /etc/profile.d/umask.sh
umask <your_umask>

sudo vi /etc/login.defs
UMASK <your_umask>

sudo vi /usr/local/bin/systemd-user
/usr/lib/systemd/systemd --user

sudo chmod a+x /usr/local/bin/systemd-user

sudo vi /usr/lib/systemd/system/user@.service
ExecStart=-/usr/local/bin/systemd-user


Taking user input and searching through Firebase Database

Question: I am currently doing a project using DialogFlow and Firebase Database. My main concern, and I have been trying to figure it out for a long time is, how do I take a user input and search through the Firebase database for it?
As you can see in the code, I have the if else statement to help me filter it out for now, however as more events are being stored the database,I figured out that the if else statement will not be efficient and viable. So, do advise me on how to best take in a user's input and search the database per their request. For example, they might ask "What events are there on 15th August?", the function should then search the database for 15th August, and inform them of any events on that day. Hope to hear from you soon!
function askDate(agent) {
const date1 = agent.parameters.date;

return admin.database().ref('date').transaction((date)=>
{
    let askdate = date.askDate;
    let activity = date.activity;

    let askdate1 = date.twelfthAugust.askDate;
    let activity1 = date.twelfthAugust.activity;

    let askdate2 = date.fourthAugust.askDate;
    let activity2 = date.fourthAugust.activity;

    let askdate3 = date.ninthAugust.askDate;
    let activity3 = date.ninthAugust.activity;
    if (date1 == askdate)
    {
        agent.add("We have " + activity);
    }
    else if (date1 == askdate1)
    {
        agent.add("We have " + activity1);
    }
    else if (date1 == askdate2)
    {
        agent.add("We have " + activity2);
    }
    else if (date1 == askdate3)
    {
        agent.add("We have " + activity3);
    }
    else
    {
        agent.add("We do not have any events on this day!");
    }
    return date;
},
function (error, isSuccess) {
    console.log('Success: ' + isSuccess);

});
}

Comment: please share the use case.
Comment: @AbhinavTyagi hi there, basically, there are a few things a user can ask the google home, such as events and courses. For this instance, the user wishes to ask Google Home if there is an event on 5th August 2018, for example. The dialogflow will then reference the database, and search for the date stated by the user, and inform them is there is an event on that date. My concern is that if I keep using the if else statement, it will not be very efficient as there will be more events to be added.
As such, is there a way to take simplify the if-else statement?
Answer: You just need to design intent to capture a date from the user. Pass this date to webhook and use something like "select event from DB where date = userProvidedDate"
Instead of if else, you should fetch the event from the DB based on the date. You need to look for how you will be doing that.


Full JSON render of object with nested object

Question: I have a grails application with mongodb plugin.
All my domain objects are:
class Person {
  ObjectId id
  String name
}

and
class Like {
  ObjectId id
  Person from
  Person to
  Date createdAt
}

My controller should give a full data according to some Like by id:
class MyController {
  def like() {
    def like = Like.findById(new ObjectId("someIdHere"));
    render(like as grails.converters.JSON)
  }
}

I wish to receive a full JSON-object of like:
{
  "class":"Like",
  "id":{
    "class":"org.bson.types.ObjectId",
    "inc":1483542456,
    "machine":805594765,
    "new":false,
    "time":1340363115000,
    "timeSecond":1340363115
  },
  "createdAt":"2012-06-22T11:05:15Z",
  "from":{
    "class":"Person",
    "id":{ ... },
    "name":"Some name here"
  },
  "to":{
    "class":"Person",
    "id":{ ... },
    "name":"Some name here"
  }
}

but I've receive first-level properties of object:
{
  "class":"Like",
  "id":{
    "class":"org.bson.types.ObjectId",
    "inc":1483542456,
    "machine":805594765,
    "new":false,
    "time":1340363115000,
    "timeSecond":1340363115
  },
  "createdAt":"2012-06-22T11:05:15Z",
  "from":{
    "class":"Person",
    "id":"4fd31d453004dc0f010aca51"
  },
  "to":{
    "class":"Person",
    "id":"4fd31d463004dc0f010aca89"
  }
}

My question is: is there any way to construct full (with referenced objects) JSON of mongo db (DBObject) data object? I've found out this solution with JSONBuiled with escaped fields 'class', metaClass' and 'dbo'. But I think it can be done with Expando classes but I cann't find the right way...
Thanks any way,
Maksim
Answer: Change
render(like as grails.converters.JSON)

to
render(like as grails.converters.deep.JSON)

Comment: deep.JSON is now deprecated. Use the JSON.use("deep") for deep conversions.
Comment: I've tried this way, but the response is

    {
      "class":"Like",
      "id":{...},
      "createdAt":"2012-06-22T11:05:15Z",
      "from": {
        "class":"Person",
        "id":{...},
        "name":null
      },
      "to":{
        "class":"Person",
        "id":{...},
        "name":null
      }
    }

So the deep configuration doesn't trigger the lazy methods.
Answer: I believe the standard way is to use named configs now so you want
JSON.use("deep") {
    render like as JSON
}

Comment: I've tried this way, but the response is

`    {
      "class":"Like",
      "id":{...},
      "createdAt":"2012-06-22T11:05:15Z",
      "from": {
        "class":"Person",
        "id":{...},
        "name":null
      },
      "to":{
        "class":"Person",
        "id":{...},
        "name":null
      }
    }`

So the deep configuration doesn't trigger the lazy methods.
Answer: If this continues to be a problem for you, you might want to try another JSON library, like Jackson, which gives much more control over serialising objects to JSON than the Grails JSON libraries do.
Comment: Hi! I've wrote a custom work around my classe. I know it is not good for me). Next time I'll use your advice, I think.
Any way thank you!
Answer: Set the Child association to non lazy.
So
   class Like {
  ObjectId id
  Person from
  Person to
  Date createdAt

 static mapping = {
        from lazy: false
    }

}

Comment: unlazy configuration wasn't suit me well... But can help.
Thnx!
Comment: NEVER do that, imagine that you have many nested objects and you just want to change one attribute, with lazy false you'll load in memory all the objects, the nested objects, the sub-nested objects in the nested objects, etc.


How to create Appserver, schema, trigger and modules DB in every host attached to a cluster?

Question: I am trying to configure MarkLogic instance setup in AWS. I have a cluster with 3 nodes(3 EC2 instances) attached to ELB. I want each of the host to have the same App Server, Modules , Schema and Trigger DB. How can i set it up using ml-gradle?
Answer: Try walking through the Getting Started guide first. When you create an app server, it will by default exist on each host. And your database will by default have one or more forests on each host. The fact that it's AWS doesn't impact anything here. Also see this sample project for an example of an application with a schemas and triggers database (along with many other kinds of resources).


Why does the skins hanger make me exit the game?

Question: Every time I tap the skins hanger, it takes me to my home screen and makes me exit the game. What's happening and how do I fix it?
Comment: I think this is a question about MCPE
Answer: Try getting MCPE Master and a get a skin from there and apply it. Afterwards you should be able to press on the skins button.
Comment: This does not provide a solution and looks almost like a promotion.


How to remove carriage returns in a text editor?

Question: How can I go about remove carriage returns from a file in a text editor?
For example, if I start with this:
Hello
world
this
is
an
example

I'd like to end up with:
Hello world this is an example

How do I do this in Text Editor and Notepadqq in Ubuntu 16.04 LTS?
Answer: This is easy to do in Ubuntu's default text editor gedit a.k.a. Text Editor.
Open Find and Replace menu by using the default Ctrl+H key shortcut or by using the context menu in the top right of gedit.

If you are editing a file with UNIX-style line endings, do a find & replace like so:
Find: \n
Replace with: space

If you are editing a file with Windows-style line-endings, do a find & replace like so:
Find: \r\n
Replace with: space
Comment: @EliahKagan even if it doesn't work in Notepadqq, OP could still copy/paste into gedit... *shrug*
Comment: I believe the OP may have been interested in how to do it in multiple editors, based on the original wording in the question--that's why I was asking. (In some desktop environments, gedit appears in menus as "Text Editor.") This answer is definitely valuable.  I've added a heading so people know this is gedit. @HidekiNishimura I've edited your question to make it say what I think you had intended. But if that is not correct, please feel free to roll back my edit or otherwise edit again.


SWIG-Java memory management when returning references to member variables

Question: I am accessing C++ code from Java using SWIG.
Getters in C++ usually return const references:
class B
{
public:
  const A& getA() const { return a_; }
private:
  A a_;
};

Generate SWIG wrappers. B::getA in Java returns a reference as expected. Yet JVM does not know that this reference is associated with class B. It might lead to a broken reference:
public A createA() {
    B b = new B();
    return b.getA();
}

Object returned from createA is invalid once garbage collector destroys B b and JVM knows nothing about it.
SWIG provides documentation addressing this issue: references and swig. Yet it means that I need to add all these references manually.
I came up with the following solution which returns copies instead of const references in SWIG generated code:
%typemap(out) const SWIGTYPE&
{
  *($&1_ltype)&$result = new $1_basetype(($1_type)*$1);
}
%typemap(javaout) const SWIGTYPE&
{
  return new $javaclassname($jnicall, true);
}

I have two questions:

Is this approach safe? Did not I forget something?
Is there any better solution to address this issue and not to write much code?

Any help is appreciated.
Answer: That looks sensible as written however I wouldn't recommend using it.
As it stands you will lose the semantics of return by const reference if you force every case of it to become a copy. This will impact the SWIG wrapping of other things too (e.g. standard library containers).
It has the potential to adversely impact performance of your wrapped code compared to the native library. More seriously though, it fundamentally changes the behaviour in some cases too. Consider for example the following SWIG example:
%module test

%typemap(out) const SWIGTYPE&
{
  *($&1_ltype)&$result = new $1_basetype(($1_type)*$1);
}
%typemap(javaout) const SWIGTYPE&
{
  return new $javaclassname($jnicall, true);
}

%inline %{
struct A {
    int v;
    A() : v(0) {}
};

class B
{
public:
  B() { }
  const A& getA() const { return a_; }
  void counter() {
    a_.v++;
  }
  int test() const { return a_.v; }
private:
  A a_;
};

%}

If we were to use it from Java like:
public class run {
    public static void main(String[] argv) {
        System.loadLibrary("test");
        A a = test();
        System.out.println("A.v = " + a.getV());
    }

    private static A test() {
        B b = new B();
        A result = b.getA();
        System.out.println("A.v = " + b.test() + " (test)");
        b.counter();
        System.out.println("A.v = " + result.getV());
        return result;
    }
}

The result is that v is always (unexpectedly) 0:
A.v = 0 (test)
A.v = 0
A.v = 0

Contrast that with the same (correct) C++ beahviour:
#include <iostream>

struct A {
    int v;
    A() : v(0) {}
};

class B
{
public:
  B() { }
  const A& getA() const { return a_; }
  void counter() {
    a_.v++;
  }
  int test() const { return a_.v; }
private:
  A a_;
};

static A test();

int main() {
    const A& a = test();
    std::cout << "A.v = " << a.v << "\n";
}

static A test() {
    B b;
    const A& result = b.getA();
    std::cout << "A.v = " << b.test() << " (test)" << "\n";
    b.counter();
    std::cout << "A.v = " << result.v << "\n";
    return result;
}

Which correctly returns:
A.v = 0 (test)
A.v = 1
A.v = 1

That unnatural semantics is a show-stopper for me.
My suggestion would be to skip the copy constructor plan and adapt the example from the documentation to be generic:
%module test

%typemap(javabody,noblock=1) SWIGTYPE {
  private long swigCPtr;
  protected boolean swigCMemOwn;

  protected $javaclassname(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected $javaclassname(long cPtr, boolean cMemoryOwn, Object cParent) {
    this(cPtr, cMemoryOwn);
    swigCParent = cParent;
  }

  protected static long getCPtr($javaclassname obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  private Object swigCParent;
}

%typemap(javaout) SWIGTYPE const & {
    return new $javaclassname($jnicall, $owner, this);
  }

%inline %{
struct A {
    int v;
    A() : v(0) {}
};

class B
{
public:
  B() { }
  const A& getA() const { return a_; }
  void counter() {
    a_.v++;
  }
  int test() const { return a_.v; }
private:
  A a_;
};

%}

Which now behaves like the C++ equivalent for one extra Object reference that gets inserted and managed automatically per class.
If you want to made this work automatically for both static and non-static methods we need to use a few tricks because, unfortunately, there is no way of specifying a typemap should only apply to non-static methods. The trick I used is explained in detail on another question. With this trick we can modify the SWIG interface to add:
%pragma(java) moduleimports=%{
  import java.lang.reflect.Field;
%}

%pragma(java) modulecode=%{
  static Object getThisOrNull(final Object o, final Class c) {
    for (Field f: o.getClass().getDeclaredFields()) {
      if (f.getType().equals(c)) {
        try {
          return f.get(o);
        }
        catch (IllegalAccessException e) {
          // Omm nom nom...
        }
      }
    }
    return null;
  }
%}

And change the javaout typemap to be:
%typemap(javaout) SWIGTYPE const & {
    return new $javaclassname($jnicall, $owner, $module.getThisOrNull(new Object(){}, $javaclassname.class));
  }

The remainder of the interface is as previously discussed, but this modification now causes swigCParent to be null if there is no parent (i.e. static method).
Comment: We have a large library exposed via swig, and early deletion (due to this issue) has been a real thorn in our side.  Big thanks to @Flexo for pointing us in the right direction, and to bactron for the clear overview of the problem. Flexo's solution works for most code, but breaks on any static functions that return by reference.  Any idea how to exclude static functions from a typemap?  Is there a javaout modifier we can use to match statics?
Comment: @AlexGoldberg I added a workaround that lets this compile and work for both cases in one typemap. It's ugly though, so I'd recommend running some profiling and if it hurts writing specific typemaps for specific functions. (I'm working on another solution though that might be slightly better using C++ template meta programming techniques instead)
Comment: Wow, definitely points for creativity on that one ;)  We decided that such static functions were rare enough that we could would handle them individually (by wrapping the declarations in macros that disable and then re-enable the typemap).  Last thing is to figure out how to handle public member variables.  Currently looking for a way to disable the automatic getter/setter creation for those...
Comment: @AlexGoldberg You can make SWIG ignore member variables with `%rename("$ignore", %$isvariable, %$ismember) "";` -  see ['Advanced Renaming'](http://www.swig.org/Doc3.0/SWIG.html#SWIG_advanced_renaming) for details. Some of the others (e.g. `%$ismemberget` or `%$isstatic`) might let you do some neat things too.
Comment: Thanks!  You've really saved us a lot of time.


How to implement a C function that will not proceed with it's operations if it is called more than 100 times per second?

Question: I need to implement a function which should not proceed it's operations if it is called more than 100 times per a sec. Any suggestions how can I write this function in C?
Comment: Instead of describing what you're trying to do, describe [what problem you're trying to solve](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).
Comment: @BasileStarynkevitch: Sure you can. All you need is `time`, `gmtime`, and some static storage to keep track of the "current second" and the number of calls made during it.
Comment: On which operating system?
Answer: How about:
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
uint64_t timedfun(uint64_t a, uint64_t b)       //dummy arguments, replace with yours
{
  static time_t lastt;                          //might want to use _Thread_local
  static uint_fast8_t count;                    //might want to use _Thread_local
  time_t currt = time(NULL);
  if (lastt != currt)
    {
      lastt = currt;
      count = 0;
    }
  if (++count > 100)
    {
      exit(EXIT_FAILURE);            //You didn't specify what to do when it's called more than 100 times...
    }
  return a+b;                        //dummy result, replace with your function
}

As nos touched upon thread-safety in his answer, I've added some comments. The comments show where an applicable storage/lifetime specifier should go to ensure thread-safety (this will allow up to 100 calls to this function per thread). Otherwise this limit would be shared over all threads, and prone to race-conditions. In that case, you might need a mutex too.
Edit for non-POSIX systems, pure C-compliance (kudos to chux's comment):
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
uint64_t timedfun(uint64_t a, uint64_t b)       //dummy arguments, replace with yours
{
  static time_t lastt;                          //might want to use _Thread_local
  static uint_fast8_t count;                    //might want to use _Thread_local
  time_t currt = time(NULL);
  if (difftime(lastt, currt) >= 1.0)            //uses floating-point numbers, use for non-POSIX systems
    {
      lastt = currt;
      count = 0;
    }
  if (++count > 100)
    {
      exit(EXIT_FAILURE);            //You didn't specify what to do when it's called more than 100 times...
    }
  return a+b;                        //dummy result, replace with your function
}

Comment: In practice this works, but `time_t` is permitted to be in units other than seconds, e.g. to be higher resolution. So to be fully correct, you would need to convert the `time_t` to `struct tm` and compare it that way.
Comment: @R.. and OP, using `difftime()` would simplify portability.
Comment: @R.. 2 approaches 1) This answer using 1 sample and then see if 100 occur within 1 sec.  Something like the 2nd solution posted here other than I'd use `if (difftime(lastt, currt) >= 1.0)` as `difftime ()` may have finer than 1.0 second resolution.  The 2nd approach follows John's idea of 100 buckets then checking if the 100th previous invocation for <= 1.0 seconds ago.  This 2nd approach would detect a burst of say 60 calls right before a 1 second tick and a burst of 60 calls right after the tick.
Comment: Excellent. Thanks for the simple answer.
Comment: On POSIX, `time()` returns seconds (or, to be precise, something close to seconds) since the Unix-Epoch.
Comment: @chux: Sure, that would work. It's a bit ugly in my opinion, since it uses a `double`, and so now you're involving the FPU in this calculation for no good reason. Seems like a waste to me.
Comment: How would you recommend to make this solution portable?
Comment: @chux: Oh, I'm not saying that this isn't the easiest portable solution. I'm just saying it's a shame it *is*. If everyone was POSIX-compliant (Or the C standard was more specific), we could avoid this kludge.
Answer: Add:
usleep(10000);

:)
Short of that you'll need to allocate storage to hold the times of the last 100 invocations, and keep track of those in a rotating fashion.  This seems silly, but perhaps there might in some dark corner of the universe be a reasonable reason to do this.
Comment: No, you just need the time of the last invocation, rounded to 1-second resolution.
Comment: Actually, a time-stamp AND a counter should be sufficient then.  As long as it is 100 in any given second on the clock, not worrying about 100 which might span a particular second to the next second on the clock.
Comment: Yes, sorry; but "just" I meant that you don't need a full record of the last 100 invocations, not that you don't need any additional information (the counter).
Comment: Huh, if the last invocation is the same second as the current invocation, how do I know how many there have been in the current second?  Could be just these two, could be billions.
Answer: You can use a token bucket principle to rate limit your function.
First some common stuff:
struct RateLimit {
    //how many tickets we want
    long tickets;
    //per this period of time
    long period;

    //internal fields:

    //money we have to "buy" tickets
    long funds;
    //time of the previos period
    long last_refill_ts;
};

#define RATELIMIT_INITIALIZER(tickets, period)\
{ tickets, period, 0, -period}

//current_ts must be in the unit of r->period
static void ratelimit_refill(struct RateLimit *r, long current_ts)
{

    long diff_period;
    //Find elapsed time
    diff_period = current_ts - r->last_refill_ts;

    if (diff_period > r->period) {
        //help prevent overflow when calculating available tickets below
        diff_period = r->period;
    } else if (diff_period < 0) {
        //time went backwards, skip this round
        diff_period = 0;
    }

    //Calculate the cost of tickets that became available
    r->funds += diff_period * r->tickets;

    //throttle handing out tickets
    if (r->funds > r->period * r->tickets) {
        r->funds = r->period * r->tickets;
    }

    //save this period.
    r->last_refill_ts = current_ts;
}

int ratelimit_allow(struct RateLimit *r, long current_ts)
{
    int allowed;

    if (r->funds < r->period) { //not enough funds

        ratelimit_refill(r, current_ts);

        //as we keep track of the last timestamp of refilling
        //We don't need to refill when there is enough funds
    }

    //If we have enough to buy atleast one ticket, we can allow
    if (r->funds >=  r->period) {
        r->funds -= r->period;
        allowed = 1;
    } else {
        //not enough to buy a ticket
        allowed = 0;
    }

    return allowed;
}

Then you'd use this in your function that you want to rate limit:
void my_function(void)
{   //limit to 100/sec
    static struct RateLimit rl = RATELIMIT_INITIALIZER(100, 1);
    if (!ratelimit_allow(&rl, time(NULL))) {
         abort(); //or less drastic measures
    }
    //your actual code here
}

Note - this function is not thread safe, you'd have to provide a mutex or similar around the ratelimit_allow() to make it thread safe too.


Is the ideal $\langle x^2 + 1\rangle$ maximal in $\mathbb{Z}_3[x]$?

Question: Is the ideal $\langle x^2 + 1\rangle$ maximal in $\mathbb{Z}_3[x]$?
I am going about this by trying to prove that $\frac{\mathbb{Z}_3[x]}{\langle x^2 + 1 \rangle}$ is a field. I can prove commutative and unity, but I need some help on how I should show that every nonzero element is a unit.
Comment: By $\mathbb{Z}_3$, do you mean the 3-adic integers, or just the integers mod 3?  (In the latter case, I tend to prefer using $\mathbb{F}_3$ or $\mathbb{Z} / 3 \mathbb{Z}$ to avoid confusion with the former.)
Comment: $1i$ is technically correct, but this redundancy makes me doubt your assertions.
Comment: What is $i$? There are no elements in ${\Bbb Z}_3$ with square $-1=2$.
Comment: The $i$ was a typo, my apologies.
Comment: Make sure you put the ideal generated by the polynomial, and not just the polynomial, in the denominator here.
Comment: @DanielSchepler $\mathbb{Z}_3=\{0,1,2\}$ so just the integers mod 3.
Comment: hints: let $F$ be any field. then $F[x]$ is a PID, so (i) non-zero prime ideals are maximal, and (ii) an irreducible element generates a prime ideal. can you do the rest from here?
Answer: $x^2 + 1$ has no roots in $\Bbb{Z}_3 := \Bbb{Z}/3\Bbb{Z}$, so the ring of equivalence classes $$\frac{\Bbb{Z}_3[x]}{\langle x^2 + 1 \rangle} := \{ \overline{a + bx}: a, b \in \Bbb{Z}_3 \}$$ is a finite integral domain, which means it's a field.
In general, if what you really want to know is whether or not an ideal $M \subset R$ of the ring $R$ is maximal, it's very inefficient (not to say impractical, or sometimes impossible) to directly check that every nonzero equivalence class $\overline{a} = a + M \in R/M$ has a multiplicative inverse in $R/M$ by hand-computation.
It's better to use some heavier machinery--in this case, the fact that $R = \Bbb{Z}_3$ is a field, so $\Bbb{Z}_3[x]$ is a Euclidean domain, which means every ideal is principal and the maximal ideals are precisely those generated by irreducible polynomials (since non-constant factors of $p(x) \in \Bbb{F}[x]$ become zero divisors in the quotient ring $\frac{\Bbb{F}[x]}{\langle p(x) \rangle}$, which is finite iff $\Bbb{F}$ is finite).
I was a little sloppy in just saying "$x^2 + 1$ has no roots", actually, because having no roots is a necessary but not a sufficient condition to be an irreducible polynomial. For instance, $x^4 + 1$ has no roots in $\Bbb{Z}_5$, but it factors over $\Bbb{Z}_5$ as $(x^2+2)(x^2+3)$. In this specific case though, $M = \langle x^2 + 1 \rangle$, so it's sufficient to say the polynomial has no roots, because the only possible factors of a quadratic like $x^2 + 1$ are linear.
Answer: OK, let us show explicitly that every element in the ring $R=\Bbb F_3[x]/(x^2+1)$ is a unit. (This is of course a field, the extension of degree two of the field $\Bbb F_3$ with three elements, since the ideal $(x^2+1)$ is generated by an irreducible = prime element. The ring $R$ is by general means isomorphic to the one field $\Bbb F_9$ with nine elements - taken up to isomorphism. But well, the OP wants to show that every element is a unit.)
The non-zero elements in $\Bbb F_3$, identified with (classes of) constant polynomials are units. Let us consider all "other" (classes of) polynomials $f$. These have degree one. After possibly norming the principal coefficient (with units $\pm 1$ in $\Bbb F_3$) we can and do consider the monic case only. There are only three cases:

For $f$ being (the class of) $x+1$ we have $(x+1)(x-1)=x^2-1\equiv -1-1=-2=1$.
For $f$ being (the class of) $x-1$ we have the same computation.
For $f=x$ consider $x(-x)=-x^2\equiv -(-1)=1$.

So every non-zero element in $R$ is a unit.
$\square$


text fields are empty when retriving data from firebase to recycler view

Question: I am trying to build an android application which retrieve data from Firebase real time database. I have coded to display data from Firebase to a recyclerview in fragments. Project was successfully build but its not showing when i run the app, text fields are empty and some of them shows text values that i given for reference. I have looked in Firebase Adapter for any change in code and search over internet for solutions.

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:backgroundTint="@color/txtcolor"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/recycler_design"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="3dp"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/worker_name"
                android:textSize="16sp"
                android:text="Name:  "
                android:textColor="@color/black"/>

            <TextView
                android:id="@+id/debit_workerName"
                android:layout_width="225dp"
                android:layout_height="wrap_content"
                android:textColor="@color/black"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/debit_date"
                android:layout_width="96dp"
                android:layout_height="wrap_content"
                android:textAlignment="textEnd"
                android:textColor="@color/black"
                android:textSize="14sp" />

        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/white"/>

        <LinearLayout
            android:layout_width="392dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="180dp"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/billNumber"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Bill Number:  "
                    android:textColor="@color/black"
                    android:textSize="14sp" />

                <TextView
                    android:id="@+id/debit_billNumber"
                    android:layout_width="94dp"
                    android:layout_height="match_parent"
                    android:textColor="@color/blue"
                    android:textSize="14sp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="202dp"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/commi"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Comm:  "
                    android:textColor="@color/black"
                    android:textSize="18sp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/Rs"
                    android:textColor="@color/black"
                    android:textSize="18sp" />

                <TextView
                    android:id="@+id/debit_commission"
                    android:layout_width="123dp"
                    android:layout_height="match_parent"
                    android:textColor="@color/selected_red"
                    android:textSize="18sp" />
            </LinearLayout>

        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/white"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:padding="3dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/billAmt"
                android:textSize="14sp"
                android:text="Bill Amount:  "
                android:textColor="@color/black"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:text="@string/Rs"
                android:textColor="@color/black"/>

            <TextView
                android:id="@+id/debit_billAmount"
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:textColor="@color/greentxt"
                android:textSize="14sp" />

        </LinearLayout>
    </LinearLayout>

</RelativeLayout>

Model class

public class modelDebit {

    public String wName, bill_no,bill_amt,date,comm;

    public String getwName() {
        return wName;
    }

    public void setwName(String wName) {
        this.wName = wName;
    }

    public String getBill_no() {
        return bill_no;
    }

    public void setBill_no(String bill_no) {
        this.bill_no = bill_no;
    }

    public String getBill_amt() {
        return bill_amt;
    }

    public void setBill_amt(String bill_amt) {
        this.bill_amt = bill_amt;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getComm() {
        return comm;
    }

    public void setComm(String comm) {
        this.comm = comm;
    }

    public modelDebit(String wName, String bill_no, String bill_amt, String date, String comm) {
        this.wName = wName;
        this.bill_no = bill_no;
        this.bill_amt = bill_amt;
        this.date = date;
        this.comm = comm;
    }

    public modelDebit() {

    }
}

Logcat

 --------- beginning of system
2019-03-18 20:22:10.572 1600-2206/? I/ActivityManager: START u0 {cmp=......./.Transaction} from uid 10081
2019-03-18 20:22:10.578 5039-5070/V/FA: Recording user engagement, ms: 14804
2019-03-18 20:22:10.582 5039-5070/ V/FA: Connecting to remote service
2019-03-18 20:22:10.585 5039-5070/ V/FA: Activity paused, time: 1230916
2019-03-18 20:22:10.613 5039-5070/ D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=14804, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-657156986720031714}]
2019-03-18 20:22:10.654 5039-5070/ V/FA: Connection attempt already in progress
2019-03-18 20:22:10.654 5039-5039/ V/FA: onActivityCreated
2019-03-18 20:22:10.749 5039-5070/ D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=-657156986720031714, firebase_screen_class(_sc)=Transaction, firebase_screen_id(_si)=-657156986720031713}]
2019-03-18 20:22:10.793 1400-1453/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 8298496
2019-03-18 20:22:10.802 1400-1453/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 8298496
2019-03-18 20:22:10.805 5039-5070/ V/FA: Connection attempt already in progress
2019-03-18 20:22:10.807 5039-5070/ V/FA: Connection attempt already in progress
2019-03-18 20:22:10.807 5039-5070/ V/FA: Activity resumed, time: 1231049
2019-03-18 20:22:10.815 1400-1453/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 8298496
2019-03-18 20:22:10.849 5039-5077/ D/EGL_emulation: eglMakeCurrent: 0xa17055a0: ver 2 0 (tinfo 0xa1703510)
2019-03-18 20:22:10.872 1600-1621/? I/ActivityManager: Displayed /.Transaction: +294ms
2019-03-18 20:22:10.878 5039-5070/ D/FA: Connected to remote service
2019-03-18 20:22:10.879 5039-5077/ D/EGL_emulation: eglMakeCurrent: 0xa17055a0: ver 2 0 (tinfo 0xa1703510)
2019-03-18 20:22:10.882 5039-5070/ V/FA: Processing queued up service tasks: 4
2019-03-18 20:22:10.888 5039-5077/ D/EGL_emulation: eglMakeCurrent: 0xa17055a0: ver 2 0 (tinfo 0xa1703510)
2019-03-18 20:22:10.902 5039-5046/ I/zygote: Do full code cache collection, code=243KB, data=173KB
2019-03-18 20:22:10.903 5039-5046/I/zygote: After code cache collection, code=239KB, data=134KB
2019-03-18 20:22:10.918 2208-5079/? V/FA-SVC: Logging event: origin=auto,name=user_engagement(_e),params=Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=14804, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-657156986720031714}]
2019-03-18 20:22:10.936 2208-5079/? V/FA-SVC: Saving event, name, data size: user_engagement(_e), 68
2019-03-18 20:22:10.937 2208-5079/? V/FA-SVC: Event recorded: Event{appId='FA......', name='user_engagement(_e)', params=Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=14804, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-657156986720031714}]}
2019-03-18 20:22:10.938 2208-5079/? V/FA-SVC: Upload scheduled in approximately ms: 2445285
2019-03-18 20:22:10.938 2208-5079/? V/FA-SVC: Cancelling job. JobID: 812057698
2019-03-18 20:22:10.943 2208-5079/? V/FA-SVC: Scheduling upload with GcmTaskService
2019-03-18 20:22:10.943 2208-5079/? V/FA-SVC: Scheduling task with Gcm. time: 2445285
2019-03-18 20:22:10.950 2208-5079/? V/FA-SVC: Background event processing time, ms: 33
2019-03-18 20:22:10.961 2208-5079/? V/FA-SVC: Logging event: origin=auto,name=screen_view(_vs),params=Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=-657156986720031714, firebase_screen_class(_sc)=Transaction, firebase_screen_id(_si)=-657156986720031713}]
2019-03-18 20:22:10.967 2208-5079/? V/FA-SVC: Saving event, name, data size: screen_view(_vs), 96
2019-03-18 20:22:10.967 2208-5079/? V/FA-SVC: Event recorded: Event{appId='FA...', name='screen_view(_vs)', params=Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=-657156986720031714, firebase_screen_class(_sc)=Transaction, firebase_screen_id(_si)=-657156986720031713}]}
2019-03-18 20:22:10.968 2208-5079/? V/FA-SVC: Upload scheduled in approximately ms: 2445255
2019-03-18 20:22:10.970 2208-5079/? V/FA-SVC: Cancelling job. JobID: 812057698
2019-03-18 20:22:10.973 2208-5079/? V/FA-SVC: Scheduling upload with GcmTaskService
2019-03-18 20:22:10.973 2208-5079/? V/FA-SVC: Scheduling task with Gcm. time: 2445255
2019-03-18 20:22:10.975 2208-5079/? V/FA-SVC: Background event processing time, ms: 14
2019-03-18 20:22:11.169 5039-5039/ W/ClassMapper: No setter/field for time found on class .modelCredit
2019-03-18 20:22:11.169 5039-5039/ W/ClassMapper: No setter/field for Cname found on class .modelCredit
2019-03-18 20:22:11.204 5039-5039/ W/ClassMapper: No setter/field for time found on class FA.modelDebit
2019-03-18 20:22:11.204 5039-5039/ W/ClassMapper: No setter/field for Cname found on class .modelDebit
2019-03-18 20:22:11.207 5039-5046/ I/zygote: Do partial code cache collection, code=240KB, data=149KB
2019-03-18 20:22:11.208 5039-5046/ I/zygote: After code cache collection, code=240KB, data=149KB
2019-03-18 20:22:11.208 5039-5046/ I/zygote: Increasing code cache capacity to 1024KB
2019-03-18 20:22:11.227 5039-5039/ W/ClassMapper: No setter/field for time found on class FA.modelDebit
2019-03-18 20:22:11.227 5039-5039/ W/ClassMapper: No setter/field for Cname found on class FA.modelDebit
2019-03-18 20:22:11.251 5039-5039/ W/ClassMapper: No setter/field for time found on class ......modelDebit
2019-03-18 20:22:11.251 5039-5039/... W/ClassMapper: No setter/field for Cname found on class ........modelDebit
2019-03-18 20:22:11.271 5039-5039/..... W/ClassMapper: No setter/field for time found on class ........modelDebit
2019-03-18 20:22:11.271 5039-5039/....... W/ClassMapper: No setter/field for Cname found on class .......modelDebit
2019-03-18 20:22:11.288 5039-5039/....... W/ClassMapper: No setter/field for time found on class .........modelDebit
2019-03-18 20:22:11.288 5039-5039/....... W/ClassMapper: No setter/field for Cname found on class ..........modelDebit
2019-03-18 20:22:11.303 5039-5039/......... W/ClassMapper: No setter/field for time found on class ............modelDebit
2019-03-18 20:22:11.303 5039-5039/.......... W/ClassMapper: No setter/field for Cname found on class ............modelDebit
2019-03-18 20:22:11.316 5039-5039/.......... W/ClassMapper: No setter/field for time found on class ........modelDebit
2019-03-18 20:22:11.316 5039-5039/........ W/ClassMapper: No setter/field for Cname found on class ........modelDebit
2019-03-18 20:22:11.319 5039-5046/.......... I/zygote: JIT allocated 56KB for compiled code of void android.view.View.<init>(android.content.Context, android.util.AttributeSet, int, int)
2019-03-18 20:22:11.350 5039-5039/........... I/TextView Start: here it start adding values to text feild

Freagment Class

[import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class Debit extends Fragment {

    private View debitView;
    private RecyclerView debitRecyletList;
    private DatabaseReference debitRef;
    private FirebaseAuth firebaseAuth;

    public Debit() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        debitView= inflater.inflate(R.layout.fragment_debit, container, false);

        firebaseAuth=FirebaseAuth.getInstance();

        debitRecyletList = (RecyclerView) debitView.findViewById(R.id.debit_recyclerView);
        debitRecyletList.setHasFixedSize(true);
        debitRecyletList.setLayoutManager(new LinearLayoutManager(getContext()));
        debitRef = FirebaseDatabase.getInstance().getReference("debit");
        debitRef.keepSynced(true);

        return debitView;
    }

    @Override
    public void onStart() {
        super.onStart();

        FirebaseRecyclerOptions options1 = new FirebaseRecyclerOptions.Builder<modelDebit>()
                .setQuery(debitRef, modelDebit.class)
                .build();

        FirebaseRecyclerAdapter<modelDebit, debitViewHolder> adapter1 = new FirebaseRecyclerAdapter<modelDebit, debitViewHolder>(options1) {
            @Override
            protected void onBindViewHolder(@NonNull final debitViewHolder holder1, int position, @NonNull modelDebit model1) {

                debitRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if(dataSnapshot.exists()) {

                            String workerNmeDebit1 = dataSnapshot.child("wName").getKey().toString();
                            String billDateDebit1 = dataSnapshot.child("date").getKey().toString();
                            String billNoDebit1 = dataSnapshot.child("bill_no").getKey().toString();
                            String billAmntDebit1 = dataSnapshot.child("bill_amt").getKey().toString();
                            String workerComsnDebit1 = dataSnapshot.child("comm").getKey().toString();

                            Log.i("TextView Start","here it start adding values to text feild");

                            holder1.bill_amtD.setText(billAmntDebit1);
                            holder1.bill_NoD.setText(billNoDebit1);
                            holder1.dateD.setText(billDateDebit1);
                            holder1.nameD.setText(workerNmeDebit1);
                            holder1.commD.setText(workerComsnDebit1);

                        }
                        else {
                            Toast.makeText(getContext(), getString(R.string.error_msg), Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });

            }

            @NonNull
            @Override
            public debitViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup1, int i) {

                View view1 = LayoutInflater.from(viewGroup1.getContext()).inflate(R.layout.debitdesign, viewGroup1, false);
                debitViewHolder viewHolder1 = new debitViewHolder(view1);
                return viewHolder1;

            }
        };

        debitRecyletList.setAdapter(adapter1);
        adapter1.startListening();

    }

    public static class debitViewHolder extends RecyclerView.ViewHolder{

        TextView nameD, dateD, bill_amtD,  bill_NoD, commD;

        public debitViewHolder(@NonNull View itemView1) {
            super(itemView1);

            nameD = itemView1.findViewById(R.id.debit_workerName);
            dateD = itemView1.findViewById(R.id.debit_date);
            bill_amtD = itemView1.findViewById(R.id.debit_commission);
            bill_NoD = itemView1.findViewById(R.id.debit_billNumber);
            commD = itemView1.findViewById(R.id.debit_commission);

        }
    }
}

database view
Comment: Hello @aseebp , may I take a look at your database?
Comment: yes offcource, i have edited my question with image in it.Ihave given description as "database view". Thank you for helping me.
Answer: From your database, you seem don't put the Cname, time, in the model class.
I already updated your model class.
public class modelDebit {

private String wName;
private String bill_no;
private String bill_amt;
private String date;
private String comm;
private String Cname;
private String time;

public modelDebit() {
}

public modelDebit(String wName, String bill_no, String bill_amt, String date, String comm, String cname, String time) {
    this.wName = wName;
    this.bill_no = bill_no;
    this.bill_amt = bill_amt;
    this.date = date;
    this.comm = comm;
    Cname = cname;
    this.time = time;
}

public String getwName() {
    return wName;
}

public void setwName(String wName) {
    this.wName = wName;
}

public String getBill_no() {
    return bill_no;
}

public void setBill_no(String bill_no) {
    this.bill_no = bill_no;
}

public String getBill_amt() {
    return bill_amt;
}

public void setBill_amt(String bill_amt) {
    this.bill_amt = bill_amt;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getComm() {
    return comm;
}

public void setComm(String comm) {
    this.comm = comm;
}

public String getCname() {
    return Cname;
}

public void setCname(String cname) {
    Cname = cname;
}

public String getTime() {
    return time;
}

public void setTime(String time) {
    this.time = time;
}
}

After that, change the your databaseReference from this:
 debitRef = FirebaseDatabase.getInstance().getReference("debit");

become this:
 debitRef = FirebaseDatabase.getInstance().getReference().child("debit");

Next, change the FirebaseRecyclerAdapter to this.
 FirebaseRecyclerAdapter<modelDebit, debitViewHolder> adapter1 = new FirebaseRecyclerAdapter<modelDebit, debitViewHolder>(options1) {
            @Override
            protected void onBindViewHolder(@NonNull final debitViewHolder holder1, int position, @NonNull modelDebit model1) {

            String workerNmeDebit1 = model1.getwName();
            String billDateDebit1 = model1.getDate();
            String billNoDebit1 = model1.getBill_no();
            String billAmntDebit1 = model1.getBill_amt();
            String workerComsnDebit1 = model1.getComm();

            holder1.bill_amtD.setText(billAmntDebit1);
            holder1.bill_NoD.setText(billNoDebit1);
            holder1.dateD.setText(billDateDebit1);
            holder1.nameD.setText(workerNmeDebit1);
            holder1.commD.setText(workerComsnDebit1);

        }
    }

Comment: @aseebp you are welcome. you can tick 'right' at this answer. :)


How to use existing decorators in Zend Framework?

Question: Following code:
$this->addElement('text', 'email', array(
    'label' => 'Your email address:',
));

$this->addElement('submit', 'submit', array(
    'label' => 'Sign Guestbook',
));

produces following HTML:
<form enctype="application/x-www-form-urlencoded" action="" method="post">

            Your email address:

            <input type="text" name="email" id="email" value="" />

            <input type="submit" name="submit" id="submit" value="Sign Guestbook" />

</form>

I know, I can write my own decorators, but I would like to know, how to use existing decorators, to create following HTML:
<form enctype="application/x-www-form-urlencoded" action="" method="post">

        Your email address:
        <input type="text" name="email" id="email" value="" class="my_class" />

        <input type="submit" name="submit" id="submit" value="Sign Guestbook" class="my_class" />

</form>

No
,
,
, added class attribute.
For example, I know, how to remove surrounding
 tag:
$this->addDecorator('FormElements')
     ->addDecorator('Form');

Are other changes possible without writing custom decorators?
Answer: You can use the HtmlTag decorator and pass which tag to use as a parameter.
All available decorators are listed here: http://framework.zend.com/manual/en/zend.form.standardDecorators.html
Answer: This (append this array to your parameters array, which now consists of only one label option) should help with your email field:
'class' => 'my_class',
'decorators' => array(
    'ViewHelper',
    'Errors',
    'Label',
    array('HtmlTag', array('tag' => 'div'))
)

And the same without Label - for submit.
Comment: Heh, that's almost exactly the same as here: http://framework.zend.com/manual/en/zend.form.elements.html#zend.form.elements.custom


Speaker wires to outside covered deck

Question:
If the picture loads you should be able to see what I'm talking about. I'm looking to move the 2 speakers that are mounted to the back of my garage over to the covered part of my deck. I would like to run them directly over from where the speakers are mounted now to the top of the post on the deck. Running them below ground is not an option. Distance is approximately 6'. Thought of maybe mounting a plastic pvc box at both ends with the plastic flex conduit glued between them. I don't want anything rigid to allow for movement of the different structures. Any suggestions or comments would be appreciated
Comment: When you say "plastic flex conduit", are you talking about LFNC or ENT?
Comment: If your thinking about this flex conduit flying in the air from the current location to the roofed portion just don't do it.  Is the roofed part freestanding completely?
Comment: I'm not sure what type of flex it is and yes the roof is freestanding.
Answer: Conduit's not what you want here
Flexible conduit (of any type) can't be run between buildings like this as it violates the support rules (you need supports every 3', and you can't have that here).
Instead, what you want to do is run a galvanized, aluminum-clad, or copper-clad steel messenger wire between the two structures, and then use field lashings or cable saddle rings to attach an outdoor rated (sunlight resistant) CL2 or CL3 speaker cable to it.  This falls under Article 396 of the NEC, and in particular the line in table 396.10(A) that states "Other factory-assembled, multiconductor control, signal, or power cables that are identified for the use" are allowed for messenger-supported wiring installations.
It is important to provide enough slack in the messenger and cable to let the messenger adopt a natural catenary curve (instead of having it taut between structures or excessively slack/drooping, check a sag and tension chart for details) in order to take up structural motion and wind deflections, as you indicate, and also to attach the cable to the messenger in a way that will withstand the test of time (usually, a thinner lashing wire is wound around the combination of cable and messenger, or the cable is threaded through cable saddles that have been attached to the messenger wire).  You'll also need to ground the messenger wire itself at at least one end (probably using a split bolt on the messenger with a ground wire or Bare Armored Ground cable going back to a nearby mains box that a ground can be tapped at).

Speaker wires to outside covered deck


Scroll - Hide Content

Question: I'm searching for a way to Hide the content when scrolled. Let me explain.
This from the Treehouse Website:
Normal Content:

When Scrolled:

As you see the content hides and the line appears. Go Check it out here
Has anybody an Idea how they did this?
Comment: unclear what you're asking
Comment: I'm asking how they achieved this Style, that the scrolling hides the content and slides into this line
Answer: This is because on scroll down of div
They are adding a class shadowy to a

     .heading-pocket.shadowy {
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); //cause of the shadow on top
        transition-duration: 0.2s;
    }

On scrolling back to top they are removing the class shadowy
Comment: They are adding the class via JS right? could you give me an example of the code ?
Comment: This link would help you http://stackoverflow.com/questions/12558311/add-remove-class-with-jquery-based-on-vertical-scroll
Comment: Helped a lot !! Thanks @Sanjeev
Answer: It's called CSS. You want position:fixed on whatever "header" you want to overlay the content.
Comment: I actually didn't down voted you. I know it's CSS Tyler, but this specific Styling of the Scroll Hide is pretty awesome and i'm searching for a way to replicate it / and learn.
Comment: I agree the styling is very cool. If utilized right it can work wonders... Except it's rather over used now since bootstrap specifically uses this in its navbars. I can't speak for the other frameworks but position:fixed is nice. Use it almost as use would an absolute positioned element using the top, left, right, bottom elements
Comment: I'm not talking about the position, i'm talking about the Transition happening when scrolling.

Scroll - Hide Content


What does "an immersed sub manifold is in general not a submanifold as a subset" mean?

Question: According to Wikipedia https://en.wikipedia.org/wiki/Submanifold :
An immersed submanifold of a manifold M is the image S of an immersion map f: N → M; in general this image will not be a submanifold as a subset, and an immersion map need not even be injective (one-to-one) – it can have self-intersections.
I am not understanding what this last sentence means. Could someone please elaborate on what "submanifold as a subset" means?
Comment: The usual notion of submanifold is embedded submanifold (hence the fact that you say "immersed submanifold" and not just "submanifold"). Look for instance at the "intrinsic" definition here : https://en.wikipedia.org/wiki/Submanifold#Embedded_submanifolds
Answer: For example the sign $\infty$ (or $8$ if you prefer) is the image of an immersion $S^1 \to\Bbb R^2$, but it is not a submanifold, because the cross point has no neighborhood homeomorphic to $\Bbb R^n$ in the subspace topology (though all other points have, with $n=1$).
Answer: The thing is that in general, even a 1-1 immersion (one for which no self-intersections take part) can present even more horrendous problems. What the "... submanifold as a subset ..." part means is that the image of a 1-1 immersion may have a subspace topology different than the one induced by the immersion, i.e the 1-1 immersion may not be a homeomorphism onto its image, which is one of the equivalent characterizations of a regular or embedded submanifold.
So, the problem is a little more subtle than the thing with the self-intersections.
As an example, if you embedd $\mathbb{R}$ into $\mathbb{R}^2$ injectively as in Figure 1-9 pp. 16 of $\textit{Differential Topology}$, by Guillemin & Pollack, you certainly don't have self-intersections, but your immersion fails to be homeomorphism because it is not a proper map. Just take a compact neighborhood around the special point and its preimage is not compact.
Another well-known example is the line with irrational slope in the torus, as a 1-1 immersion $\mathbb{R}\rightarrow \mathbb{T}^2$ (Example 5.3 pp. 95 in $\textit{Introduction to Smooth Manifolds}$ by J. M. Lee), where the image of the 1-1 immersion is even dense in the ambient!


Mixing promotion with value

Question: I am developing a product to help people book cabs easier / faster. Once the cab is booked I was hoping to provide a safety feature to it by allowing the customer to send a sms to a family member. The sms would read as

Hello. This message is from Taxeeta. Neha is traveling in vehicle number MH12 12 1234, from Pune, Airport at 12:20am with Suraj driver with driving license number DL 12 4579821. Terms and Conditions Apply. Thankyou Taxeeta

Now, I also need to do promotions and some kind of share feature to allow people to make the product more famous.
So I was thinking, why not do some kind of multi-level marketing, where if they share this app on facebook, sms and twitter I will provide them with more free time.

Hello. Neha is traveling in vehicle number MH12 12 1234, from Pune, Airport at 12:20am with Suraj driver with driving license number DL 12 4579821. Terms and Conditions Apply. Install and use Taxeeta, promotion code XYZ, to help Neha use the product without any charge 5 more times. Thankyou Taxeeta

The Question
Mixing a value feature with promotion. Does it give good feel to the app ? From a developers stand point I just want to give value to the customer. From marketing point of view its important to also promote at every touch point. I am looking for some basic advice on pros and cons for mixing thought processes.
Summary of the answers

Keep it shorter
Separate promotion from value
Make promotion personal

With the 160 character limit, and the above advice, how does this sound ? Does it sound personal ? Am I keeping promotion separate from value ?
Total 154 characters, also all variable text is removed. I am sure next-of-kin knows where Neha is, and what time approximately she is about to travel.

Neha travels with Suraj Lalwani(MH12AB1234,DL103214569870,9876543210).T&CApply.Promotion(code XYZ12345):Install Taxeeta and help Neha travel safely again.

Variable text in this message are the names. I can reserve 13 characters for customer and 10 characters for drivers name.
Comment: Is it really a **safety** feature (as in, to make sure the customer doesn't get raped or robbed)? Why not give the customer the opportunity to send the information to her relatives on her own? Why should she trust you with NNK numbers if you don't trust your drivers?
Comment: Provided you don't spam the customer's next-of-kin, I can see this as a useful feature. You could cut all the stuff about terms and conditions (it's not an ad, right? :P) , and only leave "Sent through Taxeeta". Let the happy customers spread the word...
Comment: 3. Make promotion personal
Comment: Good point, the drivers know that the information has been sent to the their relatives. So yes it is a safety feature. I construct the sms so that the customer does not have to type it out. And yes, the customer will register a number (relative or friend) to send this information to.
Comment: Well, the sms is going from the customers address book, only by their next-of-kin permission, only when they travel.
Comment: Do you recon a good chunk of your user base will be using smart phones with internet connectivity?
Comment: Yes, all my customers will be user base using smart phones. No websites.
Answer: We can advertise the app by multi-level-marketing, but the message format which you have posted doesn't looks proper.
The user is obviously interested in the main message. The promotion message or marketing message can be posted, no doubt, but in proper format. Also the message should be a short one, like : Share this app for exciting offers
Hope this will help you.
Comment: I generally agree with the "short message", but @Siddharth's example is compelling: an immediate, tangible benefit can set you apart from the general "exiting offers" which is a promise everyone makes.
Comment: @peterchen, Check out the latest version to keep it under 160 characters. Does it beat your feel for a tangible benefit ? Does it still feel good / safe ?
Comment: Yes, looks good to me.  --- I'm not sure if the character limit is an issue for you (modern phones do split and re-combine longer messages). OTOH, you might replace the "MH12AB1234,DL103214569870,9876543210" with e.g. "taxee.ta/"  and have the details online. But then, this might have reliability, traceability and accessibility issues as I presume your "target demographic" doesn't have ubiquitous internet access.
Answer: Con: Receivers may perceive the message as marketing, reducing their trust in its information.
Still, the method is common and not wrong in principle. The balance between content and marketing depends on your target audience and your (company's) values. For me, the combination would be ok, if:

there is a clear distinction between the content and the advertisement, content is more prominent
you do not artificially increase volume to publish more ads
(e.g. your sample message would be ok, but sending messages when Neha is about to start, just started, and is about to arrive would be spam)

Now, SMS doesn't allow an easy distinction. I would suggest the following minor modifications to your example:

Hello. Neha is traveling in vehicle number MH12 12 1234, from Pune, Airport at 12:20am with Suraj driver with driving license number DL 12 4579821. Thank you, Taxeeta. Terms and Conditions Apply. Promotion: Install and use Taxeeta, promotion code XYZ, to help Neha use the product without any charge 5 more times.

Move the "Thank you" forward to clearly indicate the end of the "personal" message, and introduce the promotion with a clear indicator saying so. ("Promotion:")
Answer: An SMS is limited to 160 symbols. Longer messages are divided on several separate SMSs and I hate them because the text seems to be broken and conserning possible time lags between SMSs and short-term memory constraints I sometimes loose sense of such messages. So be aware of possible bad experience.
I recommend send separate messages for informing and promotion. But last should be more personal to not be perceived as clear advert. For example, "Help Neha to travell more...".
This is just an example, you should carefully choose micro-content.
Comment: Did not think about the limit.. Neat..

Mixing promotion with value


Percentage Problem: Can someone help me with finding the right percentage?

Question: In this article, we have the data that police officers have around 50 million interactions with the public and 1000 Fatal shootings but later they say "... those interactions led to fatal shootings about 0.00002 percent of the time."
How exactly does it work? Shouldn't it be:
(1000/50Mil)*100 = 0.002% instead?
Comment: Your math is clearly accurate, and the discrepancy may be explained by the writer being intentionally or unintentionally in error.  mathSE probably not the site for debating non-math issues.
Comment: @user2661923 Thank you. I personally was just concerned with the mathematics of it and not the actual political debate. But it's good to know my math was accurate. Cheers!
Answer: $1000$ over $50000000$ is $0.00002$, but just like my students do, they forget, hopefully just because of math ignorance, that percentage is over $100$
It's like saying that $150$ over $300$ students are girls, thus the percentage of girls is $0.5\%$
The correct percentage of fatal shootings is $0.002\%$, like you said correctly in your post.
Remark. I find tons of math mistakes on the papers. The most recent? On a national famous journal  in an article about smoking they said that "[...] yearly  17 millions euro go up in smoke." A mistake is a MISTAKE if you miss 3 orders of magnitude...


UIBarButtonItem setBackButtonTitlePositionAdjustment doesn't work

Question: Updated
I want to change offset between Arrow and Text in Back Button in Navigation Bar. It works just fine until I set
UINavigationBar.appearance().standardAppearance = newAppearance
Here is the full code:
        let appearance = UINavigationBar.appearance()
        let standardAppearance = UINavigationBarAppearance()
        standardAppearance.configureWithOpaqueBackground()
        standardAppearance.backgroundColor = someColor
        standardAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor]
        standardAppearance.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor]
        standardAppearance.shadowColor = navigationShadowColor

        // if remove theses 2 line, offset code works!!!
        appearance.standardAppearance = standardAppearance
        appearance.scrollEdgeAppearance = standardAppearance

        // code to set offset
        UIBarButtonItem
            .appearance()
            .setBackButtonTitlePositionAdjustment(
                UIOffset(horizontal: -20, vertical: 0),
                for: .default)

Comment: Didn't you set/use `UINavigationBar.prefersLargeTitles`, because above appearance works only for standard titles?
Comment: @Asperi I checked in code and see that it is set in somewhere, but then it's turned off on viewDisappear, but I'll try turning it off everywhere (I'll do it today or tomorrow). Could you please post that as an answer, so it that helps I'm gonna mark your answer as correct ?
Comment: hack - Instead you add some space in your image at a side. Or put needed spaces in text.
Comment: I need negative spacing
Comment: I updated the code, because I found which line causes the issue, but don't know how to fix it "appearance.standardAppearance = standardAppearance"
Comment: I've got your situation, please see worked solution in answer
Answer: UINavigationBar.appearance() when specified overrides everything and has own settings for everything, so you need to configure offset via its own properties, like
...
standardAppearance.backButtonAppearance.normal.titlePositionAdjustment =
    UIOffset(horizontal: -20, vertical: 0)

appearance.standardAppearance = standardAppearance
...

so the part of UIBarButtonItem.appearance() not needed - just remove it
Comment: I updated the question text, because I found which line causes the issue, could you please check one more time?
Comment: Man... I've lost 3 hours to solve this. Thank you so much!
Answer: You need to set TitlePositionAdjustment in app delegate method "didFinishLaunchingWithOptions" then it will be work.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    UIBarButtonItem
    .appearance()
    .setBackButtonTitlePositionAdjustment(
        UIOffset(horizontal: -20, vertical: 0),
        for: .default)
    return true
}

Comment: I think I'm doing just the same but not in didFinishLaunchingWithOptions, I'm gonna check that in didFinishLaunchingWithOptions today or tomorrow
Comment: Yes, you are doing same, but you need to put that code in AppDelegate.
Comment: sure, I'll check that and reply here, thank you for a suggestion
Comment: no, it doesn't help. And in general it doesn't matter when in the app you set Appearance But if you set it when UI Appeared, you need to pop (dismiss) this screen, so Appearance will be applied
Comment: I updated the question text, because I found which line causes the issue, could you please check one more time?
Answer: This is my code for a custom back button
func addBackButton() {
    let backButtonView = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 44))
    let imageView = UIImageView(image: UIImage(named: "back-arrow"))
    imageView.frame = CGRect(x: -5, y: 11, width: 12, height: 22)
    imageView.image = imageView.image!.withRenderingMode(.alwaysTemplate)
    imageView.tintColor = .fiGreen()
    let label = UILabel(frame: CGRect(x: 10, y: 0, width: 60, height: 44))
    label.textColor = .fiGreen()
    label.text = NSLocalizedString("back", comment: "Back")
    backButtonView.addSubview(imageView)
    backButtonView.addSubview(label)
    backButtonView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backButtonClicked)))
    let barButton = UIBarButtonItem(customView: backButtonView)
    navigationItem.leftBarButtonItem = barButton
}

I think you can modify it to have the offset that you need.
Comment: I don't want to use leftBarButtonItem (it has different offset from the edge), I don't want to use UIBarButtonItem with custom view (because for different iOS versions one needs to fix offset difference between System back button and custom), I just need to set offsets of backBarButtonItem
Comment: I updated the question text, because I found which line causes the issue, could you please check one more time?


How to add missing maven libraries to Jetty

Question: I am trying to launch a maven project, that I always launched manually in Tomcat, in Jetty. For this I am using the maven-jetty-plugin.
When executing jetty:run It seems like everything goes fine, except for the fact that Jetty does not find the dependencies defined in the POM.
If I run jetty:war, the war is built properly, using the dependencies, so that works. Why is jetty:run not including my libraries in WEB-INF/lib (or anywhere else)?
Comment: I am also having this problem, using Maven 2 with jetty-maven-plugin 7.5.2. If I use jetty:run, the application gives ClassNotFoundException and NoClassDefFoundError. If I use jetty:run-war, everything is fine. Also, if I copy the dependency to the plugin's dependency list (so that it's on the container's classpath), jetty:run works. My dependencies are on third-party artifacts that Maven has already downloaded to my local repo.
Would love to hear from anyone who knows why it behaves this way.
Comment: What is the "scope" of missing dependencies?
Comment: @BenoitCourtine, I defined no scope.
Answer: If you need a dependency for Jetty which resides somewhere other than the main Maven repo, add the following:
<pluginRepositories>
    <pluginRepository>
        <id>repo-id</id>
        <url>http://my_other_repo.edu</url>
    </pluginRepository>
</pluginRepositories>

I don't believe Jetty will use the existing repositories in your POM.
Answer: It really depends on the dependencies you have defined. For example, if you have defined a JNDI resource in your jetty.xml file, you will need the jetty-plus dependency. However, you will need this dependency for the execution of the plugin only. Plugins can have <dependencies/> and that is where you need to define it.
If you have a list of Jetty-specific classes that the plugin can't find, the best way to look up the dependencies is to use a site like www.jarvana.com.
Comment: I dont use any jetty specific classes. I migrated from tomcat, so I have absolutely nothing jetty specific. I do not hava a jetty.xml either...
Answer: By 'dependencies', do you mean other projects?
If so, you will need to install (mvn:install) these into the local repository before jetty:run will see them.
It's possible that jetty:war is packaging them and placing them into the lib folder without installing into the local repo.
Answer: For me I had one .jar file in my repo that was not getting picked up by Eclipse.  I didn't figure out how to fix it in Eclipse, so my work around was to ...

Add a duplicate of the .jar file to the repo under a different groupId (different path under ~/.m2) using this command:
mvn install:install-file -Dfile=dhcp4java-1.0.0.jar -DgroupId=a_abc.hack -DartifactId=dhcp4java -Dversion=1.0.0 -Dpackaging=jar
Reference the new groupId , which requires only to update this entry for the dependency in pom.xml :
<groupId>a_abc.hack </groupId>


Sliding overlay panel that works with bootstrap 3 css

Question: I've been endlessly searching for a sliding overlay panel using jquery that doesn't destroy my bootstrap 3 css file. But I can't find any. I need a panel that is like a form, has dropdowns, selectable grids, input boxes, etc.. and anything I do on this menu panel will refresh the content panel automatically; but in my case it's not really considered a "menu", its just a sliding or pop-out form that you can fill out.
I've searched this site:
http://designhuntr.com/15-slide-panel-jquery-plugins/
And not a single one gave me what I wanted. I need a sliding panel that comes from the left, filled up with forms (like bootstrap accordion, select2 dropdown).
The first link gave exactly what I wanted, but rendering the content of my bootstrap css came into heavy conflict and was rendered useless.
The most perfect example I was able to find is located here:
http://demos.jquerymobile.com/1.3.0-beta.1/docs/panels/#
When you click the overlay button; it does exactly what I needed in terms of functionality.
But using this library also conflicts with bootstrap. I've tried 5 different libraries, all ending in failure. It just seems that a simple idea such as this could have had some kind of leeway by now.
If anyone has had any kind of success, I'd love to hear it. Otherwise I'm all out of options  at this point.
[Edit 6/17/2014]
A big requirement for me is to have a button that is kept static, it doesn't move with the sliding panel. I didn't want the user to move the button every time the user slid a panel out. I also needed this functionality to exist for ie7+. I want to have more control over what is moving, want is sliding, the effects, everything. Not a total 100% full slide.
Answer: After exhausting my brain and time into this, found out that most 3rd party apps for sliding panels doesn't do cross browser support very well. Some says they do, but when you check out the demos, it clearly doesn't. So what I did was replicated the project by including jquery.ui and simply added in the features myself.
http://jqueryui.com/toggle/
I used toggle, with "drop" selected. This mimics the sliding in from the left side of the window. Works in IE7+ and chrome.
I made my div content as "position:fixed"; for my purposes I like this because I have control over whether I want to do an overlay or if I want my content to be pushed.
Then with that div content in place, I can then add an jquery's "animate" function and have it slide to whatever position I want.
https://api.jquery.com/animate/
In time, I'll create my own library that beats out everyone else's with as little css styling as possible. But for now, I just need to wrap my stuff up.
EDIT: 6/17/2014 - This was implemented almost a few days after I posted the answer up here
Here's my code I implemented using jquery ui:
mind you, twitter bootstrap doesn't interfere with this code since its purely used as css at this point.
components used:

A button for toggling the sliding, i gave it an id="button".
A div panel with id="effectMenu"

This is responsible for the menu sliding and fading away

A div panel with id="effectContent" (shown right next to effectMenu)

When the menu slides and fades, this slides into the empty space
When the menu slides and returns, this slides and allows the menu to come back

A hidden input box with id="positionOfEffect"

Used for determining where the content should slide to

A hidden input box with id="didContentSlide"

Holds a boolean value: true if content moved to new position, false if it went back to original state

So you get something like this:
<button type="button" id="button" class="btn btn-default btn-lg" />

        ...

        ...

<input id="positionOfEffect" type="hidden" />
<input id="didContentSlide" type="hidden" />

Now the jquery code:
$('body').on('click', '#button', function (e) {
    e.preventDefault();

    //position of the effect menu
    var positionOfEffectMenu = $("#positionOfEffectMenu").val();

    //gets the value of whether or not the content slide to the new position
    //true if it did, false if it returned back to the original position
    var didContentSlide = $("#didContentSlide").val();

    //starting position of everything, capture the current state at this point
    //this is the page load set up
    if (positionOfEffectMenu == "") {
        //mimic the behavior of md-col-4 (33.333333% of screen)
        $("#positionOfEffect").val((($(".row").width() * 0.33333333)));
        $("#didContentSlide").val(false);
        positionOfEffectMenu = $("#positionOfEffectMenu").val();
        didContentSlide = $("#didContentSlide").val();
    }

    /**
     *   How far we want the transition to occur for the sliding content.
     *   The divided by 2 means, we're only going to be moving half the
     *   distance of the menu's width while the menu disappears.
     *   In my page, this makes a very space-friendly behavior
     *   originally the menu is all the way to the far right, and I have content
     *   next to it if I'm bringing the menu out, I dont want the content
     *   page to swing all the way to where the menu is, I want it to move
     *   just a bit so that it can fill up the space and look good for the user
     *   to focus in on.
     */
    positionOfEffect = parseFloat(positionOfEffectMenu) / 2;
    didContentSlide = didContentSlide == "true"; //turns string to bool value

    //I disable my button as its sliding otherwise if the user frantically clicks
    //it will intercept the positions and hijack the animation
    //it gets re-enabled later in this code
    var $elt = $(this).attr('disabled', true);

    //begin the animation

    //Now.. move the effect content to the new position
    //or if it is already at the new position, move it back to where it was before
    $("#effectContent").animate({
        left: (!didContentSlide) ? "-=" + (positionOfEffect) + "px" : "+=" + (positionOfEffect) + "px"
    }, 500, function () {

    })
    //as the content is going in, drop the effectMenu out of the page
    //or if the content is going back out, bring the effectMenu into the page
    .queue(function () {
        $("#effectMenu").toggle("drop", {}, 500);
    }).dequeue();

    //this is for the button.. its re-enabled when everything stops moving
    setTimeout(function () {
        $elt.attr('disabled', false);
    }, 500);

    //update the value of whether or not the contents slid into the new position
    didContentSlide = (!didContentSlide);
    $("#didContentSlide").val(didContentSlide);

    //override the defaults of the button
    return false;
});


DirectX 11: Shader not creating world view matrix

Question: After coming across this problem here, where the the Entity::draw() call would not be displayed due to the vertex shader values returning 0 on multiplication with the world view matrix.

The problem was funneled to a faulty constant buffer input. However, after checking the values, I can't seem to understand the problem at hand. I pre-multiplied the World, View, and Projection matrices:
mWorld = XMMatrixIdentity();
mView = XMMatrixLookAtLH(Eye, At, Up);
mProjection = XMMatrixPerspectiveFovLH(XM_PIDIV2, 1.0, 0.0f, 1000.0f);
mWVP = mWorld*mView*mProjection;

mWVP
-0.999999940, 0.000000000,  0.000000000, 0.000000000
 0.000000000, 0.999999940,  0.000000000, 0.000000000
 0.000000000, 0.000000000, -1.00000000, -1.00000000
 0.000000000, 0.000000000,  5.00000000,  5.00000000

mWVP enters the constant buffer after being transposed:
WorldCB.mWorldVP = XMMatrixTranspose(mWVP);
DeviceContext->UpdateSubresource(MatrixBuffer, 0, NULL, &WorldCB, 0, 0);
DeviceContext->VSSetConstantBuffers(0, 1, &MatrixBuffer);

XMMatrixTranspose(mWVP);
-0.999999940, 0.000000000,  0.000000000, 0.000000000
 0.000000000, 0.999999940,  0.000000000, 0.000000000
 0.000000000, 0.000000000, -1.00000000,  5.00000000
 0.000000000, 0.000000000, -1.00000000,  5.00000000

Which looks OK, at least to me. Next my shader starts doing its thing, but here's where things get funky, checking the disassembly yields that when:
output.position = mul(position, WVP);
Vertex Shader:
00000000  dp4 o0.x, v0.xyzw, cb0[0].xyzw
00000001  dp4 o0.y, v0.xyzw, cb0[1].xyzw
00000002  dp4 o0.z, v0.xyzw, cb0[2].xyzw
00000003  dp4 o0.w, v0.xyzw, cb0[3].xyzw
00000004  mov o1.xyzw, v1.xyzw

For each multiplication, values return 0. And if output.position = position; Values are correct, and the box displays, but not inside the world transformation.
The full shader file below:
cbuffer ConstantBuffer:register(b0)
{
    matrix WVP;
}

struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VOut VShader(float4 position : POSITION, float4 color : COLOR)
{
    VOut output;
    output.position = mul(position, WVP); // position;
    output.color = color;

    return output;
}

float4 PShader(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
     return color;
}

Edit: Also noted that the Transpose of the World matrix equals zero:
ObjectSpace = m_Scale*m_Rotation*m_Translate;
mWVP = ObjectSpace*direct3D.mView*direct3D.mProjection;

LocalWorld.mWorldVP = XMMatrixTranspose(wWVP);

XMMatrixTranspose(wWVP) comes out:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

And is likely the problem. Any guesses as to why the transpose of a matrix would equal 0?
Answer: The near plane of the perspective projection must be some value larger than zero.  If it is zero, then the near plane is exactly where the camera is located, and everything in the scene converges to a single point.
Comment: Days have been lost from my life.


Java 1.7.0u45 redirects connections to localhost

Question: It seems that with the latest Java update, 1.7.0u45, my JNLP application that is supposed to connect to a server is instead forced to try and connect to localhost for some reason that I cannot quite seem to figure out.
I know that some other changes have been made, such as requiring the Permissions attribute in the manifest and some such things, which I'm currently trying to figure out a reasonable way to comply to, but I cannot find anything that ought to cause this behavior.
My code just does an ordinary Socket.connect call to a specific server, but what happens is that the connection is instead made to localhost. This only happens when the code is running in the JNLP client; not when I run it "manually" by starting the VM on it.
Does anyone know why this is?
Answer: At last, I managed to figure out what was happening. It was not, in fact, that connections as such were being redirected, but rather that the JNLP client has started blocking JNLP files that are not signed from setting system properties with certain names. Particularly, only properties whose names begin with jnlp are, it seems, guaranteed to be configurable by unsigned JNLP files.
The problem, therefore, was that I specified what server to connect to via a system property whose name did not begin with jnlp, and it then being blocked (since my JNLP file isn't signed) led to my program using its default server specification instead, being localhost.


Display plymouth on Ubuntu server 18.04

Question: I installed Ubuntu Server 18.04 and Budgie desktop on top as my desktop environment. I don't want to see the text running when I restart or shutdown.
I found out that in /boot/grub/grub.cnf I have:
quiet splash $vt_handoff

It works but after updating Grub it goes back to the default.
Answer: You are changing the compiled file rather than the source file. When sudo update-grub runs your changes to the compiled file are replaced by the source file.
The correct source file to edit is /etc/default/grub.
After saving /etc/default/grub changes then you need to run:
sudo update-grub

Comment: More a comment than an answer.
Comment: @A.B. Unless we can somehow close this question, it will keep popping up on the home page until it is answered. With your downvote this question may qualify to keep popping up on the home page from time to time because it doesn't have an upvoted answer. I'm not positive on this mind you... Still no matter how you look at it the answer must be correct. Also the user is unlikely ever to sign-on again to delete th question.

Display plymouth on Ubuntu server 18.04


Using SQL to send emails based on new entries in tables

Question: I'm looking for a way to send emails (or reminders/confirmations) to users who create a new record in a web application, which is then inserted into a table. Basically a dynamic way of sending emails.
I've been reading online about Triggers and DB mail and there seems to be alot of disadvantages going with this approach.
Does anyone have any recommendations on the best way to achieve this?
Flow: New Record Inserted into DB Table ->>> At this point the email address of the user who created the record in the application should receive a mail (basically a confirmation mail).
What I've tried already:
DB mail is already configured and working.
I've made the below Trigger (very basic) but from reading online using a trigger in this way will lead to load/performance issues of my DB.
But I'm on unsure on how to generate the emails and last record inserted.
CREATE TRIGGER [dbo].[INSERT_Trigger] ON [dbo].[Entity]

FOR INSERT
AS

EXEC msdb.dbo.sp_send_dbmail

   @profile_name = 'DBMail',

@recipients = 'email@example.com', ####Here I would need dyncamic emails based on what user enters the new record which are stored in the same table

@query = 'Select Description From Entity where 'Last inserted record'####Here I would need the last record for that user entered

@subject = 'Subject' ,

@Body = 'Message Body',

@importance = 'High',

Answer: IMHO this approach is a design flaw: the DB tier is something that should be one of the leaves of the tier tree. The fact that the MS SQL Server is actually an application server and has support for such things is a legacy, but I don't think that it should be used.
At first look:

you might need to switch to another RDBMS
your production environment might not support SMTP for any reason
your attempt to send the mail could fail for various reasons - resulting in user not being notified and never trying it again

Yes, indeed, you can use SQL Server even as a message bus but would not be an efficient one. This concept is actually dispatching events of "notification needed" kind. The event is implemented as insert and the trigger is the consumer. But the event is produced inside your application, in a higher tier. Why not reacting to it there? Or, use the database only as a queue: store the details there, but process them in a way where you have more control.
You have not told us about the application you are creating, but I would create a separate background task (the implementation could vary depending on the application design - can be an OS-level scheduled task, windows service, or a background worker in your application) that checks periodically for mails not yet sent, and tries to send them, storing the result in the record. Things might get of course more complicated depending on load. But this way you can retry, and you are certainly taking load of the DB server, but at least you have the possibility to do so.
Answer: I have a trigger that works as u asked
First insert records in temporary table from inserted table
Second, declare parameters that you need
Third, add a cursor in your trigger and get parameters that u need in cursor from temporary table
Inside trigger you can declare recipients as u needed to be, query, and other stuffs
CREATE TRIGGER Trigger  ON [Entity]
FOR INSERT
not for replication
AS

select ins.* into #temp from inserted ins

declare @Param1 integer, @Param2 integer
declare cursor forward only for
select Col1, Col2 from #temp order by Col1
open cursor
fetch next from cursor into @Param1, @Param2
while @@fetch status = 0
begin

declare @recipients varchar (max), @query varchar(max)

select @recipient = Col1 -- or whatever col contains the recipient address
from #temp
where Col1 = @Param1

select @query = description
from #temp
where Col2 = @Param2 -- or whatever condition give u the description for parameter

exec sp_send_dbmail
@profile_name = 'profile',
@recipients = @recipient
@subject = 'Subject' ,
@Body = @query,
@importance = 'High'

fetch next from cursor into @Param1, @Param2
end
close cursor
deallocate cursor

drop table #temp

--- note that the body can be formatted in html format, like bellow
declare @body varchar(max)
select @body = ''
select @body = @body+'Hello'+''
select @body = @body+'Here is the description:'+@query+''
select @body = @body+'Regards'
select @body = @body+''