Q: Tuning of mtry by caret returning strange value I tune the mtry parameter of randomForest using the train function from the caret package. There are only 48 columns in my X data, however train returns mtry=50 as the best value whereas this is not a valid value (>48). What is the explanation of that ?
> dim(X)
[1] 93 48
> fit <- train(level~., data=data.frame(X,level), tuneLength=13)
> fit$finalModel

Call:
 randomForest(x = x, y = y, mtry = param$mtry)
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 50

        OOB estimate of  error rate: 2.15%
Confusion matrix:
     high low class.error
high   81   1  0.01219512
low     1  10  0.09090909

It is even worse if I don't set the tuneLength parameter:
> fit <- train(level~., data=data.frame(X,level))
> fit$finalModel

Call:
 randomForest(x = x, y = y, mtry = param$mtry)
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 55

        OOB estimate of  error rate: 2.15%
Confusion matrix:
     high low class.error
high   81   1  0.01219512
low     1  10  0.09090909

I don't provide the data cause it is confidential. But there's nothing special in these data: each column is numerical or is a factor, and there are no missing value.

A: The apparent discrepancy is most likely[1] between the number of columns in your data set and the number of predictors, which may not be the same if any of the columns are factors. You used the formula method, which will expand the factors into dummy variables. For example:
> head(model.matrix(Sepal.Width ~ ., data = iris))
  (Intercept) Sepal.Length Petal.Length Petal.Width Speciesversicolor Speciesvirginica
1           1          5.1          1.4         0.2                 0                0
2           1          4.9          1.4         0.2                 0                0
3           1          4.7          1.3         0.2                 0                0
4           1          4.6          1.5         0.2                 0                0
5           1          5.0          1.4         0.2                 0                0
6           1          5.4          1.7         0.4                 0                0

So there are 3 predictor columns in iris but you end up with 5 (non-intercept) predictors.
Max
[1] This is why you need to provide a reproducible example. Often, when I get ready to ask a question, the answer becomes apparent while I take the time to write a good description of the issue.


Q: Including disturbance rejection in GEKKO MPC I am trying to implement an MPC algorithm using GEKKO MPC to compare against my own MPC implementation. I have managed to perform the set point changes without a problem however, when I try to include steps in a disturbance the controlled variable does not return to steady state (a value of zero for deviation variables). This would make me think that I need to include a command which allows feedback? I am unsure.
from gekko import GEKKO
import numpy
import matplotlib.pyplot as plt

t = numpy.linspace(0,300,100)
m = GEKKO(remote = False)
m.time = t
# Parameters

T1 = m.Param(value = 53.97272679974334)
T2 = m.Param(value = 48.06851424706475)
T3 = m.Param(value = 38.48651254747577)
T4 = m.Param(value = 31.018933652439845)
k1 = m.Param(value = 5.51)
k2 = m.Param(value = 6.58)
γ1bar = m.Param(value = 0.333)
γ2bar = m.Param(value = 0.307)
A1 = m.Param(value = 730)
A2 = m.Param(value = 730)
A3 = m.Param(value = 730)
A4 = m.Param(value = 730)
v1bar = m.Param(value = 60)
v2bar = m.Param(value = 60)

# Manipulated variable
v1 = m.MV(value=0, lb=0, ub=100)
v1.STATUS = 1
#v1.DCOST = 0.1
#v2.DMAX = 20

v2 = m.MV(value=0, lb=0, ub=100)
v2.STATUS = 1
#v2.DCOST = 0.1
#v2.DMAX = 20

γ1 = m.MV(value=0, lb=0, ub=1)
γ1.STATUS = 1
#γ1.DCOST = 0.1
#v2.DMAX = 20

γ2 = m.MV(value=0, lb=0, ub=1)
γ2.STATUS = 1
#γ2.DCOST = 0.1
#v2.DMAX = 20

d = numpy.ones(t.shape)
d[0:10] = 0

d22 = numpy.zeros(t.shape)

d1 = m.Param(name='d1', value=d)  # Disturbance
d2 = m.Param(name='d2', value=d22)  # Disturbance

m.options.CV_TYPE = 2 # squared error

# Controlled Variable
h1 = m.CV(value=0)
h1.STATUS = 1  # add the SP to the objective
h1.SP = 1    # set point
h1.TR_INIT = 1 # set point trajectory
h1.TAU = 1   # time constant of trajectory
h1.BIAS = 1
h1.FSTATUS = 1

h2 = m.CV(value=0)
h2.STATUS = 1  # add the SP to the objective
h2.SP = 0  # set point
h2.TR_INIT = 1 # set point trajectory
h2.TAU = 1     # time constant of trajectory
h2.BIAS = 1
h2.FSTATUS = 1

h3 = m.CV(value=0)
h3.STATUS = 1  # add the SP to the objective
h3.SP = 0     # set point
h3.TR_INIT = 1 # set point trajectory
h3.TAU = 1     # time constant of trajectory
h3.BIAS = 1
h3.FSTATUS = 1

h4 = m.CV(value=0)
h4.STATUS = 1  # add the SP to the objective
h4.SP = 0     # set point
h4.TR_INIT = 1 # set point trajectory
h4.TAU = 1     # time constant of trajectory
h4.BIAS = 1
h4.FSTATUS = 1

m.Equation(h1.dt() == -(1/T1)*h1 + (A3/(A1*T3))*h3 + (γ1bar*k1*v1)/A1 + (γ1*k1*v1bar)/A1)
m.Equation(h2.dt() == -(1/T2)*h2 + (A4/(A2*T4))*h4 + (γ2bar*k2*v2)/A2 + (γ2*k2*v2bar)/A2)
m.Equation(h3.dt() == -(1/T3)*h3 + ((1-γ2bar)*k2*v2)/A3 - k2*v2bar*γ2/A3 - (k1*d1)/A3)
m.Equation(h4.dt() == -(1/T4)*h4 + ((1-γ1bar)*k1*v1)/A4 - k1*v1bar*γ1/A4 - (k2*d2)/A4)

m.options.IMODE = 6 # control

m.solve(disp=False,debug = True)

A: Try setting h1.SP = 0 instead of 1 to set the objective to drive it back to 1. Also, these options are not needed if h4.TR_INIT = 0 to create a setpoint that is zero everywhere (not a reference trajectory).
h4.TAU = 1
h4.BIAS = 1
h4.FSTATUS = 1

I also added lower bounds of zero for each of the height CVs with lb=0. There is a move on v2 when the disturbance starts. It appears that the controller can't resolve this offset. Is this the correct response?

from gekko import GEKKO
import numpy
import matplotlib.pyplot as plt

t = numpy.linspace(0,300,100)
m = GEKKO(remote=False)
m.time = t

T1 = m.Param(value = 53.97272679974334)
T2 = m.Param(value = 48.06851424706475)
T3 = m.Param(value = 38.48651254747577)
T4 = m.Param(value = 31.018933652439845)
k1 = m.Param(value = 5.51)
k2 = m.Param(value = 6.58)
γ1bar = m.Param(value = 0.333)
γ2bar = m.Param(value = 0.307)
A1 = m.Param(value = 730)
A2 = m.Param(value = 730)
A3 = m.Param(value = 730)
A4 = m.Param(value = 730)
v1bar = m.Param(value = 60)
v2bar = m.Param(value = 60)

# Manipulated variable
v1 = m.MV(value=0, lb=0, ub=100)
v1.STATUS = 1
#v1.DCOST = 0.1
#v2.DMAX = 20

v2 = m.MV(value=0, lb=0, ub=100)
v2.STATUS = 1
#v2.DCOST = 0.1
#v2.DMAX = 20

γ1 = m.MV(value=0, lb=0, ub=1)
γ1.STATUS = 1
#γ1.DCOST = 0.1
#v2.DMAX = 20

γ2 = m.MV(value=0, lb=0, ub=1)
γ2.STATUS = 1
#γ2.DCOST = 0.1
#v2.DMAX = 20

d = numpy.ones(t.shape)
d[0:10] = 0

d22 = numpy.zeros(t.shape)

d1 = m.Param(name='d1', value=d)  # Disturbance
d2 = m.Param(name='d2', value=d22)  # Disturbance

m.options.CV_TYPE = 2 # squared error

# Controlled Variable
h1 = m.CV(value=0,lb=0)
h1.STATUS = 1  # add the SP to the objective
h1.SP = 0    # set point
h1.TR_INIT = 0 # set point trajectory
#h1.TAU = 1   # time constant of trajectory
#h1.BIAS = 1
#h1.FSTATUS = 1

h2 = m.CV(value=0,lb=0)
h2.STATUS = 1  # add the SP to the objective
h2.SP = 0  # set point
h2.TR_INIT = 0 # set point trajectory
#h2.TAU = 1     # time constant of trajectory
#h2.BIAS = 1
#h2.FSTATUS = 1

h3 = m.CV(value=0,lb=0)
h3.STATUS = 1  # add the SP to the objective
h3.SP = 0     # set point
h3.TR_INIT = 0 # set point trajectory
#h3.TAU = 1     # time constant of trajectory
#h3.BIAS = 1
#h3.FSTATUS = 1

h4 = m.CV(value=0,lb=0)
h4.STATUS = 1  # add the SP to the objective
h4.SP = 0     # set point
h4.TR_INIT = 0 # set point trajectory
#h4.TAU = 1     # time constant of trajectory
#h4.BIAS = 1
#h4.FSTATUS = 1

m.Equation(h1.dt() == -(1/T1)*h1 + (A3/(A1*T3))*h3 + (γ1bar*k1*v1)/A1 + (γ1*k1*v1bar)/A1)
m.Equation(h2.dt() == -(1/T2)*h2 + (A4/(A2*T4))*h4 + (γ2bar*k2*v2)/A2 + (γ2*k2*v2bar)/A2)
m.Equation(h3.dt() == -(1/T3)*h3 + ((1-γ2bar)*k2*v2)/A3 - k2*v2bar*γ2/A3 - (k1*d1)/A3)
m.Equation(h4.dt() == -(1/T4)*h4 + ((1-γ1bar)*k1*v1)/A4 - k1*v1bar*γ1/A4 - (k2*d2)/A4)

m.options.IMODE = 6 # control

m.solve(disp=True)

