Is it possible to imput values using mice package, reshape and perform GEE in R?

Question: I have a longitudinal database that has more than 50% of the missing data of the MAR type.
This amount of missing values was a surprise to me because I did not foresee this in the study design, and for that reason I cannot delete those that have missing values because my sample N will be very small. however, these imputation methods are new to me, and I am facing many difficulties.
I saw some tutorials on multiple imputation through the MICE package. So the following points were not clear:
How to specify categorical variables (The categorical variables have no missing data). In my case I have two categorical variables, one with two levels (before  and after) and the other with 4 levels (grp1,grp2, grp3, grp4). and eight continuous variables with missing values (D0 to D7).
Just like in the example below:

When imputing data I would like to specify that an imputation should occur through categorical variables (time and group).
I used the code below but I don't know if considered the categorical variables
 library(mice)
 imputed_Data <- mice (my.data, m = 5, maxit = 50, method = 'pmm', seed = 500)

After making the imputations, I would like to change from the wide format to the long format, where there would be only the columns: ID, Name, Time, group and a two columns one with the repeated mensure (D0 to D6) and other with Values. I know how to do this with DAtaFrames, but the object generated by mice is of the mids type.
As in the example below:

As my data are repeated (dependent) measures, I want to perform the analysis of generalized
equation estimation.
fit<- with(geeglm(value ~ Time+ group,
              data= IM.imputed_Data ,family=gaussian,id=ID,
              corstr="ar1"))

  summary(pool(fit))

Answer: There are two ways to do this in the mice package. First, you could use complete() to turn the imputed mids object into a dataframe containing the impute values, reshape the dataframe into long format, turn it into a new mids object with as.mids(), then fit the models with the new mids object. Second, you could place the code to reshape the data inside the with() block. I show an example of how to do that below
library(geepack)
library(mice)
#>
#> Attaching package: 'mice'
#> The following object is masked from 'package:stats':
#>
#>     filter
#> The following objects are masked from 'package:base':
#>
#>     cbind, rbind
library(tidyverse)
# This data comes in long format and has no missing values, so I
# first transform it to wide and make some values missing
koch2 <- koch
koch2$id <- factor(koch2$id)
koch2$trt <- factor(koch2$trt)
koch2 <- pivot_wider(koch2,
                     names_from = day,
                     values_from = y,
                     names_prefix = "day")
set.seed(1)
koch2[rbinom(nrow(koch2),1,0.1)==1, "day3"] <- NA
koch2[rbinom(nrow(koch2),1,0.1)==1, "day7"] <- NA
koch2[rbinom(nrow(koch2),1,0.1)==1, "day10"] <- NA
koch2[rbinom(nrow(koch2),1,0.1)==1, "day14"] <- NA
# Create imputations, using predictorMatrix to specify the
# variables used in imputations
ini <- mice(koch2,
            maxit = 0)
pred <- ini$predictorMatrix
pred[,"id"] <- 0
imp_dat <- mice(koch2,
                printFlag = FALSE,
                predictorMatrix = pred)
# fit the models to the imputed data
mods <- with(imp_dat,
             {
               dat <- data.frame(trt = trt,
                                 id = id,
                                 day3 = day3,
                                 day7 = day7,
                                 day10 = day10,
                                 day14 = day14)
               dat_long <- pivot_longer(dat,
                                        cols = contains("day"),
                                        names_to = "time",
                                        values_to = "y")
               geeglm(y ~ time + trt,
                      id = id,
                      data = dat_long)
             })
summary(pool(mods))
#>          term   estimate  std.error  statistic       df      p.value
#> 1 (Intercept)  2.0861111 0.09938558 20.9900775 259.9958 0.000000e+00
#> 2   timeday14 -0.3055556 0.09866652 -3.0968514 264.0978 2.166670e-03
#> 3    timeday3  0.4500000 0.07020265  6.4100143 118.7481 3.066805e-09
#> 4    timeday7  0.0500000 0.08668541  0.5767983 196.6644 5.647353e-01
#> 5        trt1 -0.3444444 0.10217856 -3.3710051 250.4968 8.672982e-04

If there are many variables in the imputed data, you can select all of them using dat <- data.frame(mget(ls())). If you only want some of the variables, the ls() could be replaced with a vector of character names of variables, which could be generated programmatically.
To use the complete() method I initially mentioned you need to set include = TRUE and also recalculate the .id column created by mice. Below is an example of how to do that.
all_dats <- complete(imp_dat, action = "long", include = TRUE)
working_dats <- list()
for(i in 0:max(all_dats$.imp)) {
  working_dats[[i+1]] <-
    all_dats %>%
    subset(.imp == i) %>%
    pivot_longer(cols = contains("day"),
                 names_to = "time",
                 values_to = "y") %>%
    mutate(.id = 1:nrow(.))
}
imputed_long <- as.mids(do.call(rbind, working_dats))
mods_complete <- with(imputed_long,
                      geeglm(y ~ time + trt,
                             id = id))
summary(pool(mods_complete))
#>          term   estimate  std.error  statistic       df      p.value
#> 1 (Intercept)  2.0861111 0.09938558 20.9900775 259.9958 0.000000e+00
#> 2   timeday14 -0.3055556 0.09866652 -3.0968514 264.0978 2.166670e-03
#> 3    timeday3  0.4500000 0.07020265  6.4100143 118.7481 3.066805e-09
#> 4    timeday7  0.0500000 0.08668541  0.5767983 196.6644 5.647353e-01
#> 5        trt1 -0.3444444 0.10217856 -3.3710051 250.4968 8.672982e-04

Comment: @LC-datascientist I added example code for `complete()`. You can use `data.frame(mget(ls()))` to get all columns that were in the imputed data.
Comment: The `with()` method that you show works for me. However, I cannot get the `complete(...) %>% pivot_longer(...) %>% as.mids()` approach to work; I get an error about duplicate row.names. I also want to ask, within the `with()` method, is there a more convenient way to create `dat` than to manually add each column one by one? My data frame has a lot of columns so that is a tedious task.
Answer: You could use tidyr::gather() to transform your data into long format and then use the package jomo for multiple imputation accounting for the nested structure of the data.
Comment: I tried to use ´gather´but the object generated by mice is of the mids type, and gather did not work.
Comment: Sorry, I meant using `gather()` first. Once you have the data in long format, then proceed to imputing.
Comment: teamug I thought that to use mice the variables should be in columns (Wide format) .. I will try it like this.
Comment: That is probably true, but if you want to proceed in long format, `jomo` can handle it, and specifying the cluster is pretty straightforward.
Comment: Okay, the jomo package is new to me so I research it to understand it better. I don't know if I will have enough time, but I will try.
Comment: This should help: https://www.ucl.ac.uk/population-health-sciences/sites/population-health-sciences/files/quartagno_1.pdf
Answer: Have you tried the following:
fit<- with(imputed_Data, geeglm(value ~ Time+ group,
              family=gaussian,id=ID,
              corstr="ar1"))

summary(pool(fit))

Comment: ,I did a test with other data that I have and it worked, but with my data it is not working because I couldn't change from wide format to long


How to Set OnClickListener to Card in PlaceholderView?

Question: I am using PlaceHolderView library to show an Infinite List of contents like the Facebook Android app. I was using InfinitePlaceHolderView for it. It looks like this:
And here is how it looks like output
Now If the story is large then a user can click on the card view and it will take him to a new activity where there will be a detail of that story. For this, I need to add a Listener. But I could not find any documentation at all, how to implement it. The documentation shows that all those cards are dynamically created and not any of those cards have any id so that I can put a listener.
How to implement it?
Answer: So, what I did is given below:
In my feed.xml file which contain the above view, I set an id for the whole view. Then I used that id and used it ItemView.java from here:
feed.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/home_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey_100"
    android:orientation="vertical"
    android:weightSum="4"
    tools:context="com.example.shamsad.tutionhub.activities.FeedActivity">

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:id="@+id/tbHome"
        android:background="@color/colorPrimary"
        app:titleTextColor="@color/grey_100">
    </android.support.v7.widget.Toolbar>

    <com.mindorks.placeholderview.InfinitePlaceHolderView
        android:id="@+id/loadMoreView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

ItemView.java
@Click(R.id.rootView)
    public void onCardClick() {
        Intent intent = new Intent(mContext, DetailActivity.class);
        intent.putExtra("title", mInfo.getTitle());
        intent.putExtra("caption", mInfo.getCaption());
        intent.putExtra("salary", mInfo.getSalary());
        intent.putExtra("routine", mInfo.getRoutine());
        intent.putExtra("time", mInfo.getTime());
        Log.d("sajid", "onClick");
        mContext.startActivity(intent);
    }

So, in this onCardClick() method, the clickable id is set up by this code @Click(R.id.rootView). And that's all. It basically sets the whole card-view as a clickable thing.
And also thanks to the writer of this great library Janisher Ali. I contacted him and he helped a lot, and it worked.
This is a great library. To me much better than RecyclerView. You can try it out :)
Answer: In step three of the documentation you have an example of the Event Bind:
@Animate(Animation.ENTER_LEFT_DESC)
@NonReusable
@Layout(R.layout.gallery_item_big)
public class ImageTypeBig {

    @View(R.id.imageView)
    private ImageView imageView;

    private String mUrl;
    private Context mContext;
    private PlaceHolderView mPlaceHolderView;

    public ImageTypeBig(Context context, PlaceHolderView placeHolderView, String url) {
        mContext = context;
        mPlaceHolderView = placeHolderView;
        mUrl = url;
    }

    @Resolve
    private void onResolved() {
        Glide.with(mContext).load(mUrl).into(imageView);
    }

    @LongClick(R.id.imageView)
    private void onLongClick(){
        mPlaceHolderView.removeView(this);
    }

}

More information:
https://github.com/janishar/PlaceHolderView#step-3-create-item-class-to-bind-and-define-view-operations
Comment: It actually works for only the imageview as the imageview is larger there. Whereas in my case I want to set the listener for the whole card.
Comment: Try to set your component clickable/toutchable and make sure you have no components inside the card consuming the event.


Finding expected number coin flips to get 2 consecutive heads