plt.subplot(3,1,1)
plt.plot(m.time,d1.value,'k-',label='Disturbance')
plt.ylabel('Disturbance'); plt.grid(); plt.legend()

plt.subplot(3,1,2)
plt.plot(m.time,h1.value,'r-',label='Height 1')
plt.plot(m.time,h2.value,'g--',label='Height 2')
plt.plot(m.time,h3.value,'b:',label='Height 3')
plt.plot(m.time,h3.value,'k--',alpha=0.5,label='Height 4')
plt.ylabel('CVs'); plt.grid(); plt.legend()

plt.subplot(3,1,3)
plt.plot(m.time,v1.value,'r-',label='MV 1a')
plt.plot(m.time,v2.value,'g--',label='MV 2a')
plt.plot(m.time,γ1.value,'b:',label='MV 1b')
plt.plot(m.time,γ2.value,'k--',alpha=0.5,label='MV 2b')
plt.ylabel('MVs'); plt.grid(); plt.legend()

plt.show()


Q: Is SSH public key need to be the same each time I do push/pull with git repository? I am just started using Git, so I apologize if it is a newbie question.
I am using two different machines to commit changes to remote Git repository on github.com. Do I need to use the same SSH public key (the one I mentioned for my repository on Github)?

A: No -- if you go to your GitHub accounts page, you can add as many SSH public keys as you want.


Q: Segmentation Fault p_thread with a possible race condition Issue: I created a linked list of Child thread TIDS and want to wait on all the  child tids to finish execution before I continue my main thread. Basically I have directory traversal (a directory is specified by the members of a given struct).  Every time I see a directory or file I create a new thread and put its threadID into the linked list. However when I traverse the linked list and call pthread_join I get a segmentation fault (core dumped) - I cannot understand why. I believe in may have to do with race condition but I am not sure. When I remove the pthread_join I no longer segfault however I don't get full traversal of directories within directories.

Program:
void *handy(void *arguments)
{
    static pthread_t threadA;
    threadA=pthread_self();
    handarg *thestruct=(handarg*)arguments;
    DIR *dp=opendir(thestruct->directory);
    DIR *outExist=opendir(thestruct->outputdirectory);
    if(outExist==NULL)
    {
        if((thestruct->outputdirectory = ""))
        {
            ;
        }
        else
        {
            printf("The outputdirectory doesnt exist, program terminated\n");
            exit(1);
        }
    }

    struct dirent *entry;  // has two important members (d-type)-tells me if its a directory (d-name) tells me current file name
    if(dp==NULL)
    {
        printf("directory doesnt exist: %s\n", thestruct->directory);
        exit(1);
    }
    NODE *head=NULL; //linked list
    NODE *ptr=(NODE*)malloc(sizeof(NODE));//node POINTER
    int count;

    while((entry=readdir(dp))!=NULL)
    {
        if(strcmp(entry->d_name,"..")==0||strcmp(entry->d_name,".")==0)
        {
            continue;
        }

        if((entry->d_type==DT_DIR))
        {
            unsigned int const sz1 = strlen(thestruct->directory);
            unsigned int const sz2 = strlen(entry->d_name);

            char *dnewname=(char *)malloc((sz1+sz2+2)*sizeof(char));

            memcpy(dnewname,thestruct->directory,sz1);
            memcpy(dnewname+sz1,"/",sizeof(char));
            memcpy(dnewname+sz1+1,entry->d_name,sz2);
            dnewname[strlen(dnewname)]='\0';

            pthread_t tid;

            handarg *current=(handarg*)malloc(sizeof(handarg));//malloc
            current->directory=dnewname;
            current->outputdirectory=thestruct->outputdirectory;
            current->column=thestruct->column;
            pthread_create(&tid,NULL,&handy,current);

            threadA=pthread_self();
            printf("The Filepath is: %s, The Parent TID = %ld, THE peer TID = %ld\n",dnewname, threadA, tid);
            NODE *newNode=(NODE*)malloc(sizeof(NODE));
            newNode->peerTid=tid;
            newNode->next=NULL;
            if(head==NULL)
            {
                head=newNode;
                ptr=newNode;
                //printf("THE TID I PUT INTO THIS NODE IS FUCK YOU FUCK YOU FUCK YOU %ld\n",ptr->peerTid);
            }
            else
            {
                ptr->next=newNode;
                ptr=newNode;
                //printf("THE TID I PUT INTO THIS NODE IS YAMAKA %ld\n",ptr->peerTid);

            }
            //and call wait on each of tids  for loop only exit if last tid is waiting on
        }

        if((entry->d_type==DT_REG))
        {
            char *filename = entry->d_name;
            int len = strlen(filename);
            const char *last_four = &filename[len-4]; //need to account for if filename is less than 4 characters
            if(strcmp(last_four,".csv")==0)
            {
                char *dnewname = (char*)malloc(sizeof(char)*(strlen(thestruct->directory)+strlen(entry->d_name)+2));
                char *slash = (char*)malloc(sizeof(char));
                strcpy(dnewname, thestruct->directory);
                strcpy(slash, "/");
                strcat(dnewname, slash);
                strcat(dnewname, entry->d_name);
                dnewname[strlen(dnewname)]='\0';

                pthread_t tid;
                handarg *current=(handarg*)malloc(sizeof(handarg));
                current->directory=dnewname;
                current->outputdirectory=thestruct->outputdirectory;
                current->column=thestruct->column;
                pthread_create(&tid,NULL,&handleFile,current);
                //count++;
                threadA=pthread_self();
                printf("The Filepath is: %s, The Parent TID = %ld, THE peer TID = %ld\n",dnewname, threadA, tid);
                NODE *newNode=(NODE*)malloc(sizeof(NODE));
                newNode->peerTid=tid;
                newNode->next=NULL;
                if(head==NULL)
                {
                    head=newNode;
                    ptr=newNode;

                //printf("THE TID I PUT INTO THIS NODE IS %ld\n",ptr->peerTid);
                }
                else
                {
                    ptr->next=newNode;
                    ptr=newNode;
                    //printf("THE TID I PUT INTO THIS NODE IS %ld\n",ptr->peerTid);
                }
            }
        }
    }

    printf("the thread produced %d threads\n", count);
    if(head==NULL)
    {
        printf("no child threads\n");
    }
    ptr=head;
    printf("\nthese are the items from the linkedlist\n\n");
    while (ptr!=NULL)
    {
        printf("%ld\n",ptr->peerTid);
        ptr=ptr->next;
    }
    printf("\n");
    ptr=head;
    while (ptr!=NULL)
    {
        threadA=pthread_self();
        printf("THE PEER THREAD %ld --------I AM THE THREAD %ld\n",ptr->peerTid,threadA);
        pthread_join(ptr->peerTid,NULL);
        printf("got here");
        ptr=ptr->next;
    }
    printf("\n");
    //return NULL;
}


Q: WPF Storyboards in Datatemplates Can you programmatically begin a storyboard that is within a datatemplate?


Q: How to trigger a searchDisplayController by a button? I was wondering is there any way to implement such UI features.
As we know when we dragged in a search bar and searchDisplay control in xcode 5, we are be given a set of search controls including a search bar and a searchDisplayController.
Instead of using the native search bar, I want to use a button to trigger the search display control like that one in the latest facebook app.
I have tried to delete the search bar. But the display control failed directly.
I have tried to insert the search bar inside the tableView (Which I don't know its correct or not)

- (void)viewDidLoad
{
   [self hideSearchBar];
}

- (void)hideSearchBar
{
    self.UISearchBar.hidden = YES;
     self.UISearchBar.bounds = CGRectMake(0, 0, 0, 0);
}

- (IBAction)SearchClicked:(UIButton *)sender {
    [self.searchDisplayController setActive:YES animated:NO];
    self.UISearchBar.hidden = NO;
}

- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
   [self hideSearchBar];
}

But the problem with it is:
When I cancel the search the scroll view is not return to its previous state. (There is a gap space where the hidden searchBar sits).
Instead of seeing this:

I want to see this when the cancel button is clicked in the search view.

How can I address this issue?
Can any body provide me with a better solution?
Thanks

A: So simple!
 -(void) searchBarCancelButtonClicked:(UISearchBar *)searchBar{
        [self.searchDisplayController setActive:NO animated:YES];
        self.navigationController popToViewController:UIViewControllerA animated:YES;
    }

A: Create a CGPoint based on the scrollview's original center.
In viewDidLoad() :
self.originalCenter = scrollView.center;

And when your user closes the searchbar:
- (void)hideSearchBar
    scrollView.center = self.originalCenter;

Where scrollView is whatever you've called your UIScrollView.

A: So finally instead of dragging a searchBar control into the storyboard.
I'm creating and destroying the searchBarControl on the fly.
-(void)initialiseSearch
{
    //Start
    searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

    searchBar.delegate = self;
    searchBar.showsCancelButton = YES;
    searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];

    searchDisplayController.delegate = self;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;

    [self.view addSubview:searchBar];

    searchBar.hidden = YES;
    [searchDisplayController setActive:NO animated:NO];

    //    [self.searchDisplayController.searchResultsTableView registerNib:[UINib nibWithNibName:@"CustomSearch" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"search"];
    //End
}

The method is called in the view did load.


Q: How to disable coffeescript on Rails 5 I started a new rails 5.1.4 project but I have forgotten to add --skip-coffee on rails new.
Is there a way to remove the coffeescript dependency without creating a new project?.

A: *

*Remove or comment out gem 'coffee-rails' from Gemfile.

*Change Javascript files that ends with .js.coffee to .js.

*Add config.generators.javascript_engine = :js to your application.rb.

*Make sure your tmp cache is cleared with rake tmp:cache:clear


Q: How to push data into widget using dashing dashboard I want to push numeric data from a file to my dashboard.
I am using the following .rb file as job for pushing the data
SCHEDULER.every '30s' do
var = File.open("/dashing/abhi/sample.txt", "r")
var.each_line do |line|
    puts line
send_event('polarion', { value: var })
end
end

but the data is not being displayed in dashboard.

A: I think this should be:
SCHEDULER.every '30s' do
  var = File.open("/dashing/abhi/sample.txt", "r")
  var.each_line do |line|
    puts line
    send_event('polarion', { value: line })
  end
end


Q: Properly resize main kivy window when soft keyboard appears on android I'm trying to use Window.softinput_mode to resize the window content when the soft keyboard appears:
softinput_mode = 'resize'

With this mode, the window is resized (i.e., window height is reduced by keyboard_height), but the keyboard still overlaps the content because, as it seems, the adapted window y coordinate is reduced by keyboard_height.
How can i vertically top-align the window content when the soft keyboard appears?
The modes 'pan' and 'below_target' didn't also help, because with them the window is moved along the y-axis (+ keyboard_height) so the top part of the window content is invisible.
EDIT:
A minimal code (taken and adapted from a kivy git-issue), that illustrates the described behavior when ran on Android:
http://pastebin.com/EzKCRMj7

A: The problem is solved by puting
    if smode == 'resize':
        y += kheight

in function Window.update_viewport(), I added the next code to my app in order to workout. DO NOT MUST CHANGE THE KIVY LIBS DIRECTLY
def update_viewport(self=Window):
    from kivy.graphics.opengl import glViewport
    from kivy.graphics.transformation import Matrix
    from math import radians

    w, h = self.system_size
    if self._density != 1:
        w, h = self.size

    smode = self.softinput_mode
    target = self._system_keyboard.target
    targettop = max(0, target.to_window(0, target.y)[1]) if target else 0
    kheight = self.keyboard_height

    w2, h2 = w / 2., h / 2.
    r = radians(self.rotation)

    x, y = 0, 0
    _h = h
    if smode == 'pan':
        y = kheight
    elif smode == 'below_target':
        y = 0 if kheight < targettop else (kheight - targettop)
    if smode == 'scale':
        _h -= kheight
    if smode == 'resize':
        y += kheight
    # prepare the viewport
    glViewport(x, y, w, _h)

    # do projection matrix
    projection_mat = Matrix()
    projection_mat.view_clip(0.0, w, 0.0, h, -1.0, 1.0, 0)
    self.render_context['projection_mat'] = projection_mat

    # do modelview matrix
    modelview_mat = Matrix().translate(w2, h2, 0)
    modelview_mat = modelview_mat.multiply(Matrix().rotate(r, 0, 0, 1))

    w, h = self.size
    w2, h2 = w / 2., h / 2.
    modelview_mat = modelview_mat.multiply(Matrix().translate(-w2, -h2, 0))
    self.render_context['modelview_mat'] = modelview_mat
    frag_modelview_mat = Matrix()
    frag_modelview_mat.set(flat=modelview_mat.get())
    self.render_context['frag_modelview_mat'] = frag_modelview_mat

    # redraw canvas
    self.canvas.ask_update()

    # and update childs
    self.update_childsize()

if __name__ == '__main__':
    app = MainApp()
    Window.update_viewport = update_viewport
    Window.softinput_mode = 'resize'
    app.run()

Have in count the import of Window and depending onn the kivy version kheight variable may have a different name.


Q: python get pointer to an item in a nested dictionary/list combination based on a list of keys I have a data structure that looks something like this:
someData = {"apple":{"taste":"not bad","colors":["red","yellow"]},
"banana":{"taste":"perfection","shape":"banana shaped"},
"some list":[6,5,3,2,4,6,7]}

and a list of keys which describes a path to some item in this structure
someList = ["apple","colors",2]

I already have a function getPath(path) (see below) that is supposed to return a pointer to the selected object. It works fine for reading, but I get into trouble when trying to write
print(getPath(someList))
>> yellow

getPath(someList) = "green"
>> SyntaxError: can't assign to function call

a = getPath(someList)
a = "green"
print(getPath(someList))
>> "yellow"

Is there a way to make this work? Maybe like this:
someFunc(someList, "green")
print(getPath(someList))
>> green

This question looks like this question, except that I want to write something to that item, and not just read it.
My actual data can be seen here (I used json.loads() to parse the data). Note that I plan on adding stuff to this structure. I want a general approach to future proof the project.
My code:
def getPath(path):
    nowSelection = jsonData
    for i in path:
        nowSelection = nowSelection[i]
    return nowSelection

A: The result you're getting from getPath() is the immutable value from a dict or list. This value does not even know it's stored in a dict or list, and there's nothing you can do to change it. You have to change the dict/list itself.
Example:
a = {'hello': [0, 1, 2], 'world': 2}
b = a['hello'][1]
b = 99             # a is completely unaffected by this

Compare with:
a = {'hello': [0, 1, 2], 'world': 2}
b = a['hello']     # b is a list, which you can change
b[1] = 99          # now a is {'hello': [0, 99, 2], 'world': 2}

In your case, instead of following the path all the way to the value you want, go all the way except the last step, and then modify the dict/list you get from the penultimate step:
getPath(["apple","colors",2]) = "green"  # doesn't work
getPath(["apple","colors"])[2] = "green" # should work

A: You could cache your getPath using custom caching function that allows you to manually populate saved cache.
from functools import wraps

def cached(func):
    func.cache = {}
    @wraps(func)
    def wrapper(*args):
        try:
            return func.cache[args]
        except KeyError:
            func.cache[args] = result = func(*args)
            return result
    return wrapper

@cached
def getPath(l):
    ...

getPath.cache[(someList, )] = 'green'
getPath(someList)  # -> 'green'

A: You can't literally do what you're trying to do. I think the closest you could get is to pass the new value in, then manually reassign it within the function:
someData = {"apple":{"taste":"not bad","colors":["red","yellow"]}, "banana":{"taste":"perfection","shape":"banana shaped"}, "some list":[6,5,3,2,4,6,7]}

def setPath(path, newElement):
    nowSelection = someData
    for i in path[:-1]:  # Remove the last element of the path
        nowSelection = nowSelection[i]

    nowSelection[path[-1]] = newElement  # Then use the last element here to do a reassignment

someList = ["apple","colors",1]

setPath(someList, "green")

print(someData)

{'apple': {'taste': 'not bad', 'colors': ['red', 'green']}, 'banana': {'taste': 'perfection', 'shape': 'banana shaped'}, 'some list': [6, 5, 3, 2, 4, 6, 7]}

I renamed it to setPath to reflect its purpose better.


Q: SPSite in Visual Studio 2010 So instead of banging my head against the wall for another couple of hours, I thought I'd just double check a few things here.
First of all, I've been trying to access lists stored on a SharePoint 2007 server (which I should start off by saying is out of my control minus the fact that I'm a member of it who can edit list information) through Visual Studio 2010 on a Windows 7 64bit computer (that is not associated with the server in any real way). I say out of my control because a) the application I'm writing can't be stored on the server comp and b) I can't reconfigure any part of the server (since it's, well, out of my control and such...)
I started off by using web services to read the listitems from a certain list, which worked (to a certain extent.) I couldn't do any more testing because it was immediately recommendeded that I stop using that method and instead try to use SharePoint's own services (like by using Microsoft.Sharepoint and the respective .dll in my project.) I found plenty of tutorials on how to go about doing this online, but I keep getting hung up on one part: namely, the SPSite portion.
I know this question has been brought up dozens of times, but I just can't be sure of what exactly I need control over in order to get this working. Upon reaching this line of code:
SPSite siteCollection = new SPSite(siteUrl);

it fails every time. (Note that siteUrl is a string that leads to a working URL of the server that worked with the web services, so I don't see why it wouldn't work now.)
I've tested multiple .Net Frameworks (3.5, 4.0...) and changed my architecture around from x86 to x64 to Any CPU and it still always fails. Now I need credentials to get onto this website, so I'm assuming that's why I can't access it. Is there some sort of credentials I need to associate with my program in order to get this to work? Or would it ask for them if it successfully accessed that site?
Sorry for all of the confusion here, my mind has just been melting from trying to absorb all of this so quickly.
(On a little sidenote, is the .Net Framework requirement of 3.5 strict? Because this is a Microsoft Surface app, which means it needs a minimum of 4.0...) :P

A: The SharePoint server-side object model you were recommended to use can't be used for your scenario.  It only works when run on a server that is a part of the SharePoint farm (which your code won't in this scenario).  Since you're on 2007 (no client object model), you're stuck with the webservices (or writing and deploying your own web service code to a server in the SharePoint farm, which your code then calls).

A: Is this code running in the same App Pool as the SharePoint website?  If not, your easiest bet would be to use the list service (/_vti_bin/Lists.asmx).  SharePoint 2010 added the Client Object Model, but obviously you're excluded from that.  Example code can be found here.


Q: Sharing several variables using one file I'm trying to share two variables between two different processes: an array and an int. And I want to use the same file. When I call mmap(), and using the offset as I think it works, I get a segmentation fault when I try to use the int.
  buf = (int *)mmap(NULL,N*sizeof(int),PROT_WRITE,MAP_SHARED,compart,0);
  count = (int *)mmap(NULL,sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED,compart,N*sizeof(int));
  *count = 0;

What I do is  locate the array at the beginning of the file, and the int at the position following the size of the array.
Am I getting something wrong?