Question: First, I know what the right answer is, and I know how to solve it. What I'm trying to figure out is why I can't get the following process to work.
The probability that we get 2 consecutive heads with one flip is 0. The probability that we get 2 consecutive heads with 2 flips = 1/4. The probability of getting 2 consecutive heads with 3 flips = 1/6. The probability of getting 2 consecutive heads with 4 flips = 2/10 = 1/5. And the probability of getting 2 consecutive heads with 5 flips = 3/16.
Am I doing something wrong. I don't see any easy way to use these numbers to solve the original problem of finding the expected number of coin flips to get 2 consecutive heads.
Comment: [here](http://math.stackexchange.com/questions/1155104/expected-number-of-coin-tosses-to-land-n-heads/1155138#1155138) is another variant of the question.
Comment: Are you asking for a computation of the expected number of flips using the probabilities that we do it in $2$, in $3$, and so on? That can be done, though it is not the simplest way. However, the probabilities are not the ones you indicate. For example, the probability that we get our first two consecutive heads using a total of $3$ tosses is $1/8$, not $1/6$.  For $4$ it is also $1/8$.
Comment: It's hard to say why you can't get your process to work if you don't describe your process.  What is it, and in what way is it not working?
Comment: @lulu Your first link goes to a different problem where you stop if you get either HH or TT.
Comment: @ByronSchmuland  True...that's why I also posted the second link.
Answer: The problem is that your experiment is not well-defined. To solve the mentioned expectation problem, you would define the experiment as follows:
You toss a coin until you get two heads in a row and then you would stop. So there are no two consecutive heads before that.
each of the probabilities, that you have calculated in your process, is related to the following experiment:
you toss a coin n times. what is the probability of having 2 heads in a row.
By the way, according to the last experiment, you have miscalculated the probabilities in your process.
Answer: The definition of expected value in this case is:
$$E[x]=\sum_{x=2}^{\infty}xP[x]$$
and
$$P[x]=\frac{x-1}{2^x}$$
Combining these yields:
$$E[x]=\sum_{x=2}^{\infty}\frac{x^2-x}{2^x}$$
Therefore $E[x]=4$.
Comment: Your formula $P[x]=\dfrac{x-1}{2^x}$ is wrong. For instance, $P[3]=\frac18$, not $\frac14$. Did you miss the requirement that the two Heads be consecutive?


Power for experimental design

Question: It's easy to calculate power for paired t-tests and ANOVA, but how do you calculate power for more complicated designs such as split plot designs or factorial designs?
Answer: First turn your anova into a regression.  Then,
$$
N = \frac{2.84^2}{p(1-p)}\frac{\sigma^2}{MDE^2}
$$
N is your sample size, p is the proportion getting the treatment, $\sigma$ is the standard deviation of the residuals, and MDE=the minimum detectable effect that you are powered for.  2.84 comes from alpha confidence of 95% and 80% power (when you've got a lot of degrees of freedom.  With fewer degrees of freedom, you'll need to use the T distribution.  Look at the reference for details.)
The more explanatory factors you've got in your experiment the more $\sigma$ will shrink.  Knowing how much it will shrink is tricky.
At some point, analytical formulas collapse, and you're better off simply simulating your entire dataset, multiple times doing some sort of monte carlo, and fitting the desired model to each of the plausible datasets.  Your power is the proportion of times you get the result you want.  As with the analytical methods, you're only as good as your assumptions.
Source is from memory, roughly following this.
Comment: How did you obtain the 2.84? Shouldn't it should depend on N via the degrees of freedom for the t distribution?
Comment: Yes, it should.  It's 2.84 when the sample size is big and N>>p.  Normal approximation of the T.
Answer: Once beyond the simple cases like t-tests I prefer to use simulations.  When you do a simulation you control all the assumptions being made and can simulate for situations that may not be in the nice canned routines.
Here is an answer with an example of a simulation:
Simulation 1

Power for experimental design


Regression tree model splitting too far - random data column?

Question: I am attempting to make some regression trees with many potential independent variables which comprise both categorical and continuous data types of widely varying scales
i have been using a few different methods of modelling with different validation methods
ANNs,
Decision trees,
Boosted trees.
Validation with
hold back, 3 way hold back and k-fold
i have decided to focus on decision trees due to the simple ability to convey results to others.
I have also decided that due to holdback validation producing some quite different models dependent on which members are used for the validation that the dataset is too small for this
What i am left with is k-fold decision tree which appears to split too far despite no k-fold validation drop off . I was shown a method (by a SAS rep) where a variable is inserted into the model making process that is essentially junk to help identify this
using this method i have found that the 'junk' variable gets incorporated into the model sometimes quite early on and splits are performed beyond this. Is it valid to prune the tree back to remove these to be left with a more true model?
incidentally, the hold back validation method produces similar models (in terms of number of splits) as this k-fold pruned model
sorry for the long read, help would be appreciated!
Edt:
I would like to add that when using 'junk' data in holdback it never gets incorporated into the model due to the early stopping that occurs in splitting variables
Comment: Added; Y is normally distributed, consists of approx 1000 members and 100 potential Xs (after severe correlation has been removed)
Answer: Single trees have severe difficulties with predictive accuracy and stability.  Interpretability is largely an illusion.  Single trees are only interpretable because they are wrong.  Do are dealing with multiplicity problems of monumental magnitude, effectively estimating hundreds of parameters.  By the way please state the sample size and distribution of $Y$.
Comment: I have added the requested info, when using boosted methods generally what i get is the lower portions of the single trees remains very similar.


while writing into error: csv unsupported operand type(s) for +: 'float' and 'str'

Question: I am new to python. I have to write data into csv file but it is giving error

unsupported operand type(s) for +: 'float' and 'str'

with open('Csvc1s.csv', "wb") as file:
    file.write("Time, Total_network\'s_Belief, Total_network\'s_Disbelief, Total_network\'s_Uncertainty")
    file.write('\n')
    list1 = [float(i) for i in timeVar]
    list2 = [float(i) for i in beliefVar]
    list3 = [float(i) for i in disbelVar]
    list4 = [float(i) for i in uncerVar]

    for x in range(0,list1Len):
         textToWrite = (list1[x]) +  "," + (list2[x]) + "," + (list3[x]) + "," + (list4[x])
         file.write(textToWrite.rstrip())
         file.write('\n')

How can I fix this?
Comment: Do you understand the error message?
Comment: while writing data into csv i cannot write float as str
Comment: @Samradnyee. That's not what it says. It says you can't *add* a float to a str.
Comment: okay. Got it . but how could I write `list1, list2, list3, list4` data into different columns in csv. I aslo tried with `textToWrite = '{},{},{},{}\n'.format(list1[x], list2[x], list3[x], list4[x])`
Comment: `file.write(str(list1[x]) + " " + str(list2[x]) + " " + str(list3[x]) + " " + str(list4[x]) + "\n")`     this worked perfectly
Answer: As you are trying to create a CSV file, the usual approach is to use Python's CSV library. This correctly handles converting lists of data into correctly delimited rows in a file:
import csv

with open('Csvc1s.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(["Time", "Total_network's_Belief", "Total_network's_Disbelief", "Total_network's_Uncertainty"])
    csv_output.writerows(zip(timeVar, beliefVar, disbelVar, uncerVar))

zip() is used to combine multiple lists together such that each time it is iterated on, the next element from each list is returned as a list (i.e. in this case a whole row). writerows() takes a list of rows and automatically adds the necessary , between each entry and a \n for each row when writing to the file.
Note, this assumes that your four lists of data all have the same length.
Comment: done with it.. Thank you.. `zip` function is working


How to set machine hostname as docker container hostname

Question: I want to set the docker container hostname to the machine hostname on which docker is installed. Please note than I want to set the hostname dynamically and don't want to hardcode the machine hostname in my docker run command.
How do I achieve this?
My docker run command:
sudo docker run --name=rabbitmq -d -p 5672:5672 -p 15672:15672 \
-e RABBITMQ_DEFAULT_USER=admin \
-e RABBITMQ_DEFAULT_PASS=admin \
--hostname ?? \
-v rmq_vol:/var/lib/rabbitmq \
rabbitmq:3.9.0

Comment: soo `--hostname "$(hostname)"`?
Answer: What KamilCuk said.
add to docker run:  --hostname $(hostname)
You're just passing in the result of the linux "hostname" command to your docker run configuration.


linux device driver container_of macro when using arrays

Question: In one of the legacy device driver that I am using, I have a structure format as below -
struct inner_struct_containing_cdev {
   struct cdev cdev;
   ....
   ....
   /* more variables */
};

struct outer_struct {
    /* because I need 10 devices */
    struct inner_struct_containing_cdev inner[10];
    ....
    ....
    /* more variables which are common to all the 10 devices. */
};

Now in my init_module I am calling alloc_chrdev_region and other allocation related calls. Now in my open file operation with signature int open(struct inode *inode, struct file *filp) I can get access to the cdev structure and hence the inner_struct_containing_cdev. But I would like to get the pointer to outer_struct instead. In the open call I don't know which array index of the inner_struct_containing_cdev struct I received a pointer to.
Is it possible to use container_of macro in such a case? Or need to re-design the structures?
Currently I am handling the situation using a global variable. But this prevents me from having multiple instantiation.
Answer: You cannot use container_of to go from inner_struct_containing_cdev to outer_struct; you've stated the reason yourself, you don't know which index of the array you're looking at.
You need to organize your data structure like this instead:
 struct driver_instance {
    /* variables shared among all N devices go here */
 };

 struct device_instance {
    struct cdev cdev;
    /* variables particular to only one device */
    struct driver_instance *driver;
 };

You only use container_of to go from the cdev to the device_instance; then you dereference the driver pointer to get the driver_instance.  You allocate a driver_instance when your driver is initialized, and then when it spins up individual devices it makes each point to that object.  Use the core kernel's reference counting logic to know when to deallocate them.
In addition to the fact that this, y'know, works, it means you don't have to hardwire the number of devices at compile time.


Terraform init error: Failed to download module (local changes would be overwritten)

Question: I have a brand-new local Terraform project that I have just cloned from gitlab. I have not made any changes to the code, but when I run terraform init I get the following error, repeated for every module in the project:
Error: Failed to download module

Could not download module " <module name>"
(<filename>.tf:<line #>) source code from
"git::<gitlab address>":
error downloading
'<gitlab address>':
C:\Program Files\Git\cmd\git.exe exited with 1: error: Your local changes to
the following files would be overwritten by checkout:
        README.md
Please commit your changes or stash them before you switch branches.
Aborting

Every module download fails on the same file: README.md. Again, I have made no changes to any files in the project.
My initial thought was that this might be related to a line-endling issue: I am using Windows, and the module files in the remote repository were created on a Mac. To address this, I ran the command git config --global core.autocrlf true
(following the recommendations here)
I then deleted the .terraform folder and re-ran terraform init, but got the same set of errors.
What am I missing?
Answer: It seems like you are having the same issue mentioned here, which is more of a Git behaviour then Terraform. Try adding the short-term workaround mentioned in this Github issue (by adding --depth in your module source.

However, if it's running multiple git commands in series that exacerbates this problem then a short-term workaround (until this can be addressed upstream in Git) might be to set the query argument depth=1 in your source address, like github.com/foo/bar?ref=v1.2.3&depth=1. In the current implementation it happens that Terraform implements shallow clone mode by running git clone --depth=1 --branch=v1.2.3, which avoids the need for the separate checkout step although I don't recall off the top of my head whether Git will accept what looks like a tag name as a valid --branch= in this context, or whether it specifically requires a refs/heads/... reference.


howto db_select and cross join on drupal?

Question: a table:
<code>CREATE TABLE `a` (`id` int(10));INSERT INTO `a` (`id`) VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
</code>
I need to make a cross join tables in drupal using db_select:
<code>$query = db_select('num', 'n1');
$query -> fields('n1', array('i'));
$query -> innerJoin('num', '10');
$query -> fields('n10', array('i'));
watchdog(__FUNCTION__, $query -> __toString(), $query -> getArguments());
$result = $query -> execute();
$records = $result -> fetchAllAssoc('i');
</code>
get as a result:

Array ( [0] => stdClass token Object ( [i] => 0 [n10_i] => 9 ) [1] =>
  stdClass token Object ( [i] => 1 [n10_i] => 9 ) [2] => stdClass token
  Object ( [i] => 2 [n10_i] => 9 ) [3] => stdClass token Object ( [i] =>
  3 [n10_i] => 9 ) [4] => stdClass token Object ( [i] => 4 [n10_i] => 9
  ) [5] => stdClass token Object ( [i] => 5 [n10_i] => 9 ) [6] =>
  stdClass token Object ( [i] => 6 [n10_i] => 9 ) [7] => stdClass token
  Object ( [i] => 7 [n10_i] => 9 ) [8] => stdClass token Object ( [i] =>
  8 [n10_i] => 9 ) [9] => stdClass token Object ( [i] => 9 [n10_i] => 9
  ) )

watchdog:
    SELECT n1.i AS i, n10.i AS n10_i FROM {num} n1 INNER JOIN {num} n10
this query in phpmyadmin gives the "multiplication" of tables: 100 rows that I deserve.
why not works through db_select in drupal?
db_select need to connect this query to a different sample already on tables Drupal, db_query would not help me =/
Comment: Please post the SQL query string that your current code produces, and the query string that you _want_ to be produced
Comment: watchdog recorded query in the log true, this for me. as I wrote, if you run it, for example through phpmyadmin, the result we get a (http://en.wikipedia.org/wiki/Join_(SQL)#Cross_join).

the query that I need to get:
SELECT n1.i AS i, n10.i AS n10_i FROM {num} n1 INNER JOIN {num} n10

if you look a result that throws db_select, we will see that the first table is selected completely, and from the 2nd "attached" only the last line.
Comment: I should have been more clear - please edit the question, and add these two pieces of information: 1. The exact SQL query that you are _trying_ to get, and 2. The exact SQL query you are _currently_ getting with the code you've already provided. Linking to the Wikipedia page for cross joins is no good, we need to see your code if you want to get an answer
Comment: Could you also elaborate on what you mean by "db_query would not help me"? db_query runs an arbitrary SQL statement against the database, so as long your SQL query string is correct, db_query will definitely work. When you add your desired SQL output to the question we can tackle that part too
Answer: innerJoin takes 3 args: table, table_alias, and condition. ex:
<code>$query->innerjoin('node', 'n', 'c.entity_id=n.nid')
</code>
The above would produce "...INNER JOIN node n ON c.entity_id = n.nid ..." You can add the fields form node by doing:
<code>$query->fields('n', array(...));
</code>


Geometric interpretation of PBH test

Question: I need to find geometric interpretation of PBH test i.e. for any space X isomorphic to R^n and U isomorphic to R^m. A is a linear operator from X to X and B is a linear operator from U to X. Prove that the pair (A,B) is controllable if and only if X=im(A-lambda*I)+im B. where I is an identity operator from X to X and lambda is the eigen value.
I am unable to figure out how to proceed. Please help me out with this. Thank you.
Answer: This is a problem on a midterm exam that was assigned Tuesday in a graduate level controls course. As such, please refrain from providing the answer until tomorrow, as it is due at 11:30 p.m. EST today, 4/9. It is not a coincidence that it was asked yesterday, as the exam is a take-home exam and was assigned Tuesday.
So you hopefully don't delete this post immediately, I will add the answer the the question in full tomorrow morning.
Answer: Maybe what you want is the eigenvector test: The pair $(A,B)$ is controllable iff there is no eigenvector of $A^T$ in the kernel of $B^T$.

Geometric interpretation of PBH test


What service to use to backup 100+ gigs of data as mounted block-level storage?

Question: I'm looking for an online solution to mount a drive as block-level storage and perform backups on it.
I'd use S3 for this, but it's not block level.
I'd use rackspace for this, but again, it's not block level.
Dreamhost has a ridiculous amount of space for $10/mo but I'm pretty sure if they found out you are using their space for backups they'll delete your account.
Does anyone have suggestions on what service to use for this? Are there any solutions meant JUST for this?
Mount drive on the cloud as if it were a local external hd, backup/use/etc.
I'm tired of local hard drives failing.
Comment: Shopping Questions are Off-Topic on any of the [se] sites. See [Q&A is hard,
lets go Shopping](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-
shopping) and the [FAQ] for more details.
Answer: Amazon's AWS Storage Gateway might work for you, it supports iSCSI.
Answer: Realize that 100+ GBytes is going to take a LONG time to transfer over any network.  Are you sure that a local disk would not be a better idea?
Have you considered using one of those local USB disks?
Does this have to be a user oriented, managed resource or not?
If you are looking for a backup service that does this in the background, I can name about three or four that generally have good reputations but it uses a client/external server to do its work and you will not have direct access to the backup like a mountpoint.  But you will have access to backed up information on-line using either the client or a supplied website.
You have not stated which operating system, I'm assumming Linux.


Mapping all characters into another set of characters in R for a string using list

Question: How do I efficiently modify a a single string (which is to be part of a column) according to a predefined dictionary (named list) of character mappings?
Suppose I had the mapping:
map <- list('a' = 'u', 'e' = 'i', 'i' = 'o', 'o' = 'a', 'u' = 'e')

And the character vector:
imp_text <- c('aei', 'ou ei', 'iua oe')

I would like to apply some function to imp_text and obtain
c('uio' , 'ae io', 'oeu ai')

Where each character was translated according to the associations defined in map. In the future, map might contain a mapping for the entire alphabet, and imp_text might contain a very large amount of entries. How do I accomplish this? I would prefer a tidyverse approach but anything's welcome.
Answer: chartr(paste0(names(map), collapse=""), paste(map, collapse=""), imp_text)
# [1] "uio"    "ae io"  "oeu ai"

Comment: `paste(..,collapse=)` collapses a set of strings into a single string, separated by nothing, so the first reduces to `"aeiou"`, the second reduces to `"uioae"`. [`chartr`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/chartr.html) just translates from each character in the first with each character in the second.
Comment: no, this is designed for case-sensitive operations, so something like `"aAeEiIoOuU"` and `"uUoOiIeEaA"`.
Comment: One of those great answers because it uses a relatively obscure function which is simple and very fast to execute. I tried something with string-splitting and indexing and got nowhere close.
Comment: Thanks for the answer. Would you mind explaining how this works?
Comment: Ok, that is a great answer. I am thinking I could deal with the presence of uppercase letters by extending the `````map```` mapping and then applying the above all at once. Is there a more efficient way of dealing with mixed case letters when I need to preserve the original case?


Will the accidental of a mordent affect another mordent that is in the same measure?

Question:
The first mordent in this measure will be played as D , C# , D. The second mordent in the same measure doesn't have a sharp like the first mordent.
Will the sharp accidental of the first mordent affect the second mordent since they are both in the same measure?
There is a very similar question (Would an accidental in a mordant still be effective for the whole measure?); however, the question itself is not specific to this situation, and although the primary answer addresses it, it's ambiguous.
I'm looking for a documented answer to this specific case.
Comment: Related question, but when the ornament is explicitly notated: [Do accidentals on ornaments apply to the same notes elsewhere in the measure?](https://music.stackexchange.com/q/5716/70803).
Comment: It is a hypothetical question, or are you asking about some specific piece?
Comment: The 1st is a lower mordent with inflected note. The sign you wrote is for a simple mordent. Bothe different anyway!
Answer: This scenario is undefined and therefore ambiguous. It should be considered an editorial error.
From Elaine Gould's Behind Bars:

Accidentals affecting ornaments
An altered pitch should be confirmed or cancelled for an ornament later in the bar....
An accidental indicated for an ornament should be confirmed or cancelled when the pitch is reiterated later in the bar as a measured note. (p. 84)

Thus, the example given in the question should be written either as

and both played D-C#-D, or

with the first played D-C#-D and the second played D-Cnatural-D.
In the ambiguous situation, the only recourse would be:

look to original sources;
look to recorded evidence;
make a decision based on musical analysis.
Comment: Your answer makes more sense than that other guy's answer. Your answer is how I thought things should be because I thought that the accidental for an ornament (the type of ornament that is not written on the stave) only applies to that ornament that it is attached to. That other guy's answer confused me.


How to forecast number of event occurences in a certain time period?

Question: I am attempting to predict how many times a certain event will happen in a time period. For instance, predict the number of time the event will occur in the next 5 hours. I have data going back a couple years just listing the time the event occurred. Here is a graph of the total number of events vs time. I also have external variables related to the event, such as time of day or weather, which I would like to incorporate into the model.

So far, I've tried a linear regression algorithm, but proved to not be very accurate, likely due to the overall increasing trend. I also tried a neural net regression technique with a dataset consisting of the time until the end of the time period I'm predicting, the number of occurrences so far, and the total number of occurrences I am trying to predict, but it ended up just memorizing the dataset and not actually learning anything. Any help much appreciated!
Comment: Hello @Anthony Ebiner. Were you able to find a strong approach? I have tried multiple methods but none is giving me what I would like to achieve
Answer: The number of counts in a specific time period is modeled using a counting process with a deterministic or stochastic intensity. Stochastic process $N(t)$ is a counting process (point process) if

$N(t)$ takes non-negative integer values,
in each random scenario, the trajectory of $N(t)$ is piece-wise constant,
in each random scenario, the trajectory of $N(t)$ is right-continuous,
$N(t)$ is non-decreasing.

The intensity of counting process $N(t)$ is defined to be a stochastic process $\lambda(t)$ such that, for any time $t$ and shift $u$,
$$
P(N(t+u) - N(t) = 1 | N(s), 0 \leq s \leq t) = \lambda(t) u + o(u),
$$
where $o(u)$ is a function of $u$ which converges to $0$ when $u$ converges to $0$. The intensity stands for the expected number of jumps per unit of time in a very small time interval.
Counting process is a generalization of a non-homogeneous Poisson process. Non-homogeneous Poisson process jumps with a deterministic, time-varying intensity while counting process jumps with a stochastic, time-varying intensity (generally speaking). Typically, diffusion processes are used to model the intensity $\lambda(t)$. Ito diffusion is a stochastic process $X(t)$ satisfying the following stochastic differential equation:
$$
                                dX(t) = A(t,X(t)) dt + B(t,X(t)) dW(t),
$$
where $W(t)$ is Brownian motion.
In particular, if we choose to employ affine diffusions the counting process gains certain nice properties. In affine diffusions, $A(t,X(t))$ and $B(t,X(t))^2$ can be written as linear functions of $X(t)$.
This approach is the industry standard in actuarial science, derivatives pricing and survival analysis. If you have seen some simpler models, the chances are they fall within the aforementioned framework as special cases.
NOTES (addressing the follow-up questions):
1] $o(u)$ stands for "small o". The term is part of calculus. By definition, function $g(u)$ is "small o" with respect to function $f(u)$ when $u$ converges to $a$ if $g(u) / f(u)$ converges to 0 when $u$ converges to $a$.
2] Modeling jump intensity $\lambda(t)$ as a deterministic or stochastic process is a big field. Many methods and modeling ideas are part of it. $\lambda(t)$ does not always have to be complex but, in the presence of substantial amount of data, a clever diffusion-based model may improve the goodness of fit... To get acquainted with the field, please refer to the following references:

Duffie, D., & Singleton, K. (2003). Credit Risk: Pricing, Measurement, and Management. Princeton University Press.
Rausand, M. & Høyland, A. (2004). System Reliability Theory: Models, Statistical Methods, and Applications. Wiley-Interscience, Hoboken, New Jersey.
Comment: Thank you for the detailed response! I do have a couple questions. First off, what does the function *o* represent? Also, how would I figure out the *λ* equation for my data? You mention using a diffusion process such as Ito diffusion. How would I use my data to implement such a process? My apologies if these questions seem ignorant, which I am in this subject quite frankly.
Comment: @AnthonyEbiner I have edited my response to address your questions. Please see above.
Answer: A possibly simpler approach to a full-blown stochastic process would be to use standard time series forecasting tools. Bin your events in an appropriate time granularity, e.g., in hourly buckets, or even in 5-hour buckets. Then use a standard forecasting algorithm, such as exponential smoothing. I very much recommend this open online textbook.
Be aware that even the best prediction models may not reach the level of accuracy you would like to see. How to know that your machine learning problem is hopeless? may be helpful.
Comment: Two possibilities. (1) Model total events up to a regular time point, e.g., up to each time point. Any forecasting algorithm should note the positive trend and extrapolate it. Or (2) model the *incremental* events happening in each time bucket, then forecast these out, and aggregate the forecasts over time. Which approach is better can't be said beforehand.
Comment: Yet better: do both (1) and (2) and average the resulting forecasts. I suspect the result of this may be better yet than either one in isolation.
Comment: Thank you for the response and textbook recommendation, it looks like it will be very helpful. You mention exponential smoothing, and when I look at examples of its use, I see cases of it predicting a value associated with each time value, such as sales or price, which can go up or down. Since I am hoping to forecast the total number of events, a value that can only go up, could I still use this algorithm? Also, if I were to bin the events in hourly buckets, would I have each bin's value set to the total number of events up until that time, or the number of events that occurred during hour?
Comment: That makes perfect sense, thanks!
Comment: To understand your (1) @StephanKolassa; say you want to forecast number of events the next month and you have 11 month of data. Would you then create 11 samples (11 buckets of a month) use e.g exp. smoothing to forecast the number of events for the 12 month (or do I misunderstand?).
Comment: @CutePoison: I wouldn't call it 11 "samples". You just have a time series of monthly data, with each data point giving you the total number of events for that month. Then indeed use something like exponential smoothing to forecast out for one month.


Set / get viewmodel in localstorage if exist - knockout - javascript

Question: I'm retrieving my global navigation with CSOM. But it takes some time to execute. What I want is to store the ViewModel in localstorage the first time I'm loading the page.

I'm not having any problem retrieving the ViewModel but I need some
help to check if the viewmodel exist / get view model / set
viewmodel correct.
What's the best way to check if viewmodel has changed? (example code)

JS - check (not working properly)
  if (localStorage.getItem('GlobalNavigation') == null) {
        $_global_Mavention_GlobalNavigation_Some_Other_Stuff();
    } else {
        var retrievedData = JSON.parse(localStorage.getItem('GlobalNavigation'));
        ko.mapping.fromJS(GlobalNavigation, {}, self);
        $_global_Set_GlobalNavigation_Node_Active();
    }

HTML

JS
Mavention.GlobalNavigation.loadNavigationInternal = function () {
var context = SP.ClientContext.get_current();
var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
var termStore = taxonomySession.get_termStores().getByName(this.termStoreName);
var termSet = termStore.getTermSet(this.termSetId);
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(Function.createDelegate(this, function (sender, args) {
    var termsEnumerator = terms.getEnumerator();
    var menuItems = new Array();

    while (termsEnumerator.moveNext()) {
        var currentTerm = termsEnumerator.get_current();
        Mavention.GlobalNavigation.viewModel.globalMenuItems.push(new Mavention.GlobalNavigation.MenuItem(currentTerm.get_name(), currentTerm.get_localCustomProperties()['_Sys_Nav_SimpleLinkUrl']));
    }

    ko.applyBindings(Mavention.GlobalNavigation.viewModel);
    localStorage.setItem('GlobalNavigation', Mavention.GlobalNavigation.viewModel);
    SP.UI.Notify.removeNotification(this.nid);
    $_global_Set_GlobalNavigation_Node_Active();
    $("#customGlobalNavigation > div").show();
}), Function.createDelegate(this, function (sender, args) {
    alert('The following error has occured while loading global navigation: ' + args.get_message());
}));
};

Answer: You can set and get from local storage like this:
private saveGlobalNavigationToLocalStorage() {
    localStorage.setItem('GlobalNavigation', JSON.stringify(this.YOUR_OBJECT));
}

public getGlobalNavigation() {
    // check if it exists already
    if (!localStorage.getItem('GlobalNavigation')) {
        // If NOT - Perform your get & assign value to this.YOUR_OBJECT

        // Then call the save method to add to local storage
        this.saveGlobalNavigationToLocalStorage();
    } else {
        // Otherwise return object from local storage
        this.YOUR_OBJECT(JSON.parse(localStorage.getItem('GlobalNavigation')));
    }
}


Apache 2.4 on MacOS suddenly wrong permissions

Question: Suddenly my local installation of Apache 2.4 on MacOS Yosemite stopped working.
The problem seems to be related with permissions, but I can't find a way out.
After several hours and reading several posts, the situation is now:
Error:
<code>[authz_core:debug] [pid 35232] mod_authz_core.c(799): [client 127.0.0.1:55992] AH01626: authorization result of Require valid-user : denied (no authenticated user yet)
[core:crit] (24)Too many open files: [client ::1:53498] AH00529: /Users/username/Sites/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable and that '/Users/username/Sites/' is executable
</code>
(I don't have such .htaccess file). Anyway, I enforced brutally 777 permission everywhere:
<code>$ chmod -R a+rwx /Users/username
$ ls -l /Users/username
drwxrwxrwx  187 username  staff      6358 Dec 13 16:05 Sites
$ ls -l /Users/
drwxrwxrwx+ 174 username  staff  5916 Dec 13 16:39 username
</code>
My directive in httpd.conf is as follow:
<code><Directory "/Users/username/Sites/">
    Options +Indexes +FollowSymLinks +ExecCGI
    AllowOverride All
    Order allow,deny
    Allow from all
    #Require all granted - tried, doesn't matter
</Directory>
</code>
I can get rid of AllowOverride, but I do really need .htaccess AND anyway the problem with permission is still present for many images and resources in my virtual hosts.
As suggested by somebody, I changed apache user inside httpd.conf
<code>#User _www
#Group _www
User username
Group staff
</code>
Still the same.
Comment: Changing permissions won't help with "Too many open files". Restart your computer.
Comment: @MichaelHampton actually that's the error showing already after restarting the computer
Comment: @MichaelHampton well, as you suggested I focused on "too many open files" problem. I checked with lsof and there where 351 open files for httpd. I disabled all my Vhost except one and now it seems stable. I still don't understand what could have been changed that lowered my limit, nor I understand how to raise it again...
Answer: What are your hit counts/day? If they are high you could try changing your caching settings. It could be that you are keeping files opened in an attempt to improve your response times. How many virtual domains are you hosting? What is the (approx.) total file count for your vhosts? This seems like it could be a performance tuning problem...
Comment: it's just for local development, so hit count it's not an issue here. Apache is not starting! I have around 130 virtual hosts. What I believe is that probably apache is trying to check all folders on my Sites directory for .htaccess on starting. Number of folders can be then in the range of thousands. I don't understand what has changed in my configuration, because it worked until last week.


Atualizações e mudanças na versão do App

Question: Tenho algumas dúvidas sobre atualizações e mudanças na versão de um aplicativo.
Eu fiz a publicação de um app na Play Store e não alterei nada em meu AndroidManifest. Ficou da seguinte maneira:
package="com.app"
android:versionCode="1"
android:versionName="1.0"

O que eu gostaria de saber é: como funciona o VersionCode e o VersionName, e, na postagem de uma atualização, quais as alterações que ocorrem nos mesmos? Devo seguir uma ordem numérica? E alguns apps e softwares tem versões do tipo: 1.1.4. Podem me explicar isto?
Valeu!
Answer: O versionCode não é mostrado ao utilizadores e por isso é um numero interno incremental para diferenciar as varias versões, e que permite ao sistema Android não deixar o utilizador instalar um aplicativo com versão inferior ao que já lá está. Da mesma forma também não será possível colocar na Play Store uma versão com um versionCode inferior ao que está lá.
As boas práticas dizem que a cada nova versão o versionCode deve aumentar de 1 em 1.
O versionName é a versão que os utilizadores vem, logo é apenas texto, podendo o programador escrever coisas como:
versionName="1.1-demo"

Tipicamente este estilo de versões segue o seguinte padrão de nomenclatura:
<major>.<minor>.<point>

Em que <major> é a numeração de versão para quando tem alterações muito grandes, o <minor> é quando tem pequenas adições de funcionalidades, e o <point> são regra geral só pequenas correções.
Logo de 1.1.14 para 1.1.15 seria apenas pequenas correções de coisas que não tinham ficado corretas.
De 1.1.14 para 1.2 seria uma adição de uma ou outra pequena funcionalidade.
De 1.1 para 2.0 seria uma diferença muito larga e/ou modificação em grande parte das funcionalidades de toda a aplicação, que pode até ser incompatível com versões anteriores.
Documentação oficial para versões de aplicações pela Google
Comment: Muito obrigado, não tenho mais dúvidas em relação a isto!


correct thumb position?

Question: I have been playing guitar for 1.5 year.. and I have practiced long hours and I can switch between chords smoothly in 1 1/3 second 5 or 6 of them.
unfortunately at some point in my learning process I started stretching my thumb parallely to the neck all the way to the nut and touching, to pivot around it while holding difficult chords such as G..
a few hours ago I was playing a riff and I experienced the pain of the terrible position of thumb I have developed habit of..
I looked up youtube and found this video on where to place the thumb

It seems doable and I am able to do it... but it also means I have to redo a lot of practice probably for another couple of weeks at least if I put in an hour daily...just want to get an opinion I am doing it correctly this time, and I won't need to redo everything again at some later point.
Comment: may be it was just one off thing, I can continue doing it? will it cause me any long term harm...
Comment: Never listen to anyone on YouTube who tells you the correct way to place your thumb, there is no correct way. It's a very personal thing, lots of questions on here ask the same question, I always recommend practice (as an exercise not a performance technique) to play without placing you thumb on the neck at all. If you are relying on thumb position or have this kinda pain your grip is too tight.
Answer: It's probably not so much where your thumb goes - and let's face it, that varies from chord to chord, shape to shape, and indeed person to person.
It's more likely you're squeezing the neck too tightly. There really is no need on most shapes, if any at all. In fact, you should be able to play clean barre chords with the thumb off the back of the neck. Not saying that's a great way to do it, just saying you need hardly any pressure from the thumb to play chords.
It also may be the set-up of your guitar. If the action is high and the strings tight, you'll need to press harder, which will show in the form of pain.
You could also consider how you wear the guitar. The angle looked at from above, that looked at from the side, the height you sling your guitar at. All these factors would have been brought to your attention by a good teacher, and it looks like that's you, now!
Pain anywhere is the body saying 'I've had enough for now'. Maybe play for less time each time. I see little credit in working through that pain at your stage.
Answer: If you feel pain playing chords I would consider that is extremely recommended to correct your position, before things get worse. I've experienced this same problems when playing chords progession during long time, or just even when playing a whole song that uses chord progressions, and, after some testing changing positions and modifying the way I handle the guitar neck, it left evidence that all the pain I was suffering was caused by long term practice holding the neck in not very advisable positions.
It's true that a lot of guitar players use to play holding guitar in some particular ways, and it's a fact that this worked for them. As each one of us has different physical conditions, some guitarists may experience problems (mostly during his first steps), and even pain, when executing some tricky tecniques or depending on the fingers, wrist or arm position, and others don't. That's because I would recommend you changing this, as I must inlcude myself in the first group, and the time spent practicing to correct this yielded positive results.
By the way, and as subjective contribution, I found very useful Justin Sandercoe videos (as the one you provide on your post), specially on this matters, due to the clear exposition as he is a good communicator.  Despite this, don't dismiss checking other options or and search more alternatives, as there may be some more valuable advices for your situation.
Comment: Thanks. i never took any guitar lessons, may be I should have. but there are so many things which goes to learn guitar, thumb placement could have been easily missed... I have a friend who introduced me to guitar. might seek his advice.. I am still a beginner and changing my thumb position was relatively easy and I am not going to lose a lot. Since he has been playing for decades, might follow his method and use it.. if it didnot hurt him for a decades it shouldn't hurt me too..the only  Justin Timberlake I know is singer.. does he make guitar tutorials too?  Thanks for answering..
Comment: https://www.youtube.com/watch?v=PP8sYOw_8g0
this video shows his thumb position clearly which is on top of 6th string.. I put my thumb parallel to guitar neck touching the nut...
Comment: I'm sorry for the error, it's my fault. It's Justin Sandercoe (sometimes my mind plays tricks on me...), the one who speaks in the video you posted. I already updated my post.
Comment: I must admit that guitar clasess were very positive for me as well, as you could get rid of this kind of trouble sooner if someone pays attention actively to your playing style and your fingers placement. But this requires a good teacher, and it would help you further more specially if he has experienced same problems as you. I must admit that I was lucky on this matter, as my teacher at that time was a very good classical guitarists, always concerned for positioning and ergonomics. You are welcome, don't forget to mark the answer as helpful if this helped. Hope your problem get solved soon!
Comment: Thanks. I will look into guitar teacher.. it is expensive where I live, and I did spend some money on guitar in beginning but it was all online.... I need a few lessons to correct my thumb position though.. Sorry I don't have 15 points to upvote an answer yet. your answer was very helpful!!
Comment: Ok, thanks anyway! You are right, it's usually expensive in a lot of places. You could try checking following advice from the video you send, and also search for more information, as I stated before, probably it's your best option now. Good luck, friend!
Comment: Forgot that on my first answer, and it's very important, but was mentioned on the other answers (by Lazy and Tim, respectively): the amount of pressure you are applying, specially with your thumb, but also for the rest of the fingers. It was a key point for my case, too, as I was generating too much tension pressuring harder than I needed.
Comment: Thanks. I started taking in person classes from a very good teacher... he corrected a lot of things.. i switched to  classical cause I listened to Jerome Mouffe and now I can play F chord as well.. it is still a lot of work to do... but seems like my long hours practice is giving me results finally.
Comment: I'm very glad to hear that. Experiencing pain while playing it's one of the worst things that could happen to make people giving up, it's really sad to know about such cases, but it's hard to help others in the distance. Having with you a good teacher will absolutely help you to step forward. Seriously, it's awesome that you have finally found someone to help you closely to achieve this. Hope your illusion and efforts last for long, so you could enjoy the rewarding feeling of music!
Answer: If you feel pain while playing you should absolutely not continue but try to change what causes the pain. Else you might cause permanent damage to your hand. Pain in muscles is usually fine, as these will grow stronger, but you should be very careful about pain in joints and tendons, as the first will not grow stronger in any way and latter will only do so very slowly.
The critical part here is not nescessarily where exactly your thumb is, your thumb needs to be mobile to play complex stuff. Instead you should think about how much and in what directions pressure is applied on your thumb.
The thumb joint is made for moving forward and backward, so it does not handle sideways pressure very well. Also you should not bend the tip of your thumb outwards. The thumb joint takes pressure into the joint very well, but when you press with a bent out thumb you direct the pressure out of the joint, which the joint does not take well at all.
The thumb in the thumbnail of the given video is already rather flat. Try to keep your thumb tip even just slightly curved inwards. This also enables you to open your hand better an thus move your fingers more freely over the fretboard.
Also it might be that you are pressing harder than you need to. And maybe you subconciously press too hard with your thumb. You are already taking part of the grip pressure by holding the corpus of the guitar against your chest, so you do need to hold less of that gripping force with your thumb.

correct thumb position?


Azure AD users are not moving to license group automatically

Question: I have created Dynamic Group for assigning License to All Azure AD user automatically using powershell in production Environment.
Here is my script:
`New-AzureADMSGroup -DisplayName "us_demo_group" -Description " your Descriptions-MailEnabled $False -MailNickName "group" -SecurityEnabled $True -GroupTypes "DynamicMembership" -membershipRule "(user.department -contains ""Marketing"")" -membershipRuleProcessingState "On"
Add-AADGroupLicenseAssignment -groupId "a5e95316-1c03-44d7-afac-efd0e788122c" -accountSkuId "your skuid:FLOW_FREE"
`
My script is working fine, but when I tried to create a bulk users using Excel File, Users are not getting License, always showing **No License assignment Found **.
Any help is appreciated.
Answer: I tried to reproduce the same in my environment to assign the license to Azure AD user dynamically using power shell
I have created Azure dynamic group using powerShell, name-TestGroup1 with condition.
<code>#Install  AzureADLicensing Module
Install-Module -Name AzureADLicensing
#Import AzureADPreview
Import-Module AzureADPreview
#Connect to Azure AD
Connect-AzureAD
New-AzureADMSGroup -DisplayName "TestGroup1" -Description "This group contains information of users from us domain" -MailEnabled $False -MailNickName "group" -SecurityEnabled $True -GroupTypes "DynamicMembership" -membershipRule "(user.department -contains ""Finance"")" -membershipRuleProcessingState "On"
</code>

TestGroup1 created once execute the above code.

Assign the license to group, like below
<code>#Get All License with SKUID
Get-AADGroupLicenseAssignment -All
</code>
You can fetch the group ID, like below.

<code>#Assign License to Group
Add-AADGroupLicenseAssignment -groupId "GroupIDObject ID" -accountSkuId "Your SKUID"
</code>

Create bulk user in Azure Active Directory, like below.
Azure Portal > Default Directory > Users > Bulk Operations > Bulk Create

Make sure mention the department value for moving the users to dynamic group automatically.

Download the excel file and add the value in excel and save, like below.

Once add the value in excel and Upload the excel to Azure, like below.

Successfully created bulk- users with license in Azure AD.

You can view the users in assigned group.

License assigned to group users automatically.

Successfully assigned Azure license to created users.


Neo4j - Duplicates Despite Using Merge

Question: I am attempting to generate a database using MERGE statements through Neo4JPHP. All of my queries are using MERGE; however, it is generating separate nodes every time, resulting in massive duplication.
The queries are run within a single transaction. I've removed the surrounding code to focus on the queries:
$transaction = $client->beginTransaction();

while(...) {
    $pq = new Query($client, 'MERGE (n:Page {url:"'.$page.'"}) SET n.title="'.$title.'"');
    $transaction->addStatements(array($pageQuery));

    $h1Query = new Query($client, 'MATCH (n:Page {url:"'.$page.'"}) SET n.h1s = "['.implode(", ", $h1s).']"');
    $transaction->addStatements(array($h1Query));

    $scriptQuery = new Query($client, 'MATCH (n:Page {url:"'.$page.'"}) MERGE (n)-[:CONTAINS_SCRIPT]->(s:Script {url:"'.$s.'"})');
    $transaction->addStatements(array($scriptQuery));

    $styleQuery = new Query($client, 'MATCH (n:Page {url:"'.$page.'"}) MERGE (n)-[:CONTAINS_STYLESHEET]->(s:StyleSheet {url:"'.$s.'"})');
    $transaction->addStatements(array($styleQuery));

    $otherPageQuery = new Query($client, 'MATCH (n:Page {url:"'.$page.'"}) MERGE (n)-[:LINKS_TO]->(m:Page {url:"'.$match.'"})');
    $transaction->addStatements(array($otherPageQuery));
}

$transaction->commit();

Now, after running this across a couple of pages, it comes up with 6 copies of the same Pages, one with title and h1s elements, and the rest without.
I also tried using CREATE UNIQUE, but this gave an error that the syntax wasn't supported.
I am running Neo4j 2.0.1. Any suggestions?
Answer: When you use MERGE on matches with relationships in Cypher, the entire object is being matched or created. When a match cannot be found, the entire object is created.
For example:
MERGE (n:Page { url: "http://www.neo4j.org" })
RETURN n

Gets or creates the Page with the property url set to http://www.neo4j.org. This statement will never create a duplicate node.
Now let's assume that this node now exists within the Neo4j database and then we run the following query:
MERGE (n:Page { url: "http://www.neo4j.org" })-[:CONNECTED_TO]->(test:Test { id: "test" })
RETURN *

This will attempt to match the entire pattern and if it does not exist, it will create the entire path regardless of whether or not the Page node exists.
To resolve your issue, make sure that you use MERGE to get or create your individual nodes first. Then you can use MERGE to get or create the relationship between the two nodes.
Example:
MERGE (n:Page { url: "http://www.neo4j.org" })
MERGE (s:StyleSheet { url: "http://www.neo4j.org/styles/main.css" })
MERGE (n)-[:CONTAINS_STYLESHEET]->(s)
RETURN *

Comment: Well, I guess it didn't work the way I expected. That seems to have fixed it. Thanks!

Neo4j - Duplicates Despite Using Merge


Select an item in dropdownlist using jquery

Question: I am using the following to code to bind a dropdownlist using jquery
if ($("#status_input option[value='" + status + "']").length > 0) {

    $('#status_input').val(status);
}
else {

    $('#status_input').get(0).selectedIndex = -1;
}

in status i am getting "1", i am not getting any error, but not able to bind the dropdownliast as well as this stops the working code, means when i am commenting this code the reset information bind successfully but, when i am using this code, it does not throw any error as well as not binding the Results.
Please help me how can resolve this.
UPDATE::'
My HTML is::
<asp:Repeater ID="OffersRepeater" runat="server">
<ItemTemplate>

            <%# DataBinder.Eval(Container.DataItem, "OfferId") %>

            <%# DataBinder.Eval(Container.DataItem, "ActiveStatus")%>

            <%# DataBinder.Eval(Container.DataItem, "Partner") %>

            <%# DataBinder.Eval(Container.DataItem, "Description") %>

            <%# DataBinder.Eval(Container.DataItem, "ImageSource") %>

            <%# DataBinder.Eval(Container.DataItem, "Url") %>

            <%# DataBinder.Eval(Container.DataItem, "UrlText") %>

            <%# DataBinder.Eval(Container.DataItem, "Email") %>

            <%# DataBinder.Eval(Container.DataItem, "Phone") %>

            <%# DataBinder.Eval(Container.DataItem, "IsActive").ToString().ToLower()=="true" ? "1" : "0" %>

            <%# DataBinder.Eval(Container.DataItem, "ApprovalDate") is DateTime ? ((DateTime)DataBinder.Eval(Container.DataItem, "ApprovalDate")).ToString( "MM-dd-yyyy") : "" %>

            <%# DataBinder.Eval(Container.DataItem, "StartDate") is DateTime ? ((DateTime)DataBinder.Eval(Container.DataItem, "StartDate")).ToString( "MM-dd-yyyy") : ""%>

            <%# DataBinder.Eval(Container.DataItem, "EndDate") is DateTime ? ((DateTime)DataBinder.Eval(Container.DataItem, "EndDate")).ToString( "MM-dd-yyyy") : ""%>

            <%# DataBinder.Eval(Container.DataItem, "LegalInformation") %>

            <%# DataBinder.Eval(Container.DataItem, "Twitter") %>

            <%# DataBinder.Eval(Container.DataItem, "Facebook")%>

            <%# DataBinder.Eval(Container.DataItem, "LegalOnOfferPage")%>

            <%# DataBinder.Eval(Container.DataItem, "Season")%>

                <span class='<%# DataBinder.Eval(Container.DataItem, "ActiveStatus")%>'>
                <%# DataBinder.Eval(Container.DataItem, "Partner") %>

</ItemTemplate>
</asp:Repeater>

here is that DRPDOWN

    OFFER STATUS

<select id="status_input" class="form_input" style="width: 308px;">
    <option value="1" selected="selected">ACTIVE</option>
    <option value="0">DEACTIVATED</option>
</select>

MY JQUERY CODE IS ::
function editOffer(link) {

$('#offerEntryBox').data('offer', $(link).parents('.grid_row'));
$('#offerEntryBox').data('category', $(link).parents('.grid').parent());
alert('hi');
resetForm();

$('#offerListBox').fadeOut('fast', function () {
    $('#offerEntryBox').fadeIn('fast'); doResize();
 });
}

and the function in which i am facing problem is :: resetForm();
function resetForm() {

var partner = '', categoryID = '', url = '', urlText = '', email = '', phone = '', startDate = '', endDate = '', description = '', legal = '', image = '', twitter = '', facebook = '', status = '1', Season='';

var myOfferEditor = $find(offereditorname);
var myLegalEditor = $find(legaleditorname);
$('#Legendbox').css('display', 'none');
var offer = $('#offerEntryBox').data('offer');
if (offer != null && offer != undefined) {
    $('#offerEntryBox').find('.form_title').text('EDIT OFFER');

    partner = $(offer).children('.offer_partner').text();
    url = $(offer).children('.offer_url').text();
    urlText = $(offer).children('.offer_url_text').text();
    email = $(offer).children('.offer_email').text();
    phone = $(offer).children('.offer_phone').text();
    startDate = $(offer).children('.offer_start_date').text();
    endDate = $(offer).children('.offer_end_date').text();
    description = $(offer).children('.offer_description').html();
    legal = $(offer).children('.offer_legal').html();
    image = $(offer).children('.offer_image').text();
    status = $(offer).children('.offer_status').text();
    twitter = $(offer).children('.offer_twitter').text();
    facebook = $(offer).children('.offer_facebook').text();
    Season = $(offer).children('.offer_Season').text();
}
else
    $('#offerEntryBox').find('.form_title').text('NEW OFFER');

var category = $('#offerEntryBox').data('category');
if (category != null && category != undefined)
    categoryID = $(category).children('.category_id').text();

$('#partner_input').val(partner);
$('#url_input').val(url);
$('#url_text_input').val(urlText);
$('#partner_email_input').val(email);
$('#phone_input').val(phone);
myOfferEditor.set_html(description);
myLegalEditor.set_html(legal);
$('#twitter_input').val(twitter);
$('#facebook_input').val(facebook);

 alert(status);
//    if ($('[id$=category_input option[value=22]').length > 0) {
//        alert(categoryID);
//    }
//    if ($("#category_input option[value='" + categoryID + "']").length > 0) {
//        $('#category_input').val(categoryID);
//        alert('entered 1');
//    }
//    else {
//        $('#category_input').get(0).selectedIndex = -1;
//        alert('entered 2');
//    }

if ($("#status_input option[value='" + status + "']").length > 0) {

    $('#status_input').val(status);
}
else {

    $('#status_input').get(0).selectedIndex = -1;
}
$('#start_date_input').val(startDate);

$('#end_date_input').val(endDate);
validateDate($('#start_date_input'));
validateDate($('#end_date_input'));

$('.form_input', '#submit_offer_form').not('select, #start_date_input, #end_date_input').each(function () {
    $(this).siblings('.form_field_text').text($.trim(this.value) == '' ? $(this).siblings('.form_field_text').attr('title') : this.value);
});
$('select.form_input', '#submit_offer_form').each(function () {
    $(this).css('display', 'none');
    $(this).siblings('.form_field_text').text($.trim(this.value) == '' ? $(this).siblings('.form_field_text').attr('title') : $(this).children('option:selected').text())
});

$('#image_preview_container').children('img').remove();
if (image != '' && contentPath != undefined) {
    $('#image_source_input').val(image);
    loadPreview(contentPath, image, $('#image_preview_container'), 195, 98);
}

setBoxHighlight($('.form_field', '#submit_offer_form').add($('#image_source_input').parents('.form_part')), false);
$('.form_status_message').text('');
 setFormInteraction(true);
}

Comment: can you provide a fiddle
Comment: @EhsanSajjad i have posted my code here... don't know how to create a fiddle
Comment: @raman can you re-edit? there is lot of unnecessary spacing in second code block.
Comment: anything on the console? to create a fiddle, signup to jsfiddle.net then paste your code there then get the link paste here..
Comment: @DhavalMarthak please check the question it is there
Comment: @raman Then that dropdown block is enough no need to have that repeater code in post :)
Comment: @DhavalMarthak i have posted because all the data is coming from that repeater...
Answer: I have resolved out the issue actually the value is containing the white space. that's why it didn't get the exact value. i have just trim the string value to resolve the issue.


LilyPond - compile midi output only

Question: Is there a way/command-line option, to make LilyPond only compile the \midi {} output, even though there is a \layout {} block in  the source.ly file?
Just been going through The Command Line Options in the Documentary and the only thing I can find for "midi" is the option to change the output file extension with:
midi-extension  "midi"  Set the default file extension for MIDI output file to given string.

Answer: You can add -dbackend null to your command, which will suppress the output of a printed score. Alternatively, you can use -dno-print-pages. A midi file will still be generated, as long as a \midi{} block is defined in your score.
So, you command should look like this:
lilypond -dbackend=null my_file.ly

Or like this:
lilypond -dno-print-pages my_file.ly

LilyPond - compile midi output only


Existe alguma diferença nessas duas querys?

Question: Existe alguma diferença nessas duas querys? Qual a diferença de se utilizar o parenteses no and?
SELECT *
FROM produto
WHERE grupo = 'bebidas'
AND preco < 10 OR estoque <= 100
ORDER BY estoque DESC;

SELECT *
FROM PRODUTO
WHERE grupo = 'bebidas'
AND (preco < 10 OR estoque <= 100)
ORDER BY estoque DESC;

Comment: eu faria a segunda por ser "defensiva" amanhã alguém precisa alterar , digamos colocar a condição "AND item_ativo= 'S' a 1ª ficaria errada (sem edição) a 2ª não.
Comment: https://stackoverflow.com/a/1241158
Answer: É uma questão de precedência e associatividade de operadores. Quando usa uma expressão composta de AND e OR, ou seja, de operadores relacionais, que são aqueles que avaliam valores "binários" e geram novos de acordo a álgebra booleana (veja tabela verdade e mapa de Karnaugh).
O AND é como se fosse uma multiplicação e o OR é como se fosse uma adição, então sem parênteses que mude esta precedência, o que está próximo do AND é usado prioritariamente em detrimento do que está próximo do OR.
Então leia os códigos assim para entender melhor:
(grupo = 'bebidas' AND preco < 10) OR estoque <= 100
grupo = 'bebidas' AND (preco < 10 OR estoque <= 100)

Como o AND tem precedência natural definida pela linguagem os parênteses não são necessários no primeiro, mas obrigatórios no segundo para dar a semântica pretendida nela.
De fato há quem diga, e eu concordo, que para estes operadores sempre deveria usar os parênteses para deixar claro e explícito qual é a intenção e evitar enganos sem querer. Há quem diga que deveria fazer para todos os operadores, mas isto seria exagerado, alguma não menos intuitivos que outros para um humano "normal".
Para tentar fazer uma leitura do que é cada expressão, que nosso amigo tentou mas ficou muito confuso, por isso devem ter negativado:

Tudo que seja do GRUPO de "bebidas" E ao mesmo tempo tenha PREÇO inferior à 10. Mas se esta condição não for atendida, pode pegar um produto que tenha o estoque igual ou inferior à 100, portanto se algo tiver estoque abaixo desse limite conta como alfo a ser considerado na seleção, não importa de que grupo pertence ou qual é o preço. O que me parece bem incoerente e parece um erro.

Tudo que seja do GRUPO de "bebidas" E cumpra pelo menos uma das duas condições a seguir: tenha PREÇO inferior à 10 OU tenha o estoque igual ou inferior à 100. neste caso ser do grupo "bebida" passa ser obrigatório para todos. O que também parece errado, mas quem sou eu para falar sem saber qual é o problema. Tem cara que deveria ser tudo válido e aí deveria ter 2 AND, o que dispensaria parênteses, embora possa colocar para deixar mais legível, ainda que neste caso mude pouco.

Outra questão de legibilidade é que ficou pouco visível onde é cada cláusula, seria melhor colocar o WHERE em uma linha só ou indentar:
SELECT *
FROM PRODUTO
WHERE grupo = 'bebidas' AND
    (preco < 10 OR estoque <= 100)
ORDER BY estoque DESC;

Coloquei no GitHub para referência futura.
Answer: Muita diferença. Quando colocamos um parenteses, tudo o que está dentro dele será considerado apenas um resultado. No seu exemplo, o primeiro select tem TRÊS condições INDIVIDUAIS: ele trará todos os registros que pertencerem ao grupo 'bebidas', o preço for menor que 10 OU (atenção ao 'ou') estoque menor/igual a 100. Se existir um produto com grupo 'comidas' e estoque igual a 9, ele irá aparecer porque a última condição foi satisfeita.
Já o segundo select tem DUAS condições: pertencer ao grupo 'bebidas' e possuir uma das características mencionadas no parenteses, já que o 'ou' agora pertence à expressão interna. A primeira condição não é negociável. Somente produtos pertencentes ao grupo 'bebidas' serão relacionados se possuírem preço ou estoque de acordo com o filtro. Aquele produto do grupo 'comidas' não apareceria no segundo select.
Answer: Eu tenho visto muitos SELECTs e IFs dentro da programação, e confesso que fico pensando como a pessoa faz pra manter o código coeso... claro que um pouco de atenção ajuda, mas a utilização de "()" não vai cair sua mão e no meu ponto de vista deixa a programação muito mais organizada.
Exemplo sem ():
SELECT * FROM TABELA WHERE CAMPO_A >= VALOR AND CAMPO_B <= VALOR AND STATUS = 'A'

Com ()
SELECT * FROM TABELA WHERE (CAMPO_A >= VALOR) AND (CAMPO_B <= VALOR) AND (STATUS = 'A')

Agora veja um exemplo onde você pode ter um erro pela falta de ()
SELECT * FROM TABELA A
WHERE CAMPO <= B.VALOR * C.VALOR - D.VALOR
INNER JOIN TABELA_B B ON(B.CODIGO = A.CODIGO)
INNER JOIN TABELA_C C ON(C.CODIGO = A.CODIGO)
INNER JOIN TABELA_D D ON(D.CODIGO = A.CODIGO)

Sabemos que a multiplicação será executada primeiro, mas e se você quisesse primeiro a subtração?
Para você não ter que reescrever todo o código é só usar ()
SELECT * FROM TABELA A
WHERE CAMPO <= B.VALOR * (C.VALOR - D.VALOR)
INNER JOIN TABELA_B B ON(B.CODIGO = A.CODIGO)
INNER JOIN TABELA_C C ON(C.CODIGO = A.CODIGO)
INNER JOIN TABELA_D D ON(D.CODIGO = A.CODIGO)

O uso de () não é só questão de visualização, ele é muito importante e deve ser levado em conta
2 * 1 - 1

É diferente de
2 * (1 - 1)

Answer: Bom falando sobre o from, poderá ter diferença se o Case-sensitive (é um anglicismo que se refere a um tipo de análise tipográfica da informática. Em língua portuguesa, significa algo como "sensível à caixa das letras" ou "sensível a maiúsculas e minúsculas") estiver habilitar no DB (Banco de Dados).
Caso contrario as duas tera o mesmo resultado.
Sobre o where pode ter diferenças no resultado final pois a primeira vc esta colocando o condicional como "grupo = 'bebidas' AND preco < 10" sendo verdade ou "estoque <= 100" verdade, para a segunda vc esta colocando o condicional como "grupo = 'bebidas'" verdade e "preco < 10" verdade ou "estoque <= 100".
:)


Almost sure convergence of sequences that are equal in distribution

Question: I got two sequences of random variables $(X_n)_{n \in \mathbb N}$ and $(Y_n)_{n \in \mathbb N}$ and know that
1) $X_n \to 0, \, n \to \infty,$ almost surely
2) For all $n \in \mathbb N$ the sequences are equal in distribution: $X_n \stackrel{d}{=} Y_n$
Now I'm wondering, does this imply that also $Y_n \to 0, n \to \infty,$ almost surely?
Answer: I don't have a simple counterexample at the moment but you can argue using Skorohod's Theorem: let $(Y_n)$ tend to $0$ is probability but not almost surely. Since $Y_n \to 0$ in distribution Skorohod's Theorem tells us that there exits random  variable $X_1,X_2,...$ such that $X_n \to 0$ almost surely and $X_n$ has same distribution as $Y_n$ for each $n$.
Reference: https://eventuallyalmosteverywhere.wordpress.com/2014/10/13/skorohod-representation-theorem/
A better example: consider $[0,1)$ with Lebesgue measure. Arrange the intervals $[\frac {i-1} {2^{n}},\frac i {2^{n}})$, $1 \leq i \leq 2^{n}$, $n  \geq 1$ in  as sequence using the 'natural' ordering. Let $Y_1,Y_2,..$ be the indicator functions of these intervals. Now form $X_1,X_2,...$ by replacing $[\frac {i-1} {2^{n}},\frac i {2^{n}})$ by $[0,\frac 1 {2^{n}})$ for each $i$. Then $X_n \to 0$ almost surely, $Y_n$ does not tend to $0$ almost surely and $X_n$ has the same distribution as $Y_n$ for each $n$.
Comment: @Ak19 Thank you very much.
Comment: Thanks. So if I get this right, this means the statement does not hold on the original probability space that $(X_n)_n$ and $(Y_n)_n$ are defined on, but using Skorohods theorem I can define those sequences on some other space in which the almost surve convergence of $(Y_n)$ holds?
Comment: Yes, it may be possible to give  a better example but this is what I have at the moment.
Comment: @Bazzan I have now given a better example.
Comment: thank you, this makes it clear
Comment: @KaviRamaMurthy Congrats on $100k$ rep sir!


buiding bsp using make file in vxworks

Question: I am maintaining existing BSP in vxworks and we have make file as shown below
<code>CPU = CPU32
TOOL    = gnu

TGT_DIR = $(WIND_BASE)/target

include $(WIND_BASE)/target/h/make/defs.bsp
include $(WIND_BASE)/target/h/make/make.$(CPU)$(TOOL)
include $(WIND_BASE)/target/h/make/defs.$(WIND_HOST_TYPE)

MY_PATH = C:\source\BSP\

/* Build for CPU32: */

BS_ROM_ENTRY        = _bootstrapInit
BS_LD_LOW_FLAGS     = -Ttext 8
BS_ROM_SIZE     = 4000     # Size of first sector in flash SA0.
ROM_TEXT_ADRS       = 8
HEX_FLAGS           = -v -p 8 -a 8

bsexe: $(MY_PATH)/bootstrap.hex

$(MY_PATH)/bootstrapInit.o: $(MY_PATH)/bootstrapInit.s
    $(RM) $(MY_PATH)/boostrapInit.o
    $(CC) -c $(CFLAGS_AS) $(MY_PATH)/bootstrapInit.s -o $@

$(MY_PATH)/bootStrapStart.o: $(MY_PATH)/bootStrapStart.c
    $(RM) $(MY_PATH)/bootStrapStart.o
    $(CC) -c $(CFLAGS) $(MY_PATH)/bootStrapStart.c -o $@

$(MY_PATH)/comMem.o: $(MY_PATH)/comMem.c
    $(RM) $(MY_PATH)/comMem.o
    $(CC) -c $(CFLAGS) $(MY_PATH)/comMem.c -o $@

$(MY_PATH)/bootstrap: $(MY_PATH)/bootstrapInit.o $(MY_PATH)/bootStrapStart.o $(MY_PATH)/comMem.o
    $(RM) $(MY_PATH)/bootstrap
    $(LD) $(LDFLAGS) -e $(BS_ROM_ENTRY) $(BS_LD_LOW_FLAGS) -Map bootstrap.map \
        -o $@ $(MY_PATH)/bootstrapInit.o $(MY_PATH)/bootStrapStart.o $(MY_PATH)/comMem.o
    $(ROMSIZEPROG) -b $(BS_ROM_SIZE) $@
    $(LDOUT_CONV) $@
    @echo hi   // question here line 1

$(MY_PATH)/bootstrap.hex: $(MY_PATH)/bootstrap
    $(RM) $(MY_PATH)/bootstrap.hex
    $(BINHEX) $(HEX_FLAGS) $(SECT_SPEC)$(MY_PATH)/bootstrap$(TXT_OFFSET) \
        $(IMI_SPEC)$(IMI)$(IMI_OFFSET) > $@$(MAP_EXT)
    -@ $(MV_BIN)
          @echo hi   // question her line 2
</code>
When I am building using above make file, I am seeing output of "hi" of line 1 and I am not seeing output of line2. What might be problem. I am not an make file expert trying to understand and fix the customer issue .
Another question what "$(LDOUT_CONV)" and -@ $(MV_BIN) stands for and what actions are taken when make file sees these lines.
Thanks.
Comment: To know what `$(LDOUT_CONV)` is doing you would need to find what is setting the value of that variable in your build setup. A leading `-` tells make to ignore errors. A leading `@` tells make not to print the command before running it. The story with `$(MV_BIN)` is the same as with `$(LDOUT_CONV)`.
Comment: You are running `make` or `make bsexe` when you are testing this? How do you know which `hi` output you are seeing?
Answer: Do you have exactly one tab separate ahead of line 2 statement? If it is not, this statement can no be executed.
"$(LDOUT_CONV)" and $(MV_BIN) are defined variables other files, you can find them to check what does they do.

buiding bsp using make file in vxworks


Variable set with some value in the one cucumber step implementation is losing its value in the next step

Question: Variable set with some value in the one cucumber step implementation is losing its value in the next step
@Test
Feature: Test

@test
  Scenario: Test

   When user sets value of varibale x
    Then user retrives value of x

Step Implementation
import cucumber.api.java.en.When;

public class TestStepToBeRemoved {
    String x;

    @When("^user sets value of varibale x$")
    public void setValueOfx() {
        x = "Random Text";
    }

    @When("^user retrives value of x$")
    public void retriveValueOfX() {
        System.out.println("Value of X is : " + x);
    }
}

This was working fine before we merged another framework in our project which uses Guice libraries and injectors. But Now output
Value of X is : null

So, is there any in cucumber that we can set the cucumber to clear all the object when step execution is completed?
Please dont ask for making x static, it will resolve this issue but we need any other solution except making x static
Comment: see https://stackoverflow.com/questions/26422470/good-practice-to-pass-variables-between-cucumber-jvm-steps
Comment: Not very helpful but I got the solution now.
Answer: when you user cucumber-guice lib, cucumber somehow creates different object references for different step definitions, Hence the instance variable initialized in one step is not able to keep the same value in the next step.
To avoid this situation you can use @ScenarioScoped at the top in Step definition file and it will resolve the issue
import cucumber.api.java.en.When;

@ScenarioScoped
public class TestStepToBeRemoved {
    String x;

    @When("^user sets value of varibale x$")
    public void setValueOfx() {
        x = "Random Text";
    }

    @When("^user retrives value of x$")
    public void retriveValueOfX() {
        System.out.println("Value of X is : " + x);
    }
}


Bugzilla error after installation

Question: After the installation of bugzilla, I am unable to find the bugzilla login page, The following are the errors which is showing in the browser.
./data/params file does not exist. You probably need to run checksetup.pl. at Bugzilla/Config.pm line 337.
Compilation failed in require at /var/www/bigbugz/bugz/index.cgi line 34.
BEGIN failed--compilation aborted at /var/www/bigbugz/bugz/index.cgi line 34.
Please help me to solve the issue.
Answer: You probably need to run checksetup.pl.
Comment: Did it, It shows a list of packages that needs to be installed. But I have already installed those packages.
Answer: (It appears I don't have permission to post replies.)
If Bugzilla tells you you need to install the packages, then it can't find them. So you may have a Perl library path problem. The simple fix is to run the commands it tells you, in order to install your own local copies in the Bugzilla lib/ directory. If you definitely want to use the system versions, then you'll have to work out what's wrong with the path.
Note also that Bugzilla requires certain versions of packages - installing "CGI" is not enough, we need a very recent version. Check the output to see whether Bugzilla can't in fact find the packages, or whether it's finding them but the version is too old.
Gerv

Bugzilla error after installation


control radio button selected angularjs

Question: Radio "Default shipping Address" selected as default, when select Radio "new Shipping Address" it call a popup: "newAddress".
When popup "new Address" closed i want to change radio selected to "Default Shipping Address". (refresh radio selected to default) any help?

                <input type="radio" ng-model="form.receiverType" value="SELECT">
                Default shipping Address

                <input type="radio" ng-model="form.receiverType" value="INSERT">
                New shipping Address

click cancel close popup
<button data-dismiss="modal" aria-label="Close" class="btn btn-primary btn-lg ng-scope" type="button" data-translate="_Cancel" ng-click="cancelSaveNewAddss()" style=" margin-top: 20px;">Cancel</button>

event click radio button
// bind event when change receiverType
          $scope.$watch('form.receiverType', function(newVal, oldVal) {
          switch (newVal) {
            case 'SELECT':
                            $scope.selecteDefaultAddr();
                  break;
            case 'INSERT':
                  $('.modal-receiver-add').modal();
                  break;
            case 'MODIFY':
                // get reciever list
                  $scope.getReceiverList();
                  $('.modal-chondanhba').modal();
                  break;
            default:
                  break;
        }
    }, true);

Answer: You need to handle return part .result.then of the modal in your controller.
Example:
$uibModal.open({
  animation: $ctrl.animationsEnabled,
  ariaLabelledBy: 'modal-title',
  ariaDescribedBy: 'modal-body',
  templateUrl: 'myModalContent.html',
  controller: 'ModalInstanceCtrl',
  controllerAs: '$ctrl',
  size: size,
  appendTo: parentElem,
  resolve: {
    items: function () {
      return $ctrl.items;
    }
  }
}).result.then(function (response) {
  // You can get the response from modal.
  // If user clicked the cancel button, set the radio button back to the default.
}, function () {
  // Modal is dismissed with cancel, ESC button or click on the outside of modal.
  // Set the radio button back to the default.
});

More info at angularjs bootstrap modal

control radio button selected angularjs


How to prove $\sum_{k=1}^n (-1)^{(k+1)} k \binom nk=0$

Question: How to prove this identity?
$$\sum_{k=1}^n (-1)^{(k+1)} k \binom nk=0$$ This is George Casella statistical inference textbook exercise 1.27 (c). I have no idea to prove.
Comment: Use the binomial theorem to expand $(1 - x)^n$, differentiate both sides of the resulting equation w.r.t. $x$ and then put $x = 1$.
Comment: Something is not correct in the identity, because it is not true for $n=1$ .You have to say that $n\geq2$
Comment: Does this answer your question? [Binomial coefficient series $\sum\limits_{k=1}^n (-1)^{k+1} k \binom nk=0$](https://math.stackexchange.com/questions/399464/binomial-coefficient-series-sum-limits-k-1n-1k1-k-binom-nk-0)
Comment: Strong hint: Use the identity $\binom{n}{k} = \binom{n}{n-k}$.
Comment: @Yanko still have no idea
Comment: @Jonathen In doubt, always use induction for this kind of problem.
Comment: Ah seems like you've edit the question...
Comment: Alternatively use  the identity $(X+1)^n=\sum_{k=0}^{n}\binom{n}{k}X^k$.
Comment: @RobArthan Thank for your idea. I almost succeed. But I get $(-1)^{n-k}$, not the desired $(-1)^{k+1}$
Comment: Multiplied by $(-1)^{2k-n+1}$ both sides? It seems a weird step for me.
Comment: It's not really weird: it's just about the symmetries in the binomial theorem. If I'd written $(x - 1)^n$, I think you'd have got straight there.
Comment: @boojum You are right. Same. And that answers my question. I tried to search, but I didn't search the same question. Sad. otherwise I don't need to ask the quesrtion.
Answer: \begin{align}
\sum_{k=1}^n (-1)^{k+1} k \binom{n}{k}
&= n \sum_{k=1}^n (-1)^{k+1} \binom{n-1}{k-1} \\
&= n \sum_{k=0}^{n-1} (-1)^k \binom{n-1}{k} \\
&= n (1-1)^{n-1} \\
&= n \cdot 0^{n-1} \\
&= \begin{cases}
1 & \text{if $n=1$} \\
0 & \text{otherwise}
\end{cases}
\end{align}
Answer: We assume $n > 1$.  Start with the Binomial Theorem:
$$(1+x)^n = \sum_{k=0}^n \binom{n}{k} x^k$$
Differentiate:
$$n(1+x)^{n-1} = \sum_{k=1}^n k \binom{n}{k} x^{k-1}$$
Set $x=-1$ and observe that $(-1)^{k-1}=(-1)^{k+1}$:
$$\begin{align}
n(1-1)^{n-1} &= \sum_{k=1}^n k \binom{n}{k} (-1)^{k-1}\\
0 &= \sum_{k=1}^n k \binom{n}{k} (-1)^{k+1}
\end{align}$$
Answer: First we notice that the identity is not true for $n=1$. So we prove it for $n\geq\,2$. We use induction and the identity:
$\dbinom{n+1}{k}=\dbinom{n}{k}+\dbinom{n}{k-1}$.
Assume it is true for $n$. Now we write the $n+1$ statement as:
$\sum_{k=1}^{n+1}(-1)^{k+1}k\dbinom{n}{k}+\sum_{k=1}^{n+1}(-1)^{k+1}k\dbinom{n}{k-1}$.
Take the first term and notice that for $k=n+1$ the $n+1$ term is zero, by the definition of the factorial coefficient. Therefore we are left with
$\sum_{k=1}^{n}(-1)^{k+1}k\dbinom{n}{k}$ which is zero by the assumption of the induction.
Now we must prove that the second term is also zero. Set $k-1=m$ and get
$\sum_{m=0}^{n}(-1)^{m+2}(m+1)\dbinom{n}{m}$=$\sum_{m=0}^{n}(-1)^{m}(m+1)\dbinom{n}{m}$=$\sum_{m=0}^{n}(-1)^{m}m\dbinom{n}{m}+\sum_{m=0}^{n}(-1)^{m}\dbinom{n}{m}$ but $-\sum_{m=0}^{n}(-1)^{m+1}m\dbinom{n}{m}=0$
by the assumption of the induction (it makes no difference to add $m=0$).
So we are left with $\sum_{m=0}^{n}(-1)^{m}\dbinom{n}{m}$. But this is just (by Newton's binomial theorem) $[1+(-1)]^{n}=0$.
Thus the $n$-statement implies the $n+1$-statement and we are done!


Enigma combinations from another POV?

Question: I already know what is the number of Enigma combinations and how did they got to this number :
$${5!\over(5-3)!}\cdot26^3\cdot{26!\over(26-20)!\cdot2^{10}\cdot10!}=158,962,555,217,826,360,000$$
But let me please tell you how I see the right side part of the equation : (the $26!...$ part)
We should choose 10 pairs of letters from $a-z$.
Ok so we have these 10 pairs in braces:
$$(26*25)*(24*23)*(22*21)*(20*19)*(18*17)*(16*15)*(14*13)*(12*11)*(10*9)*(8*7) =  560127029342507827200000$$`
let's divide with the order of choosing those braces $$(..)*(..)*....(..)$$ which is $10!$
And then divide again with internal combination within each brace $(..)$ becuase $AB$ is like $BA$   (10 times) so it's $2^{10}  = 1024$
so it's
$$ \frac{560127029342507827200000}{(10! * 2^{10})}  = 150738274937250$$
OK.
But The thing which helped me understand this is the braces in $(26*25)*(24*23)...$
Question
But what if I remove(!) the parenthesis ? sure the result will remain the same but here  - my understanding is changing.
Let's see :
$26*25*24*23*22*21*20*19*18*17*16*15*14*13*12*11*10*9*8*7$ = combinations of arranging 20 letters = $560127029342507827200000$
let's divide by the order of choosing which is 20! and we get : 230230
ERR.... let's stop here - it's already an illogical too small value to continue.
What am I missing ( logically)?
How do I treat this problem without braces ?
Again - braces of pairs helped me understand that I should divide with $paris!$ and then divide again with internal order with each pair
But If i remove the braces - I get (in terms of words) a new story.
So now I'm having a new story of selecting 10 letters from 26 and now im dividing it by 10! (since I dont care about order) but where does 2^10 comes into play ?
Comment: You should divide by $10!$, not $20!$ as there are $20/2$ pairs.
Comment: @TobyMak If I go via the first formula - yes , but when I remove the parenthesis then the logic in my brain's changes. so now I 'm choosing 20 letters in order  - but I need 10 pairs - regardless the order. can you help me understand this ? Removing the braces changes everything  - for me
Answer: This last number is the number of Steckerbrett options. Here we choose 10 pairs out of the 26 letters to connect. This connection is symmetric so AC and CA are the same connection, e.g. Also, the order of the pairs is irrelevant, so for two pairs out of 6 letters the pairings $(AB)(CD)EF$ and $(CD)(AB)EF$ are the same.
So to generate all pairings we just take any order of the 26 letters, from left to right, and use the pairings given by letters 1 and 2, letters 3 and 4, up to letters 19 and 20, 10 pairs in all. The last $6 = 26- 6$ letters are unpaired.
It's clear we get all possible pairings in this way, but we generate equivalent pairings when we interchange the two letters in any pair, and there are 10 pairs so $2^{10}$ (because we can change the order in any one of them independently) many orders give rise to the same pairing. Also the order of the pairs does not matter for the setting either, so we can interchange them, so we get $10!$ shuffles of the $10$ pairs that are also equivalent. Finally, the order of the 6 unpaired letters at the end is also irrelevant. This makes for a factor $6!$ of overcounting. There are no other ways that an sequence of $26$ letters gives rise to the same settings as another such sequence: they must differ in order of pairs, order within a pair, or order of the unpaired letters.
So every sequence has $2^{10} \cdot 6! \cdot 10!$ many equivalents.
So the total number of classes (so different settings), is
$$\frac{26!}{2^{10} \cdot 6! \cdot 10!}$$
Note that the $\frac{26!}{6!}$ is just your term
$$(26 \cdot 25) \cdot (24 \cdot 23) \ldots \cdot (8 \cdot 7)$$
which is indeed the number of ordered sequences of $20$ letters from a $26$ letter alphabet. You can directly divide that number with the same factors $2^{10} \cdot 10!$ to account for the facts that the order within a pair can be interchanged (independently) and all $10$ pairs can be interchanged in $10!$ ways.
We shouldn't divide that number by $20!$ because the undoes all of the ordering, and we get just the number of $20$ letter sets from the alphabet, which indeed equals
$$\binom{26}{20}  = \frac{26!}{20! \cdot 6!}$$
But we need the order to make the pairs and compensate for their unorderedness later, as we did.
Comment: Please - I understand your answer . but there is something which bothers me. [This guy here](https://math.stackexchange.com/a/35959/24288) said that the number of combination to select 6 pairs out of 12 is like looking at the first one and count how many option he can pair to ( 11)  unpaired person, then looking at the second , same logic - he can connect to (9)  unpaired person - so it is 11*9*7*5*3*1. which is exactly like $\frac{12!}{2^{6}6!}$. But If I'm looking at my problem and apply this method I get : $25*23*...*7$ which is 527056905375 and it's NOT :https://i.stack.imgur.com/vSoIF.png
Comment: so where is my mistake ?
Comment: @can you please answer my comment ?
Comment: @RoyiNamir I added some explanation to the answer.
Comment: I mean the comment to your answer here. the one which starts with "please".
Comment: @RoyiNamir In that answer *all* letters are paired up. We don't have that here. First you have to pick the $20$ letters from $26$ that are going to be part of pairs, in $\binom{26}{20} = 230230$ ways. Then we apply the idea you mention. The first letter can be paired with $19$ letters, then we take the first of the remaining $18$, and note it can be matched with $17$ many pairs. etc. This gives $19 \cdot 17 \ldots \cdot 1 = \frac{20!}{10! 2^{10}}$ many options. And $\binom{26}{20}  \cdot \frac{20!}{10! 2^{10}}$ is exactly my answer. (The two terms $20!$ cancel out)

Enigma combinations from another POV?