Q: How to prevent multiple Initialization of property from derived classes The code below is a short "summary" of my real project that contain only the relevant parts to understand my question. (and don`t want to ruin someones day with the original code).
imagine you have 4 classes: Division, Branch, Department and Team. every class inherits base class in that order.
The final goal: return one division object that holds List of 7 Branches, each Branch holds List of 7 Departments and each Department holds List of 7 Teams.
for example i will be able to reach from outside to every class instance:
division d = new division();
d.CreateDivisionStructure();
int Example = d.ListOfBranches[5].ListOfDepartments[4].ListOfTeam[3].SomeIntegerProperty;

(the original code has that lists, override functions, properties etc..)
the problem: imagine that  protected string _myVar in the code below is a Datatable that needs to initialized via myVarproperty with heavy resource consuming SQL query. hence, my wish is to initialize protected string _myVar only one time for all the creation of the "division units structure". in the code below protected string _myVar will be null 64 times and will be initialized 64 times (for my understanding 7 times for each unit and one time for each base() call).
how can i achieve that?
i tried quite a lot other ways but could not solve that. I would appreciate any help, different way of thinking or advice.
  class Program
    {
        static void Main(string[] args)
        {
            division d = new division();
            d.CreateDivisionStructure();

            Console.ReadLine();
        }
    }

    class division

    {
        private static int CountHowManyTimesMyVarWasInitilized = 0;
        public division()

        {

        }

        protected string _myVar;

        public string myVar
        {
            get
            {
                if (_myVar == null)
                {
                    CountHowManyTimesMyVarWasInitilized++;
                    Console.WriteLine(CountHowManyTimesMyVarWasInitilized);
                    _myVar = "now myVar is not null";
                    return _myVar;
                }
                else
                { return _myVar; }

            }
            set { _myVar = value; }
        }

        public void CreateDivisionStructure()

        {

            Console.WriteLine(myVar);
            for (int i = 0; i < 7; i++)
            {
                Branch b = new Branch(7);
            }
        }
    }

    class Branch : division

    {

        public Branch(bool dImDerivedClass)
        {
            //  constructor for department to prevent recursive stackoverflow if base of department will call the empty constructor
        }

        public Branch(int NumberOfBranches)
        {
            Console.WriteLine(myVar);
            Department d = new Department(7);
        }

    }

    class Department : Branch

    {

        public Department(bool ImDerivedClass) : base(true)
        {
            //  constructor for team to prevent recursive stackoverflow if base of Team will call the empty constructor
        }

        public Department(int numberOfDep) : base(true)
        {
            for (int i = 0; i < numberOfDep; i++)
            {
                Console.WriteLine(myVar);
                Team t = new Team(7);
            }
        }
    }

    class Team : Department

    {
        public Team(int numberOfTeams) : base(true)
        {
            for (int i = 0; i < numberOfTeams; i++)
            {
                Console.WriteLine(myVar);
            }
        }
    }
}

A: This is likely a good use of the Lazy<T> class, used in a static variable so there is only a single copy for the process.  It will run the Func you give it once to initialize during the first access of the variable.
https://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx
However, based on your class structure I'm not sure if it is the best approach.  What is the purpose for the hierarchy of Branch : division and Department : Branch.  Is the Branch a Division? If you are trying to share common properties as to not code them over again, I would suggest creating a common class that can hold those variables that Branch, Division, and Department can inherit from.

A: You can use a static variable / static constructor in the lowest class in the hierarchy. The static constructor will only be called once.

A: A simple solution is to use a "control" variable.
I'm sure you can improve your design and avoid this problem but I don't have time to check it now..
using System;

namespace Program
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            division d = new division();
            d.CreateDivisionStructure();

            Console.ReadLine();
        }
    }

    internal class division

    {
        private static int CountHowManyTimesMyVarWasInitilized = 0;

        public division()

        {
        }

        protected string _myVar;
        private bool _isReadyForInitialization;
        public string myVar
        {
            get
            {
                if (!_isReadyForInitialization)
                    return null;
                if (_myVar == null)
                {

                    CountHowManyTimesMyVarWasInitilized++;
                    Console.WriteLine(CountHowManyTimesMyVarWasInitilized);
                    _myVar = "now myVar is not null";
                    return _myVar;
                }
                else
                { return _myVar; }
            }
            set { _myVar = value; }
        }

        public void CreateDivisionStructure()

        {
            // now _myVar is spposed to be initilized to all dirved clasess isnt is?
            Console.WriteLine(myVar);
            for (int i = 0; i < 7; i++)
            {
                Branch b = new Branch(7);
            }
            _isReadyForInitialization = true;
            Console.WriteLine(myVar);
        }
    }

    internal class Branch : division

    {
        public Branch(bool dImDerivedClass)
        {
            //  constructor for department to prevent recursive stackoverflow if base of department will call the empty constructor
        }

        public Branch(int NumberOfBranches)
        {
            Console.WriteLine(myVar);
            Department d = new Department(7);
        }
    }

    internal class Department : Branch

    {
        public Department(bool ImDerivedClass) : base(true)
        {
            //  constructor for team to prevent recursive stackoverflow if base of Team will call the empty constructor
        }

        public Department(int numberOfDep) : base(true)
        {
            for (int i = 0; i < numberOfDep; i++)
            {
                Console.WriteLine(myVar);
                Team t = new Team(7);
            }
        }
    }

    internal class Team : Department

    {
        public Team():base(false)
        {

        }
        public Team(int numberOfTeams) : base(true)
        {
            for (int i = 0; i < numberOfTeams; i++)
            {
                Console.WriteLine(myVar);
            }
        }
    }
}


Q: Automatically update annotations in mx:ColumnChart So, I have a chart (simplified):
<fx:Declarations>
    <mx:SolidColor id="solidColor" color="0x90ee90"/>
    <mx:SolidColorStroke id="solidColorStroke" color="0x90ee90"/>
</fx:Declarations>

<mx:ColumnChart id="columnChart" width="100%" height="100%">
    <mx:annotationElements>
        <mx:CartesianDataCanvas id="cartesianDataCanvas" includeInRanges="true"/>
    </mx:annotationElements>

    <mx:horizontalAxis>
        <mx:DateTimeAxis id="dateTimeAxis"/>
    </mx:horizontalAxis>

    <mx:horizontalAxisRenderers>
        <mx:AxisRenderer axis="{dateTimeAxis}"/>
    </mx:horizontalAxisRenderers>

    <mx:verticalAxis>
        <mx:LinearAxis id="linearAxis" baseAtZero="false"/>
    </mx:verticalAxis>

    <mx:verticalAxisRenderers>
        <mx:AxisRenderer axis="{linearAxis}"/>
    </mx:verticalAxisRenderers>

    <mx:series>
        <mx:ColumnSeries xField="time" yField="value" fill="{solidColor}" stroke="{solidColorStroke}"/>
    </mx:series>
</mx:ColumnChart>

From time to time in chart is updated columnChart.dataProvider. I need to draw over this chart two horizontal lines (for min and max values) and yet something. I know that all of this can be drawn in annotationElements oncartesianDataCanvas.
The question is: At what point (or what event) should redraw the annotations so that they always match the actual data?
I tried to do it immediately after updating columnChart.dataProvider. But it's too early - in dateTimeAxis andlinearAxis did not have time to calculate the new min and max values. It is foolish to calculate them manually.

A: I believe you can try change event on ColumnChart as:
<mx:ColumnChart id="columnChart" width="100%" height="100%" change="handleChange(event)">
</mx:ColumnChart>

Then in the method handleChangeyou can do all the work.


Q: last modified file date in node.js I'm trying to retrieve the last modified date of a file on the server using node.js.
I've tried
file.lastModified;

and
file.lastModifiedDate;

both come back as undefined.

A: For node v 4.0.0 and later:
fs.stat("/dir/file.txt", function(err, stats){
    var mtime = stats.mtime;
    console.log(mtime);
});

or synchronously:
var stats = fs.statSync("/dir/file.txt");
var mtime = stats.mtime;
console.log(mtime);

A: Just adding what Sandro said, if you want to perform the check as fast as possible without having to parse a date or anything, just get a timestamp in milliseconds (number), use mtimeMs.
Asynchronous example:
require('fs').stat('package.json', (err, stat) => console.log(stat.mtimeMs));

Synchronous:
console.log(require('fs').statSync('package.json').mtimeMs);

A: With Async/Await:
const fs = require('fs').promises;
const lastModifiedDate = (await fs.stat(filePath)).mtime;

A: You should use the stat function :
According to the documentation :
fs.stat(path, [callback])

Asynchronous stat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. It looks like this:

{ dev: 2049
, ino: 305352
, mode: 16877
, nlink: 12
, uid: 1000
, gid: 1000
, rdev: 0
, size: 4096
, blksize: 4096
, blocks: 8
, atime: '2009-06-29T11:11:55Z'
, mtime: '2009-06-29T11:11:40Z'
, ctime: '2009-06-29T11:11:40Z'
}

As you can see, the mtime is the last modified time.

A: Here you can get the file's last modified time in seconds.
fs.stat("filename.json", function(err, stats){
    let seconds = (new Date().getTime() - stats.mtime) / 1000;
    console.log(`File modified ${seconds} ago`);
});

Outputs something like "File modified 300.9 seconds ago"


Q: @DateTimeFormat annotation not working in Spring Controller I am following Spring Documentation 4. Through its guidelines I successfully collected the correctly formatted Date field.
The Controller Class is
@Controller
public class HomeController{

    @RequestMapping("/home")
    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
    return new ModelAndView("page1", "myForm", new MyForm());
    }
}

MyForm Class has a field date annotated with @DateTimeFormat
public class MyForm{

    @NumberFormat(style = Style.CURRENCY)
    private Double value = 50.00;

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date date = new Date();

    @NumberFormat(style = Style.CURRENCY)
    public Double getValue() {
    return value;
   }

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    public Date getDate() {
        return date;
    }
}

The JSP code that takes this myForm object and evaluates correctly formatted value of date field is
<spring:eval expression="myForm.date"/>

This far everything is correct. But when I try to use the date field inside my Spring Controller class
@Controller
public class HomeController {

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date date;

    @RequestMapping("/home")
    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
    date = new Date();
    return new ModelAndView("page1", "date", getDate());
    }
   @DateTimeFormat(pattern = "dd/MM/yyyy")
    public Date getDate() {
        return date;
    }

}
The JSP code that takes this myForm object and evaluates incorrectly formatted value of date field is
<spring:eval expression="date"/>

It still displays the date but doesn't format it. Please explain why it formats a field in MyForm Class but not a field in Controller.

A: POJO MyForm is populated by Spring framework itself while submitting the form. Spring takes request parameters, convert into correct format and populate fields of your empty POJO but if you call methods annotated by @DateTimeFormat manually then it doesn't work as expected.
You have to use java SimpleDateFormat or joda DateTime in controller.


Q: How to replace selected text with stored text with JavaScript/jQuery? Let's say I have a textarea and I select some text (with my cursor):

Text
Text <-- selected text
Text

And lets say I have a variable called storedText. How do I got about to replace the selected text with the content of storedText?

Text
Stored Text <-- selected text
Text


Q: Variable Values in Java I have a quick question in regards to the value of how variable values work. I am working on a program right now, which looks like this:
public void run() {

    println("There are " + ATOMS + " initially.");

    int atoms = ATOMS;
    int year = 0;

    while (atoms > 0) {

        for (int i = atoms; i > 0; i--) {

            println(i);
            if( rgen.nextBoolean() ) {
                atoms--;
                println("The total atoms is " + atoms);
            }

            println("The total for i is " + i + "\n"  );

        }

         year++;

         println("There are " + atoms + " at the end of year " + year );
    }

}

At the part with the for loop, and setting the variable i to the value of atoms, is what has me confused. Lets say the value of atoms starts at 20. It goes through the for loop and lets assume that the first time through the RandomGenerator makes it true. So that subtracts 1 from atoms. Then after that the value of i should also be minused due to the i--. So my question is: When I set the variable i to the value of atoms does that just take i and set it to the initial value of 20? And then from there every time I adjust the value of i it is taking off of its own version of 20, and then when I change the value of atoms it, too has its own value. So when I subtract from atoms, that is not also being subtracted from i? That is the only way I can make sense of it because this program is written and works correctly, but that part has me confused.
Thank you very much in advance for any help!

A: Once you set the value of i=atoms, it no longer changes.  It is the loop initializer, and will no longer be processed.
"i" of course will be decremented continuously (because of the i-- decrement).
But you can change the value of atoms to whatever and the results will not change.

A: i=atoms is the initialization in the for loop. So then on, value of i independent of atoms.

A: yes you have answered your own question. the variable i and atoms are two separate instances.
when you start the loop you are setting i equal to the same value as atoms but they are still separate variables. therefore inside the loop when you change the value of one it does not affect the other.


Q: Installing an app to my home screen android I am looking for a way for when someone installs my application it goes in their "all applications menu". Then, after they run the app and go into the setup, when they click save on their options, it will create a shortcut on the home screen (not the all applications menu). Also, is it possible to have this shortcut not do the same thing as the other app? meaning that if I wanted to change the settings I could click on the app in the all applications menu and if I click on the app in the home screen it does something else.

A: First off, there's lots of different home screen implementations on Android. The stock Android one, Samsung, HTC and Motorola all have their own variants, then third party ones like Launcher Pro. All use different stores as to what to keep on the home screen, may provide different profiles for the home screen (home, work, etc).
Second, the home screen is prime real estate. And it is also the user's real estate. If there was programmatic access to the home screen, what happened to the Windows quick launch, desktop, favorites menu (in older versions of IE), and older pin area of the start menu (the very top of it in Win 95/98).
To quote Raymond Chen "I bet somebody got a really nice bonus for that feature". So, in short, even if it was possible, please don't. As awesome as you think your program is, the user might not think the same.


Q: Gradle runs fine under interactive account but not under NT service We have a batch file to build our Android application. It basically runs gradlew.bat assemble. When I remote desktop into the build machine (Windows 8) and run the batch file, everything builds as expected. However, when I invoke the batch file through an NT service, we start getting errors.
The account that the service runs under does have administrative privileges on the machine.
The first error was javax.net.ssl.SSLHandshakeException. Based on another post Android Studio Gradle build failed. Error:Cause: peer not authenticated, I modified gradle-wrapper.properties to use http instead of https for the distribution url. That took care of this problem.
The next error was also similar but this time it was with downloading pom file. Based on another post android- Gradle: An issue occurred configuring root project android studio, I modified build.gradle to use http://jcenter.bintray.com/ as the url instead of default https.
Now I am getting the following error:
Could not parse POM
http://jcenter.bintray.com/com/android/tools/build/gradle/1.1.0/gradle-1.1.0.pom

I am wondering why https could cause a problem in NT service account but not in normal interactive account. Is there a way to fix it? If not, would appreciate if someone has an insight on what the above error means. Regards.

A: A common source of problems when programs that execute successfully as an interactive user, but fail when run as a service, is the user settings surrounding the execution have changed.  For example, when you run Gradle, there are settings in %USERPROFILE% \ .gradle (typically c:\users\<username>, which for you logged in interactively is different than the account under which the service is running.)
When you run as a service, there is a different user profile, or possibly none at all.  Have your batch script dump the environment (add "set" near the top of the .bat file - this will dump an alphabetical list of environment variables), and compare the output when it runs as a service to when you run it interactively.  See if USERPROFILE is defined, and if it is compare the .gradle folder in the service's area to your own .gradle folder.
In addition to Gradle settings, Gradle's cache is also typically under the .gradle folder.  Your cache is likely to contain different items than the cache of the service, which may be significant if there are authentication issues in the external repositories to which your build tries to connect (again, possibly as a result of the different credentials in your user configurations!)
The tool processing the https request may look for certificates somewhere in your user profile.  You may have accepted a certificate (used to 'recognize' an https server) that is not included in the accepted certificates of the service.  These would likely be in the .keystore file in your user profile.  Java's keytool.exe can help to decode and dump this file.
Other tools involved in your build may also have settings stored in the USERPROFILE space, which differ between your space and that of the service account - for example Android (.android), Java, Maven (.m2), Git (.gitconfig), etc.


Q: problems installing scrapy ..missing gcc 4.0 I am having trouble installing scrapy with easy_install, I get:
unable to execute gcc-4.0: No such file or directory
error: Setup script exited with error: command 'gcc-4.0' failed with exit status 1
I have gcc-4.2. I've been trying to downgrade to gcc-4.0 but cannot figure out a way ...

A: You need to setup your environment:

*

*First, install Command Line Tools for Xcode (I'm not 100% sure that you can install without XCode, if not then install XCode from App Store).

*Then install MacPorts
To complete macports setup run this command in Terminal.app:
% sudo port selfupdate

If you done, then you can install scapry from macports:
% sudo port install py27-scrapy

Afther this you should be able to use scrapy command in Terminal.app.


Q: pytest: selective log levels on a per-module basis I'm using pytest-3.7.1 which has good support for logging, including live logging to stdout during tests. I'm using --log-cli-level=DEBUG to dump all debug-level logging to the console as it happens.
The problem I have is that --log-cli-level=DEBUG turns on debug logging for all modules in my test program, including third-party dependencies, and it floods the log with a lot of uninteresting output.
Python's logging module has the ability to set logging levels per module. This enables selective logging - for example, in a normal Python program I can turn on debugging for just one or two of my own modules, and restrict the log output to just those, or set different log levels for each module. This enables turning off debug-level logging for noisy libraries.
So what I'd like to do is apply the same concept to pytest's logging - i.e. specify a logging level, from the command line, for specific non-root loggers. For example, if I have a module called test_foo.py then I'm looking for a way to set the log level for this module from the command line.
I'm prepared to roll-my-own if necessary (I know how to add custom arguments to pytest), but before I do that I just want to be sure that there isn't already a solution. Is anyone aware of one?

A: I had the same problem, and found a solution in another answer:
Instead of --log-cli-level=DEBUG, use --log-level DEBUG. It disables all third-party module logs (in my case, I had plenty of matplotlib logs), but still outputs your app logs for each test that fails.

A: I got this working by writing a factory class and using it to set the level of the root logger to logger.INFO and use the logging level from the command line for all the loggers obtained from the factory. If the logging level from the command line is higher than the minimum global log level you specify in the class (using constant MINIMUM_GLOBAL_LOG_LEVEL), the global log level isn't changed.
import logging

MODULE_FIELD_WIDTH_IN_CHARS = '20'
LINE_NO_FIELD_WIDTH_IN_CHARS = '3'
LEVEL_NAME_FIELD_WIDTH_IN_CHARS = '8'
MINIMUM_GLOBAL_LOG_LEVEL = logging.INFO

class EasyLogger():
    root_logger = logging.getLogger()
    specified_log_level = root_logger.level
    format_string = '{asctime} '
    format_string += '{module:>' + MODULE_FIELD_WIDTH_IN_CHARS + 's}'
    format_string += '[{lineno:' + LINE_NO_FIELD_WIDTH_IN_CHARS + 'd}]'
    format_string += '[{levelname:^' + LEVEL_NAME_FIELD_WIDTH_IN_CHARS + 's}]: '
    format_string += '{message}'
    level_change_warning_sent = False

    @classmethod
    def get_logger(cls, logger_name):
        if not EasyLogger._logger_has_format(cls.root_logger, cls.format_string):
            EasyLogger._setup_root_logger()
        logger = logging.getLogger(logger_name)
        logger.setLevel(cls.specified_log_level)
        return logger

    @classmethod
    def _setup_root_logger(cls):
        formatter = logging.Formatter(fmt=cls.format_string, style='{')
        if not cls.root_logger.hasHandlers():
            handler = logging.StreamHandler()
            cls.root_logger.addHandler(handler)
        for handler in cls.root_logger.handlers:
            handler.setFormatter(formatter)

        cls.root_logger.setLevel(MINIMUM_GLOBAL_LOG_LEVEL)
        if (cls.specified_log_level < MINIMUM_GLOBAL_LOG_LEVEL and
            cls.level_change_warning_sent is False):
            cls.root_logger.log(
                max(cls.specified_log_level, logging.WARNING),
                "Setting log level for %s class to %s, all others to %s" % (
                    __name__,
                    cls.specified_log_level,
                    MINIMUM_GLOBAL_LOG_LEVEL
                )
            )
            cls.level_change_warning_sent = True

    @staticmethod
    def _logger_has_format(logger, format_string):
        for handler in logger.handlers:
            return handler.format == format_string
        return False

The above class is then used to send logs normally as you would with a logging.logger object as follows:
from EasyLogger import EasyLogger

class MySuperAwesomeClass():
    def __init__(self):
        self.logger = EasyLogger.get_logger(__name__)

    def foo(self):
        self.logger.debug("debug message")
        self.logger.info("info message")
        self.logger.warning("warning message")
        self.logger.critical("critical message")
        self.logger.error("error message")

A: Enable/Disable/Modify the log level of any module in Python:
logging.getLogger("module_name").setLevel(logging.log_level)


Q: How to reduce the width of dropdown-menu? I am using bootstrap 3 to create a simple drop-down menu, but I want to decrease its width and I can't figure it out how to do this.
HTML:

  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Dropdown

  </button>

Action

Another

Something

Separated

CSS:
.dropdown-menu {
    width: 60px !important;
}

A: .dropdown-menu has min-width: 160px; and min-width overrides width so you can not change width you can use min-width instead of width.

.dropdown-menu {
  min-width: 60px !important;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Dropdown

  </button>

Action

Another

Something

Separated

It works. You should call bootstrap lib and jquery. Please, read bootstrap documentation.
Jsfiddle

A: Give a ID for the div and specify the min-width in the css as follows:
.dropdown #mydiv{ min-width:60px; }

Note: Do NOT use '!important'.
For more information check out this great post by Chris Coyier : Specifics on CSS Specificity


Q: Increasing number once per mouse click/key press in XNA This has been bothering me lately- when I use some code like below to increase selection every mouse click:
if (m.LeftButton == ButtonState.Pressed)
currentSelection++;
Then currentSelection increases by a ton, simply because this code is in my Update() function and by design, runs every frame and so increases currentSelection. There is almost no chance you can click and release fast enough to prevent currentSelection from increasing more than one.
Now my question is what I should do to make it so everytime I click the mouse down once, it only increases currentSelection once until the next time I click down again.

A: You will need to compare the current mouse state and the last update's mouse state.
In your class you'll have MouseState mouseStateCurrent, mouseStatePrevious; declared and so it'll be something like:
mouseStateCurrent = Mouse.GetState();

if (mouseStateCurrent.LeftButton == ButtonState.Pressed &&
    mouseStatePrevious.LeftButton == ButtonState.Released)
{
    currentSelection++;
}

mouseStatePrevious = mouseStateCurrent;

So it will detect that previous time you pressed it, then you release it - only then it is considered as a click and it will add to currentSelection.


Q: The analyzer produces case_block_not_terminated in a case block with nested if/else statement, although return statement is executable I have a case that I would like to understand.
If I have following Switch Case statement with nested if/else:
f(int x, int y) {
  switch (x) {
    case 0:
      if (y > 10) {
        return 'StringA';
      } else {
        return 'StringB';
      }
    default:
      return 'Anything';
  }
}

the analyses throws an error: case_block_not_terminated

case_block_not_terminated: The last statement of the ‘case’ should be
‘break’, ‘continue’, ‘rethrow’, ‘return’, or ‘throw’.

if I add a break; at the end of the case statement the error disappears, but it is clearly dead code, because one of the return statements should be executed.
f(int x, int y) {
  switch (x) {
    case 0:
      if (y > 10) {
        return 'StringA';
      } else {
        return 'StringB';
      }
      break;
    default:
      return 'Anything';
  }
}

A: This issue should go away when you enable the null-safety feature.  The analyzer's code flow analysis has been much improved for NNBD to fix this and similar cases. (You can verify this in DartPad with null-safety enabled.)
In the meantime, you also could just remove the superfluous else:
String f(int x, int y) {
  switch (x) {
    case 0:
      if (y > 10) {
        return 'StringA';
      }
      return 'StringB';
    default:
      return 'Anything';
  }
}

or remove the superfluous default case:
String f(int x, int y) {
  switch (x) {
    case 0:
      if (y > 10) {
        return 'StringA';
      } else {
        return 'StringB';
      }
  }
  return 'Anything';
}


Q: slideUp different on actual page I am trying to use the slideUp() JQuery function on a bunch of items without images. The code I've written works fine in JSFiddle, but on my actual page, it collapses in a clunky way.
Why are they not acting the same way?
JSFiddle
To activate the function on the page, press the checkbox in the right menu
Real page

A: Sifting through CSS for a few minutes and I found a solution, I have made a list of corrections.
Here is the CSS code on pastebin, it does all the fixes I have mentioned below.
Manual Fix
Find #middlewrapper #content .contentbox, disable float:left.
#middlewrapper #content .contentbox {
    width: 650px;
    padding: 15px;
    /* float: left; */
    background-color: white;
}

Find #middlewrapper #content .contentbox_shadow, disable float:left.
#middlewrapper #content .contentbox_shadow {
    width: 690px;
    height: 20px;
    /* float: left; */
    background-image: url('http://xn--nstvedhandel-6cb.dk/naestved/public/css/../images/content_skygge.png');
    background-repeat: no-repeat;
}

Find #middlewrapper #content, disable float:left.
#middlewrapper #content {
    width: 690px;
    /* float: left; */
}

Finally, find #middlewrapper #content .contentbox, after it's definition, place #content.
#content {
    width: 680px;
    float: left;
}

Do not delete or alter the definition of #middlewrapper #content found a few lines later.


Q: How to parse HTML tags as raw text using ElementTree I have a file that has HTML within XML tags and I want that HTML as raw text, rather than have it be parsed as children of the XML tag. Here's an example:
import xml.etree.ElementTree as ET
root = ET.fromstring("<root><text>
This is some text that I want to read
</text></root>")

If i try:
root.find('text').text

It returns no output
but root.find('text/p').text will return the paragraph text without the tags. I want everything within the text tag as raw text, but I can't figure out how to get this.

A: Your solution is reasonable. An element object is the list of children. The .text attribute of the element object is related only to things (usually a text) that are not part of other (nested) elements.
There are things to be improved in your code. In Python, string concatenation is an expensive operation. It is better to build the list of substrings and to join them later -- like this:
output_lst = []
for child in root.find('text'):
    output_lst.append(ET.tostring(child, encoding="unicode"))

output_text = ''.join(output_lst)

The list can be also build using the Python list comprehension construct, so the code would change to:
output_lst = [ET.tostring(child, encoding="unicode") for child in root.find('text')]
output_text = ''.join(output_lst)

The .join can consume any iterable that produces strings. This way the list need not to be constructed in advance. Instead, a generator expression (that is what can be seen inside the [] of the list comprehension) can be used:
output_text = ''.join(ET.tostring(child, encoding="unicode") for child in root.find('text'))

The one-liner can be formatted to more lines to make it more readable:
output_text = ''.join(ET.tostring(child, encoding="unicode")
                      for child in root.find('text'))

A: I was able to get what I wanted by appending all child elements of my text tag to a string using ET.tostring:
output_text = ""
for child in root.find('text'):
    output_text += ET.tostring(child, encoding="unicode")

>>>output_text
>>>"
This is some text that I want to read
"

A: Above solutions will miss initial part of your html if your content begins with text. E.g.
<root><text>This is some text that I want to read</text></root>

You can do that:
node = root.find('text')
output_list = [node.text] if node.text else []
output_list += [ET.tostring(child, encoding="unicode") for child in node]
output_text = ''.join(output_list)


Q: Creating a REST API with MySQL and PHP formatted as a JSON response I'm trying to create a public REST API from scratch without using any framework and I've created where it retrieve all the data as JSON response when the user enter in this at the end of the address "...?list=all" However, I want to  retrieve a row by an ID or retrieving the most popular items. I know that I will probably have to change that in the query string, but how would I create the end of the address that retrieves it? like ?ID=05 (retrieving row ID 5 from database) or TOP=15 (retrieving top popular 15). If there's a better or more efficient way to rewrite my code, feel free to let me know.
<?php
    // Check Connection
if(!($db = mysqli_connect($server, $user, $password, $database))) {
    die('SQL ERROR: Connection failed: '.mysqli_error($db));
    exit;
    }
return $db;
}

    //call the passed in function
if(function_exists($_GET['list'])) {
    $_GET['list']();
}

    //methods
function all(){
    $db = getMysqlDB();
    $query = "SELECT * FROM books;";
    $books_sql = mysqli_query($db, $query);
    $books = array();
    while($book = mysqli_fetch_array($books_sql)) {
        $books[] = $book;
    }
    $books = json_encode($books);
    echo $_GET['jsoncallback'].$books;
 }
?>

A: A simple start for a PHP based REST API would be:
<?php

// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);

// connect to the mysql database
$link = mysqli_connect('localhost', 'user', 'pass', 'dbname');
mysqli_set_charset($link,'utf8');

// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;

// escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
  if ($value===null) return null;
  return mysqli_real_escape_string($link,(string)$value);
},array_values($input));

// build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
  $set.=($i>0?',':'').'`'.$columns[$i].'`=';
  $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}

// create SQL based on HTTP method
switch ($method) {
  case 'GET':
    $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
  case 'PUT':
    $sql = "update `$table` set $set where id=$key"; break;
  case 'POST':
    $sql = "insert into `$table` set $set"; break;
  case 'DELETE':
    $sql = "delete `$table` where id=$key"; break;
}

// excecute SQL statement
$result = mysqli_query($link,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error());
}

// print results, insert id or affected row count
if ($method == 'GET') {
  if (!$key) echo '[';
  for ($i=0;$i<mysqli_num_rows($result);$i++) {
    echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
  }
  if (!$key) echo ']';
} elseif ($method == 'POST') {
  echo mysqli_insert_id($link);
} else {
  echo mysqli_affected_rows($link);
}

// close mysql connection
mysqli_close($link);

source
For a more complete implementation check out:
https://github.com/mevdschee/php-crud-api
Disclosure: I am the author.


Q: MongoDB java drivers not compatible in Android I am trying to delete a document from MongoDB (database present at http://mlab.com) through my Android application, but since mongo-db-java-drivers are not compatible with Android so therefore I am getting different Exceptions. So please tell is there any way to delete from MongoDB through Android application?


Q: How do I get the text decoding of the Chinese? Python in the Chinese part of the result of requests.get (url) is
"æ ?? ¯ä¸? Ç§? Å? ¯ä» ¥ è ?? ªç? ± å? ¼å? ¸ç? ??? Æ ???? è§? ï¼ "
came out in this way.
How it is necessary to decode Can you print Chinese characters?
In the following method, source and other statements will be output.

*

*result.content.decode("gbk","ignore").encode("utf-8","ignore")

*content.encode('utf-8').decode('gbk')

Example of a site is here. https://lvyou.baidu.com/notes/20fd27d671563fe1e8927d21?sid=9739db6e97289b7e6b22f9ea?request_id=831992042&idx=0
Let us know would really appreciate.

A: The problem has been resolved.
Set the encoding option in requests, we were able to obtain the required value.
Thank you very much.
sub_result = requests.get(sub_url)
sub_result.encoding = 'utf-8'
sub_soup = BeautifulSoup(sub_result.text, 'lxml')


Q: JUnit @After not executing when Jenkins pipeline is stopped I'm working with a declarative Jenkins pipeline that runs some tests which make use of JUnit 4. In the tests there are @After methods where test cleanup occurs. When a pipeline is aborted during a test I've confirmed that the @After methods are never executed (confirmed using log statements in the @After methods and checking the Jenkins console log).
This leaves test data (e.g. users that the tests use) in a bad state and cause later tests (and pipeline builds) to fail, so it's an issue.
The pipeline is aborted via the Jenkins UI "stop" button, or through the pipeline hitting a timeout for that stage. In both cases the pipeline exits with code 143, which is a SIGTERM.
How can I ensure that JUnit 4.x @After methods are executed when a declarative Jenkins pipeline is aborted?

A: I have a workaround that you could use to solve the issue. Create two classes. TestClass and AfterClass. In the AfterClass, you will have to keep one test method so that after will get triggered. Now, In test execution step of declarative pipeline, you can execute
mvn clean test -PTest

and in the post always of declarative pipeline script, you can execute below maven command
mvn clean test -PCleanup

TestClass:
import org.junit.Test;

public class TestClass
{

    @Test
    public void testClass()
    {
        System.out.println("Test");
    }
}

AfterClass:
@Test
public void beforeCleanUp()
{
    System.out.println("Before Cleanup");
}
@After
public void after()
{
    System.out.println("After");
}

POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>stackovrflw-62492859</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <profiles>
        <profile>
            <id>Test</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>3.0.0-M5</version>
                        <configuration>
                            <test>com.test.junit.classes.TestClass</test>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>Cleanup</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>3.0.0-M5</version>
                        <configuration>
                            <test>com.test.junit.classes.AfterClass</test>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

Note: This is not the actual solution as I do not have much experience on JUnit. But you could use this workaround, if you do not get any proper solution. I will be also trying to find proper solution for you


Q: POST Method not using Params I dont know why the getParams() is not working in my method?
The System.out.println works fine under getHeaders but not under getParams?
    //---------------------------------------POST request with headers---------------------------------------
public void post(String url, final String param1, final String param2, String source) {

    // Request a string response from the provided URL.
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,
            getReponse(source), createMyReqErrorListener()) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<>();
            params.put("loginAlias", "username");
            params.put("loginPassword", "12345");
            System.out.println("Params are: " + params.toString());
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put(ACCEPT, ACCEPT_JSON); //Accepting JSON
            headers.put(AUTH_ID, AUTH_ID_VALUE);
            headers.put(PLATFORM, PLATFORM_VALUE);
            headers.put(CID, "");
            headers.put(DEVICE_TYPE_MOBILE, DEVICE_TYPE_MOBILE_VALUE);
            System.out.println("Headers are: " + headers.toString());
            return headers;
        }
    };
// Add the request to the RequestQueue.
    queue.add(request);
}

I have followed all the Google Volley documentation and tried a couple options on SO but for some reason, this does not work?
Thanks

A: also faced the same issue, Finally I found that there is some issue with volley - JSONObject request. (after few googling!)
the getParams() doesn't invoke because JsonObjectRequest extended JsonRequest which invoke getBody() directly to encoding the constructor second parameter(call requestBody) as contentType, that's why it ignore your getParam() method.
try this solution, it resolved my problem.
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomRequest(String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

In activity/fragment do use this
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());

requestQueue.add(jsObjRequest);

Volley JsonObjectRequest Post request not working


Q: Can you put a Canvas instance inside a jQuery gallery? I've made several simple particle and game examples using Canvas and KineticJS and I was thinking about the using a slider like Nivo to show them off. First thoughts are that I would need to redraw each canvas on transition of the slider, but I was just wondering if anyone has tried this already with any success or failures and if it's feasible?

A: Try:
 var mystage = stage.toImage(config);

to convert the canvas to an image, then you can transition images.
But if you want the whole stage saved as an object you just do:
 var json = stage.toJSON();

and that saves your stage for reloading later, which you can do with:
 var stage = Kinetic.Node.create(json, 'container');


Q: Not getting detailed error log for java application on Tomcat on Azure App Service We deployed a java web application (WAR file) onto an Azure App Service with newest Tomcat (8.5). The WAR file is detected by Azure but on startup we are seeing the following in the catalina.date.log

06-Feb-2018 07:57:24.494 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
  06-Feb-2018 07:57:24.512 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.20
  06-Feb-2018 07:57:27.697 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [D:\home\site\wwwroot\webapps\myapp.war]
  06-Feb-2018 07:59:16.570 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
  06-Feb-2018 07:59:16.570 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Context [/myapp] startup failed due to previous errors
  06-Feb-2018 07:59:16.629 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [D:\home\site\wwwroot\webapps\myapp.war] has finished in [108,932] ms

We cannot find this log file anywhere. We have set all possible logging settings to verbose. Should this be a separate file or are some logging settings missing?
We also see the follwing row

06-Feb-2018 12:00:43.922 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=D:\Program Files (x86)\apache-tomcat-8.5.20\conf\logging.properties

It is not possible for us to change this file.

A: Azure Web services are deployed to a Windows Server 2016.
You can access the log files and change the location of the log files using

*

*Open the url https://<app service name>.scm.azurewebsites.net/DebugConsole {or choose Menu > Debug Console  > CMD)

*Type the dir command to go the location of the tomcat install. For example dir D:\Program Files (x86)\apache-tomcat-8.5.6\conf

*Alternatively you can also click on the folder name dispalyed above the command/terminal

*In your case, to enable detailed logging, open logging.properties under \Program Files (x86)\apache-tomcat-8.5.6\conf and set 1catalina.org.apache.juli.FileHandler.level = FINE. You can read more info at Documentation on Apache Tomcat 8.5 Logging
Sample screen from my Tomcat setup as a webservice:


Q: Directive with  and indirection I have several multi-selects on a page, each with a bit of logic that fills that multi-select from the server, and I want to wrap each one up into a Directive.
Before trying to wrap these into Directives, I built each as such:
index.html
<select name="groups" ng-model="inputs.groups" ng-change="groupsChanged()" ng-options="g for g in allgroups" multiple></select>

controllers.js
In the first pass, I do my $http calls from here. Yes, I know, not best practices, but I wanted to prove that this works to myself first.
  $scope.loadSelect = function(_url) {
    $http({
      url: _url,
      method: 'POST',
      data: $scope.inputs,
      model: 'all' + _url
    }).success(function(data, status, headers, config) {
      $scope[config.model] = data;
    });
  };

  // Fill groups
  $scope.loadSelect('groups');

  // When groups change, reload other select fields that depend on groups
  $scope.groupsChanged = function() {
    $scope.loadSelect('categories');
    $scope.loadSelect('actions');
  }

Now I want to migrate this to a Directive. I see two major challenges:
1.) How do I encapsulate the entire set of options (e.g. what is now the "allgroups" model) into the Directive?
2.) Based on initial experiments, I tried to physically build the <select/> into the template, but realized that I have to manipulate the DOM to physically replace name, ng-model, and ng-options. That lead me to the compile attribute, but a.) that feels wrong and b.) setting <select ng-options="x for x in allgroups" /> doesn't actually repeat after it's been inserted into the DOM.  Using compile doesn't feel right; what's the right way to approach this?
Here is my first attempt at the Directive looks like this. It doesn't really work, and I think I'm going about it incorrectly:
index.html
<dimension ng-model="inputs.users" alloptions-model="allusers">Users</dimension>

directives.js
directive('dimension', function() {
  return {
    restrict: 'E',
    scope: {
      ngModel: '=',
      alloptionsModel: '='
    },
    template:
        '
' +
          '' +
          '<fieldset>' +
              '
' +
                '<select ng-model="{{ngModel}}" ng-options="x for x in {{alloptionsModel}}" multiple class="form-control"></select>' +
              '
' +
           '</fieldset>' +
        '
',

    replace: true,
    transclude: true
  };
});

Clearly I haven't even gotten to the server load part yet, but I plan to roll that into a controller in the Directive, with the actual $http call in a service.
I feel like I'm moving down the wrong track. If you have suggestions on how to realign, please help!

A: The main problem with your directive is that you can't use mustache binding in ngModel and ngOptions directive because they are evaluated directly. You can directly bind to the scoped property (ngModel and alloptionsModel):
directive('dimension', function() {
  return {
    restrict: 'E',
    scope: {
      ngModel: '=',
      alloptionsModel: '='
    },
    template:
        '
' +
          '' +
          '<fieldset>' +
              '
' +
                '<select ng-model="ngModel" ng-options="x for x in alloptionsModel" multiple class="form-control"></select>' +
              '
' +
           '</fieldset>' +
        '
',
    replace: true,
    transclude: true
  };
});

See this plunkr for a working example.
Edit
As for the compile route, there is nothing wrong with it. It is useful when you need to dynamically create a template which will clearly be your case when you will get to the select's item template.
compile: function(tElement, tAttrs) {
  var select = tElement.find('select'),
      value = tAttrs.value ? 'x.' + tAttrs.value : 'x',
      label = tAttrs.label ? 'x.' + tAttrs.label : 'x',
      ngOptions = value + ' as ' + label + ' for x in alloptionsModel';

      select.attr('ng-options', ngOptions);
}

// In the HTML file
<dimension ng-model="inputs.users"
           alloptions-model="allusers"
           label="name">
  Users
</dimension>

I've updated the plunkr with the compile function.


Q: Using a Logic App Condition To Compare Multiple Values From The Same Field I am trying to setup a condition that compares multiple values in a field. So if the field contains 1,2 3 do this otherwise do something else. As shown in the attached image. However this only goes false if the field contains the first value. If the second or third value is contained it goes true. How can I make it false for all three values?


Q: How to pass input html data to a javascript function as its variables and get a response My problem: I can't get to pass the input data from html to js function as its variables and get the appropriate response.
My goal: when the user clics on submit button he receives whatever response the js function provided.
I have two files in the same directory:
- index.html
- index.js
index.js content:
function quEq(a, b, c) {
var delta = (b ** 2) - (4 * a * c);
  if (a == 0) {
  return "Not a quadratic equation";
  };
if (delta < 0) {
    return "Complex root! No solution in real numbers";
    } else {
        var first= (-b + Math.sqrt(delta)) / (2*a);
        var second= (-b - Math.sqrt(delta)) / (2*a);
        return {first, second};
        };
};

index.html content:
    <!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>Quadratic Equation</title>

                  <form>

                      Enter 'a' value
                      <input type="number" class="form-control" id="a" placeholder="1">
                      Enter 'b' value
                      <input type="number" class="form-control" id="b" placeholder="5">
                      Enter 'c' value
                      <input type="number" class="form-control" id="c" placeholder="6">
                      <button onclick="quEq(document.getElementById('a').nodeValue, document.getElementById('b').value, document.getElementById('c').value)" type="submit" class="btn btn-primary">Submit</button>

                  </form>

THANK YOU FOR YOUR HELP
I HOPE I AM NOT BREAKING ANY RULES

A: Your onclick event handler should successfully handle the click event, but it isn't clear what you want to do with the return value of your function. The browser will not do anything by default. Instead, you need to manage this yourself.
For example, you could write the results into some other part of the DOM.
In your HTML you can create some nodes to hold the output:

Then in your event handler:
document.getElementById('result-1').innerText = first;
document.getElementById('result-2').innerText = second;

A: You have a variety of HTML and JavaScript syntax errors.
See comments in the code below:

// Get references to the DOM elements that you'll work with
var btn = document.querySelector("button");
var a = document.getElementById('a');
var b = document.getElementById('b');
var c = document.getElementById('c');

// Do event binding in JavaScript, not with inline HTML attributes
btn.addEventListener("click", function(){
  // Use "value", not "nodeValue"
  quEq(a.value, b.value, c.value);
});

function quEq(a, b, c) {
  // Carefull with syntax!
  var delta = (b * 2) - (4 * a * c);
  if (a == 0) {
    // return doesn't show up anywhere
    alert("Not a quadratic equation");
  } else if (delta < 0) {
    alert("Complex root! No solution in real numbers");
  } else {
    var first= (-b + Math.sqrt(delta)) / (2*a);
    var second= (-b - Math.sqrt(delta)) / (2*a);
    alert(first + " " + second);
  }
}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>Quadratic Equation</title>

                  <form>

                      Enter 'a' value
                      <input type="number" class="form-control" id="a" placeholder="1">
                      Enter 'b' value
                      <input type="number" class="form-control" id="b" placeholder="5">
                      Enter 'c' value
                      <input type="number" class="form-control" id="c" placeholder="6">
                      <button type="button" class="btn btn-primary">Submit</button>

                  </form>

A: I see two flaws in this code
1)
document.getElementById('a').nodeValue

instead of
document.getElementById('a').value

2) you should be aware that placeholder is just a text, it seems strange that you can see 6 but there's no number yet, so instead of placeholder set value attribute directly if you want some default numbers
<input type="number" class="form-control" id="a" value="1">

A: Now its working
  a: <input type="number" name="a" id="a">

  b: <input type="number" name="b" id="b">

  c: <input type="number" name="c" id="c">

  <button onclick="quEq(document.getElementById('a').value,document.getElementById('b').value,document.getElementById('c').value)">Submit</button>

A: There are a couple of things in your index.html file that are not correct, for example, you opened a second div with a class "form-group" yet you did not close it, also you did not pass properly the value for "a" (.nodeValue when it should be .value).
I made some changes to your code and appended the response in the div you weren't using (the second "form-group") and changed it's name, also I added type="button" to your button so it won't submit as soon as you click on it, you can find the html and js in codepen
Here is your function:
function quEq() {
 var a = document.getElementById('a').value
 var b = document.getElementById('b').value
 var c = document.getElementById('c').value

 var delta = (b ** 2) - (4 * a * c)

 if (a == 0) {
  document.getElementsByClassName("info")[0].innerHTML = "Not a quadratic equation"
 }

 if (delta < 0) {
    document.getElementsByClassName("info")[0].innerHTML = "Complex root! No solution in real numbers"
 }
 else {
   var first= (-b + Math.sqrt(delta)) / (2*a)
   var second= (-b - Math.sqrt(delta)) / (2*a);
   document.getElementsByClassName("info")[0].innerHTML = first + ", " + second
 }
}

Here is your div changed:

                <form>

                        Enter 'a' value
                        <input type="number" class="form-control" id="a" placeholder="1" value="1"/>

                        Enter 'b' value
                        <input type="number" class="form-control" id="b" placeholder="5" value="5" />

                        Enter 'c' value
                        <input type="number" class="form-control" id="c" placeholder="6" value="6" />

                        <button onclick="quEq()" type="button" class="btn btn-primary">Submit</button>

                </form>


Q: "Book like" view in Openseadragon (several "2 pages" sequences) Openseadragon newbbie here !
I'm trying to display images by group of 2 AND keeping sequence mode activated, so I can "turn pages".
I managed to display 2 pages, I managed to read pages 1 by 1 in sequence mode, ...
But I just didn't find a way to do both.
To display 2 pages, I loaded 2 tiles sets and configured "sequenceMode=false". Then I set coordinates, to display visuals aside.
To read pages 1 by 1, I loaded several tiles and configured "sequenceMode = true".
What I would like to do is display two visuals (= tiles sets) aside (like an open book). And then, on "next" button click, display the two next visuals from my "tilesSources" array... and so on !
Thank you for your help !

A: I recommend keeping sequence mode off, like you did for the two pages, and lay out the entire sequence (in pairs) that way. You should then create your own next/previous buttons and use viewer.viewport.fitBounds to animate the viewer to each pair as needed.
Here's an example of a system that does something like that (plus a lot more):
https://iangilman.com/osd/test/demo/m2/
Press the "book" button at the top to see the "two-page" mode. The code for this is here:
https://github.com/openseadragon/openseadragon/tree/master/test/demo/m2
Of course you don't need all of that code, but hopefully it can be a helpful reference.


Q: move camera with player [unity] using System.Collections.Generic;
using UnityEngine;

public class follow_mainship : MonoBehaviour
{
    public Transform Playerposition;
    private Vector3 cameraoffset;
    // Start is called before the first frame update
    void Start()
    {
        cameraoffset = Playerposition.position - transform.position;

    }

    // Update is called once per frame
    void Update()
    {
        Vector3 newpos = Playerposition.position + cameraoffset;
    }
}

I am using this code to move camera with my player, but it is not working. I have added my object in the Playerposition box. What should I do?
Update:
As per the answer, camera is following my ship, whenever the ship touches the ground, the camera flies back a long distance. Is there any way to fix it?

A: Your logic to get the new position is correct, but in your Update() function, you have to update the position of the camera using transform.position, assuming this script is a component you have added to the Camera in the scene.
// Update is called once per frame
void Update()
{
    Vector3 newpos = Playerposition.position + cameraoffset;
    transform.position = newpos;
}

If this script isn't on the camera, you'll need a reference to the camera by taking it as an input in the Unity inspector (declaring public Camera cam; at the top of your class) and then set in in the inspector by dragging the camera object onto that input. Then you can do cam.transform.position = newpos; in Update().


Q: PhoneGap/Cordova blank screen on pause/resume I have a simple html/javascript app that starts and works up fine on an Android device. However, when the app is put in background by using the 'home button' and then brought back to the foreground by clicking on the app again - it starts with a blank screen (white blank screen on android ) and stays that way until the 'back button' is pressed.
Once the 'back button' is pressed the screen refreshes to the last page displayed by the app.
I am new to PhoneGap and I am sure there is something simple/fundamental that I am missing - in terms of how to handle the 'resume' event/etc.. I have followed the instructions provided on this link by Phil Mitchell http://wiki.phonegap.com/w/page/35501397/Tutorials (which is a great resource btw..)
Thanks.
Update :
After looking at the DroidGap code, I have tried to add the following line :-
        super.setBooleanProperty("keepRunning", false);

But this does not seem to help. I am happy for the app to exit every time the home button is entered and then do a full restart when the app is clicked on the mobile.
Any help is much appreciated..

A: I was having the same problem and I want to share a hack that worked for me.
My app is based on ionic/angular/cordova and the android version was giving me a white screen around 50% the times on pause/resume.
When it happened, tapping anywhere on the screen or hitting the back button would make the screen to render again just fine.
I added a div tied to a scope variable named random, like this:
  <body ng-app="starter" id="body">
    <div>{{ random }}</div>
    <ion-nav-view>
    </ion-nav-view>
  </body>

Then I added a listener inside my app.js to capture the resume event fired by cordova, to then change the random variable and call $apply(), like this:
document.addEventListener("resume", function() {
  angular.element(document.querySelector('#body')).scope().random = Math.random();
  angular.element(document.querySelector('#body')).scope().$apply();
})

Since the ion-nav-view takes over the whole screen that div never shows up, but angular doesn't know that and refreshes the page, causing the whole thing to work.
(I tried to tie the variable to an invisible element but then angular doesn't refresh the page)
I hope this helps someone!

A: There seem to be issues around rendering the pages thru PhoneGap and 'Dialog'ing thru Client side FB authentication flow using the JS SDK. If I disable the client side authentication, then the rendering and display of the page works very well, when the app is brought to foreground from background (pause/resume/etc).
I am assuming that the page will need to sense that it is being displayed over a mobile device and use the IOS or Androi SDK for client side authentication.. (if/when I get around to testing that, I update the answer - if there is anybody who has any more light to shed, please feel free to embellish).

A: If you still say "I am happy for the app to exit every time the home button is entered and then do a full restart when the app is clicked on the mobile." then go for it.
@Override
protected void onStop(){
super.onStop();
}

Try this from where you create activity or from the class which "extends DroidGap".


Q: Javascript check to see if an event has already been fired or clicked I have a function that needs to fire when I click on a chevron tab.  However I only need that function to fire that first time we load the page.  How can I prevent it form firing every time the tab is clicked?
    $('#navi a').bind('click',function(e){
        var $this   = $(this);
        var prevButton  = current;
        $this.closest('ul').find('li').removeClass('selected');

        if ( $(this).attr('id') == 'tab2')
        {
            //fire function only once
        }

    });

A: Use the .one binding instead. This will attach it to fire on the first click and remove itself.

A: In case you need only part of your event handler to run once :
$("div").on("click",function(){
    if (!$(this).data("fired")) {
        console.log("Running once");
        $(this).data("fired",true);
    }

    console.log("Things as usual");
});

Demo

A: Use:
var isalreadyclicked=false;
  $('#navi a').bind('click',function(e){
    var $this   = $(this);
    var prevButton  = current;
    $this.closest('ul').find('li').removeClass('selected');

    if ( $(this).attr('id') == 'tab2')
    {
    if(!isalreadyclicked){
        //fire function only once
    isalreadyclicked=true;
    }
    }

  });