menu and submenu in tree structure

Question: I need to create menu in below json format. Below is my table from which I'm fetching data:-
id  title       parent_id   url
5   Dashboard   0           /dashboard
6   Settings    0           /home
7   Menu        6           /menu
8   Menu Assign 6           /menu-assign
9   Test        5           /test
10  Demo        9           /demo

My expected format is given below.
public tail = [
 {
   name: 'Dashboard',
   link: '/dashboard',
   child: [
     {
       name: 'Test',
       link: '/test',
       child: [
         {
           name: 'Demo',
           link: '/demo',
         }
       ]
     },
   ]
 },
 {
   name: 'Settings',
   link: '/settings',
   child: [
     {
       name: 'Menu',
       link: '/menu',
       child: []
     },
     {
       name: 'Menu Assign',
       link: '/menu-assign',
       child: []
     }
   ]
 }
];

I have tried the below code
public function menuTree($parent=0,$level=0){
        Global $menuArr;
        $menus = Menu::where('parent_id','=',$parent)->get();
        foreach($menus as $allMenu){
            $menuArr[$allMenu->id][$level] = str_repeat("-", $level).$allMenu->title;
            $level++;
            $this->menuTree($allMenu->id,$level);
            $level--;
        }
        return $menuArr;
    }

Answer: I haven't had a chance to test this thoroughly. However, you can use the collection instance to loop through the menu items. This will have to be achieved within a few steps.

Firstly, we will need to create a $level public variable, which can be used throughout the controller class. We set this as the beginning of the menuTree() method.
$this->level = $this->level ?: $level will check to see if the $this->level variable has been set and is greater than 0. If so, we shall assume that is iterating through the tree, else just set to 0. This ternary expression is the same as $this->level = $this->level ? $this->level : $level.
Moving on, we get all menus and use the map() collection helper to alter the results we return. This is where we return from a new function called menuItem().
In menuItem() we get the menu item's name and link and add it to a $data array.
We then check if $this->level is true (if greater than 0). This is done to see if we need to iterate for child menu items. We also check if any menu items exist in which are children of the current menu item. If both true, we cycle through the process again and reduce the level count by 1.

To conclude, if $this->level is greater than 0, we return as an array, else we return as a json array. This is the difference between it completing the tree, and if it is still iterating through a menu level.
Here is the full code.
public $level;

public function menuTree($parent = 0, $level = 0)
{
    $this->level = $this->level ?: $level;

    $menus = Menu::where('parent_id', $parent)
        ->get()
        ->map(function ($menu, $key) {
            return $this->menuItem($menu);
        });

    return $this->level ? $menus->toArray() : $menus->toJson();
}

public function menuItem($item)
{
    $data = [
        'name' => str_slug($item->title),
        'link' => $item->url,
    ];

    if ($this->level && Menu::where('parent_id', $item->id)->count()) {
        $data['child'] = $this->menuTree($item->id);
        $this->level--;
    }

    return $data;
}

Note: In the event where the parent_id is set to null instead of 0, you will need to start the query up differently:
...

$menus = Menu::query();

if ($parent) {
    $menus = where('parent_id', $parent);
}

$menus = $menus->get()
    ->map(function ($menu, $key) {
        return $this->menuItem($menu);
    });

...

query() is used to begin a eloquent builder. The condition is set to check if the parent_id is not null|false|0 and apply the query if true.

menu and submenu in tree structure


A couple of questions about a system of equations with modulus

Question:
Solve the system of equations below:
$$
\left\{
\begin{array}{c}
x \equiv 3 \pmod {11} \\
x \equiv 4 \pmod {17} \\
\end{array}
\right.
$$

$11u + 17v = 1$
$u = -3$ and $v = 2$
$t = 4 \times 11 \times -3 + 3 \times 17 \times 2 = -30.$
The answer is supposed to be $x = -30 \pmod {187}$. Where does the $\pmod {187}$ part come from?
$ax + by \neq 1$ doesn't imply $\gcd(a, b),$ correct? But $ax + by = 1 \rightarrow \gcd(a, b),$ right? So, when solving the system above we could use the Euclidean Algorithm to find $u, v.$ Is that correct?
Comment: It comes from $187=(11)(17)$.
Answer: I don't know if I understand your whole question, especially the last two paragraphs, correctly. But I see that you are using the constructive method of Chinese remainder theorem.
The $187$ is of course $11\times 17$. It is easy to check that, if $x$ is a solution to the system of modular equations, then $(x+11\times 17n)$ is also a solution for integers $n$.
And let there are two solutions $x,y$ to the system of equations. Consider $x-y$. Then
$$\begin{align*}
x-y&\equiv 3-3 = 0 \pmod{11}\\
x-y&\equiv 4-4 = 0 \pmod{17}\\
\end{align*}$$
and $x-y$ is a common multiplier of $11$ and $17$. Since $11$ and $17$ are coprime, the smallest positive difference of any two solutions is $187$.
Comment: @ peterwhy. Thank you, I see. I just looked at the Chinese remainder theorem and it says that "if $t$ is one solution of the system, then an integer $z$ is also a solution iff $z \equiv t \pmod {m_1m_2m_3 \ldots m_r}$". So, how do we know a system has more than one solution from the get-go so that we can use the part I quoted above?
Comment: By similar reasoning as in my answer, if there is one solution, then there are infinite solutions, because any solution plus $M = m_1m_2m_3\cdots m_r$ is another solution. And it is proven (at least by construction) that there must be a solution for pairwise coprime $m_1, \ldots, m_r$.
Comment: Can we use the Euclidean Algorithm to find the values of $u, v$ in the OP?
Comment: Yes sure. All you want are two inverses $u = 11^{-1}\pmod {17}$ and $v = 17^{-1}\pmod{11}$, and extended Euclidean algorithm is a method.
Answer: Let one of the roots of this equation be $x_0$ and let another root of this equation be $x_1$.
$x_0 = 3($mod $11) \Rightarrow x_0=11p+3$ for $p \in Z $
and $x_1 = 3($mod $11) \Rightarrow x_1=11q+3$.
Thus $x_1-x_0 = 11(q-p)$ - a multiple of $11$.
Also $x_0 = 4($mod $17) \Rightarrow x_0=17r+4$
and $x_1 = 4($mod $17) \Rightarrow x_1=17s+4$.
Thus $x_1-x_0 = 17(s-r)$ - a multiple of $17$.
Combined $x_1-x_0$ must be a multiple of $17 \times 11=187$.
$x_1-x_0 = 187k \Rightarrow x_1=187k+x_0 \Rightarrow x_1 = x_0($mod $187)$


why Selenium python write only first row of csv where my scraper collecting multiple row data?

Question: I am using selenium to collect data from websites. Where my scraper collected multiple row data but my csv file write only the first row. here is my code:
for page in range(1,34):
    url = ('my website url')

    driver.get(url)
    company_name = driver.find_element_by_css_selector('.partner-name--text')
    if company_name:
           company_name = company_name.text
    else:
            company_name = "Not Found"

   header = ['company_name']
   data = [company_name]
   with open('sap.csv', 'w', encoding='UTF8') as f:
            writer = csv.writer(f)

            # write the header
            writer.writerow(header)

            # write the data
            writer.writerow(data)
   driver.quit()

I am collecting multiple company names but in my csv file only seeing the first company name.
Answer: The problem is that you are re-writing the file many times instead of appending it:
data = []
for page in range(1,34):
    url = ('my website url')

    driver.get(url)
    company_name = driver.find_element_by_css_selector('.partner-name--text')
    if company_name:
           company_name = company_name.text
    else:
            company_name = "Not Found"

   data.append(company_name)
   driver.quit()

with open('sap.csv', 'w', encoding='UTF8') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(['company_name'])

    # write the data
    writer.writerows(data)


Remapping the Sum of two Normal Random variables?

Question: I have a problem where I have sum of two random variables
1). Each distributed independently normally with different means ($\mu_1$, $\mu_2$) and sds ($\sigma_1$, $\sigma_2$). $Z=R_1+R_2$
2). Each distributed independently log-normally with different means ($u_1$, $u_2$) and sds ($s_1$, $s_2$). $LZ=LR_1+LR_2$
In the first case, the answer lies in (-$\infty$, $\infty$) and (0, $\infty$) in the second case.
I need to transform these random variables i.e. $Z$ and $LZ$ to make them probabilities and lie in [0, 1], as I want to simulate a Bernoulli Trial with that probability.
I see that as a case of remapping probability densities.
For case 1, I think I could use the logistic transform on $Z$ to make it a probability which lies in [0, 1]. I hope that makes sense?
Also, I am clueless regarding how to do this mapping for the case of lognormal distribution?
I would really appreciate any feedback on this!
Answer: Since the sum of two independent normals is normal, you wouldn't get a uniform (as in your original title) by applying a logistic transformation on the sum.

If the means and variances are known (as your question implies), you could get a uniform result by using the normal cdf of the sum (mean is the sum of means, variance is the sum of variances).
If you don't actually want a uniform (as your change in title now indicates), you could use the logistic transform as you suggest, but any cdf of $(-\infty,\infty)$ would do.

In the second case, the sum of two independent lognormals doesn't have a nice closed form.

If you're just looking to get it into the range $(0,1)$, any cdf on $(0,\infty)$ can do that (lognormal, gamma, Weibull, F, log-logistic, beta prime, ...). However you could just do $Y/(Y+1)$ -- my $Y$ is your $LZ$ -- to the same effect. I guess that would just be a standard log-logistic cdf transform though. I think this would be equivalent to taking logs and applying the same logistic you would for the normal case.
If you want a rough approximation to uniform, take the sum to be lognormal with mean the sum of the means (careful, don't add the log-scale $\mu$ parameters), and variance the sum of the variances (with the corresponding not of caution). This will often work fairly well:

(Code is given below)
By comparison, the problem with just getting the range right is that in practice almost all of the values are likely to end up in a very narrow part of the range:

That's the same sum, transformed by a standard log-logistic cdf. It's certainly in $(0,1)$, but in a sample of 10000 values, all of them were between 0.97 and 0.995. If that's what you want, then you should be okay (keeping in mind that the next one might be piled up the other end - or end up U-shaped, or bunched in the middle). If it's not what you need, then I suggest you at least do some approximate quantile matching or moment matching to get a better spread of values.

If you really do want a uniform result (up to reasonable calculation accuracy), you could perhaps make use of numerical convolution.

--
#R code to calculate the lognormal approximation to the sum and transform:

X1 <- rlnorm(10000, 3, .4)
X2 <- rlnorm(10000, 4, .3)
hist(X1, n=100)
hist(X2, n=100)

m1 <- exp(3+.4^2/2)
m2 <- exp(4+.3^2/2)
v1 <- m1^2*(exp(.4^2)-1)
v2 <- m2^2*(exp(.3^2)-1)

Y <- X1+X2
v <- v1+v2
m <- m1+m2
s2 <- log(v/m^2+1)

hist(X1+X2, n=100)
uish <- plnorm(Y,log(m-s2/2),sqrt(s2))
hist(uish, n=100)

Comment: Thanks! I changed the title. I just need to be able to simulate bernoulli draws with that probability. It need not be uniform on [0,1]. I guess, then, the logistic should be fine as its simple such cdf? Can you mention any [0, $\infty$] cdfs that I could use for log-normal?
Comment: I have updated the answer to list several distributions on $(0,\infty)$. As for whether the logistic would be suitable for your purpose, it's not clear to me what you're trying to achieve overall (it doesn't seem to do anything that I'd want to do that way, but maybe it's sensible and I just don't understand it yet), so I can hardly judge its suitability. Similar comments would apply to the distributions on the positive half-line -- I have no way to judge their suitability to your purpose until I really understand what it's supposed to achieve in the long run.
Comment: I'd have thought something like "Remapping variables to the unit interval" would be a more clear edit for the title, but I'll leave that to you; what you have now is an improvement.
Answer: If it's just a matter of doing the simulation, you can, in the normal case, do:
mu1 <- 0
mu2 <- 1

sd1 <- 1
sd2 <- 3

N <- 10^4

z <- rnorm(N, mean = mu1, sd = sd1) + rnorm(N, mean = mu2, sd = sd2)

x <- rbinom(N, size = 1, prob = exp(z)/(exp(z)+1))

For the lognormal:
u <- exp(z)

y <- rbinom(N, size = 1, prob = u/(u+1))

By the way, the title of the question is misleading. You're just changing the range of the random variables, you're not transforming them in a uniform random variable.
Comment: There are infinitely many ways of doing the transformations.
Comment: Sure! But there's no ground truth i.e. I can not verify if its the correct thing to do. For instance, there might be other ways of doing this transformation etc.
Answer: Let $X$ have the continuous cdf $F_X(x)$ then define the random variable $Y=F_X(x)$.  Then $Y$ is uniformly distributed on $(0,1)$. This important property is called the Probability Integral Transform.
In your case, you may transform $Z$ and $LZ$ to uniformly distributed variables by using their respective cdf's.  The first cdf is easy (Z is normally distributed), the last is more challenging (the sum of two log normals is not log normal).
Proof:
$$P(Y\leq y) = P(F_X(X) \leq y)$$
$$=P(F_X^{-1}[F_X(X)] \leq F_X^{-1}(y))$$
$$=P(X \leq F_X^{-1}(y))$$
$$=F_X(F_X^{-1}(y))=y$$
At the end points we have $P(Y \leq y)=1$ for $y = 1$ and $P(Y \leq y)=0$ for $y = 0$ verifying that $Y$ has a uniform distribution.
Comment: The definition I am giving you comes out of the text "Statistical Inference" by G. Cassala and L. Berger which was my introductory graduate level text.  It is similar to the definition given on Wikipedia http://en.wikipedia.org/wiki/Probability_integral_transform
Comment: Blade Runner - conventionally the probability integral transform is the term for applying F_X to X ... and $F_X(X)$ is uniform. See [here](http://en.wikipedia.org/wiki/Probability_integral_transform#Examples). You're thinking of [something else](http://en.wikipedia.org/wiki/Inverse_transform_sampling). Which is to say, Zachary is using the term in the sense that would be most widely understood.
Comment: The probability integral transform works in the opposite direction i.e. it transforms a uniform r.v to normal etc.
Comment: @ZacharyBlumenfeld: you mean G. Casella and R. Berger as the authors of the book.


What does mean some eigenvalues of the Hessian are positive? How to fix it?

Question: I prepared a research design with the discrete choice method. I have 2 labeled alternatives, 5 attributes for an alternative, and 6 attributes for an alternative. I want to analyze my data with multinomial logit in the R apollo package R. However, I have an error. But I don't know what this error means and how I should go about to fix it. I would be very happy if you could give your opinion on this.
This is the error:
<code> "Calculating log-likelihood at equal shares (LL(0)) for applicable models...
Calculating log-likelihood at observed shares from estimation data (LL(c)) for applicable models...
Calculating LL of each model component...
Calculating other model fit measures
Computing covariance matrix using analytical gradient.
 0%....25%....50%....75%...100%
WARNING: Some eigenvalues of the Hessian are positive, indicating convergence to a saddle point!
Computing score matrix...
Warning messages:
1: In sqrt(diag(varcov)) : NaNs produced
2: In sqrt(diag(robvarcov)) : NaNs produced
</code>
This is the R script:
<code>install.packages("apollo")
### Clear memory
rm(list = ls())

### Load Apollo library
library(apollo)
library(tidyverse)

### Initialise code
apollo_initialise()

### Set core controls
apollo_control = list(
  modelName       = "MNL_Deneme",
  modelDescr      = "Simple MNL model on mode choice SP data",
  indivID         = "id"
)
library(readxl)
database <- read_excel("ayakkabi.xlsx")
View(database)
attach(database)
apollo_beta=c (asc_ev = 0,
               asc_nokta= 0,
               b_ucret_ev= 0,
               b_m1ev= 0,
               b_m2ev= 0,
               b_m3ev= 0,
               b_h1ev= 0,
               b_h2ev= 0,
               b_h3ev= 0,
               b_h4ev= 0,
               b_s1ev= 0,
               b_s2ev= 0,
               b_s3ev= 0,
               b_s4ev= 0,
               b_b1ev= 0,
               b_b2ev= 0,
               b_ucret_n= 0,
               b_m1n= 0,
               b_m2n= 0,
               b_h1n= 0,
               b_h2n= 0,
               b_h3n= 0,
               b_h4n= 0,
               b_a1n= 0,
               b_a2n= 0,
               b_a3n= 0,
               b_a4n= 0,
               b_b1n= 0,
               b_b2n= 0,
               b_u1n= 0,
               b_u2n= 0,
               b_u3n= 0,
               b_u4n= 0
)
apollo_fixed = c("asc_ev","b_m1ev","b_h1ev", "b_s1ev","b_b1ev","b_m1n", "b_h1n","b_a1n","b_b1n","b_u1n")

apollo_inputs = apollo_validateInputs()

apollo_probabilities=function(apollo_beta, apollo_inputs, functionality="estimate"){
  ### Attach inputs and detach after function exit
  apollo_attach(apollo_beta, apollo_inputs)
  on.exit(apollo_detach(apollo_beta, apollo_inputs))
  ### Create list of probabilities P
  P = list()
  ### List of utilities: these must use the same names as in mnl_settings, order is irrelevant
  V = list()
  V[['ev']] = asc_ev + b_ucret_ev*ucret_ev + b_m1ev*(metot_ev==0) + b_m2ev*(metot_ev==1) +b_m3ev*(metot_ev==2) +
    b_h1ev*(hiz_ev==0) + b_h2ev*(hiz_ev==1) + b_h3ev*(hiz_ev==2) + b_h4ev*(hiz_ev==3) +
    b_s1ev*(saat_ev==0) + b_s2ev*(saat_ev==1) + b_s3ev*(saat_ev==2) + b_s4ev*(saat_ev==3) +
    b_b1ev*(bilgi_ev==0) + b_b2ev*(bilgi_ev==1)

  V[['nokta']] = asc_nokta + b_ucret_n*(ucret_nokta) + b_m1n*(metot_nokta==0) + b_m2n*(metot_nokta==1) +
    b_h1n*(hiz_nokta==0) + b_h2n*(hiz_nokta==1) + b_h3n*(hiz_nokta==2) + b_h4n*(hiz_nokta==3) +
    b_a1n*(acik_nokta==0) + b_a2n*(acik_nokta==1) + b_a3n*(acik_nokta==2) + b_a4n*(acik_nokta==3) +
    b_b1n*(bilgi_nokta==0) +b_b2n*(bilgi_nokta==1) +
    b_u1n*(uzaklik_nokta==0) + b_u2n*(uzaklik_nokta==1) + b_u3n*(uzaklik_nokta==2) + b_u4n*(uzaklik_nokta==3)
  ### Define settings for MNL model component
  mnl_settings = list(
    alternatives = c(ev=1, nokta=2),
    avail = 1,
    choiceVar = secim,
    V = V)
  ### Compute probabilities using MNL model
  P[["model"]] = apollo_mnl(mnl_settings, functionality)

  ### Take product across observation for same individual
  P = apollo_panelProd(P, apollo_inputs, functionality)

  ### Prepare and return outputs of function
  P = apollo_prepareProb(P, apollo_inputs, functionality)
  return(P)
}

# ################################################################# #
#### MODEL ESTIMATION                                            ####
# ################################################################# #

model = apollo_estimate(apollo_beta, apollo_fixed, apollo_probabilities, apollo_inputs)

# ################################################################# #
#### MODEL OUTPUTS                                               ####
# ################################################################# #
apollo_modelOutput(model,modelOutput_settings=list(printPVal=TRUE))
# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO SCREEN)                               ----
# ----------------------------------------------------------------- #

apollo_modelOutput(model)

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO FILE, using model name)               ----
# ----------------------------------------------------------------- #

apollo_saveOutput(model)
</code>
Comment: Please format the scripts properly.
Comment: The error message is clear: "indicating convergence to a saddle point!"  The algorithm has not succeeded.  You need to find ways to steer it towards the global optimum or at least a local minimum.  If this function allows you to specify starting values, then your task is to find a reasonable set of such values and provide them as inputs.
Answer: In the applications I have experience with, this has to do with multicollinearity and normalization. If, for example, your model has consumers selecting products offered by different companies and includes an intercept for each company and you do not hold one fixed at zero, then I believe you'd encounter this problem. Also, if your model includes a product characteristic that is perfectly correlated with the company (i.e., only one company offers a product with that characteristic), I believe you would also encounter the problem them. In each of these cases, one variable is a linear combination of others in the model. In the former case, the indicator for company 1 is one less the sum of the indicator for the remaining companies. In the latter case, the indicator for the product characteristic is equal to the indicator for the company that offers the product. I think that's what could be causing the convergence to a saddle point.


How to manage multiple versions of a glyph?

Question: I am learning how to design a font but I don't understand a thing: if I want to create a glyph but in both regular and bold versions, do I have to create it once and then copy/paste and I manually increase it tickness? More generally, how to manage multiple versions (bold, regular, ...) of the font?
Answer: In the very general sense, a font may be desired in several styles, such as italics, small-caps, and variants of weight. In computer fonts, when these are combined into a single font, they are termed as Multiple Master. Fonts are not always multiple master, or may contain any number of masters for different styles or combinations thereof. The requirements and limitations vary alot depending on the file format the font is being designed for.  For someone just beginning font design it may be simpler to find a font creation package that clearly simplifies the creation of different styles. For moving toward serious design, it's worth reading plenty about different font file formats, then shopping around for a software package that supports it.


Data skipped while writing Spark Streaming output to HDFS

Question: I'm running a Spark Streaming application for every 10 seconds, its job is to consume data from kafka, transform it and store it into HDFS based on the key. i.e, a file per unique key. I'm using the Hadoop's saveAsHadoopFile() API to store the output, I see that a file gets generated for every unique key, but the issue is that only one row gets stored for each of the unique key though the DStream has more rows for the same key.
For example, consider the following DStream which has one unique key,
  key                  value
 =====   =====================================
 Key_1   183.33 70.0 0.12 1.0 1.0 1.0 11.0 4.0
 Key_1   184.33 70.0 1.12 1.0 1.0 1.0 11.0 4.0
 Key_1   181.33 70.0 2.12 1.0 1.0 1.0 11.0 4.0
 Key_1   185.33 70.0 1.12 1.0 1.0 1.0 11.0 4.0
 Key_1   185.33 70.0 0.12 1.0 1.0 1.0 11.0 4.0

I see only one row (instead of 5 rows) gets stored in the HDFS file,
185.33 70.0 0.12 1.0 1.0 1.0 11.0 4.0

The following code is used to store the output into HDFS,
dStream.foreachRDD(new Function<JavaPairRDD<String, String>, Void> () {
    @Override
    public Void call(JavaPairRDD<String, String> pairRDD) throws Exception {
        long timestamp = System.currentTimeMillis();
        int randomInt = random.nextInt();
        pairRDD.saveAsHadoopFile("hdfs://localhost:9000/application-" + timestamp +"-"+ randomInt, String.class, String.class, RDDMultipleTextOutputFormat.class);
    }
});

where the implementation of RDDMultipleTextOutputFormat is as follows,
public class RDDMultipleTextOutputFormat<K,V> extends    MultipleTextOutputFormat<K,V> {

    public K generateActualKey(K key, V value) {
        return null;
    }

    public String generateFileNameForKeyValue(K key, V value, String name) {
        return key.toString();
    }
}

Please let me know if I'm missing anything? Thanks for your help.
Answer: Because the key is same, the value is getting replaced every time and hence you are getting the last value supplied to hadoop.
Comment: How can i make it not to overwrite? ... Actually i'm storing the pairRDD, that must store the entire RDD and should not overwrite.
Comment: Instead of using the same key, you can use rdd.zipWithUniqueId() to obtain different keys and then dump it to our hdfs.
Just try it.
Comment: my requirement is to store all the lines of a key with a single file. Will rdd.zipWithUniqueId() do the same?
Comment: rdd.zipWithUniqueId() is used to generate unique keys but do you already have your keys ?
Comment: Yes, i have my keys already and there will be multiple unique keys, and each key might have 5 to 10 rows in each batch interval. So i need to store them in the corresponding key file.
Comment: can you please try this, I'm not sure if it could work on hdfs but lets give it a try.
    val keys = pairRdd.map(_._1).distinct().toArray().toSeq

    keys.foreach { key => pairRdd.filter(_._1.equals(key)).map(_._2).saveAsHadoopFile(key) }
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/92020/discussion-between-kshitij-kulshrestha-and-sathish).
Comment: please  upvote if you have found it some what helpful.


Multiple Variables Calc Bison

Question: I've been working on a calculator in Flex and Bison. I can assign variables individually such as
m = 5
m * 5
25

but now I want to be able to assign multiple variables such as m = n = 5
Here's what I have for my bison file right now. How would I modify it to the above?
%{
 #include <stdio.h>
 void yyerror(char *);
 int yylex(void);
 int sym[26];
%}
%token INTEGER VARIABLE
%left '+' '-' '*'
%%
program:
 program statement '\n'
 | /* NULL */
 ;
statement:
 expression { printf("%d\n", $1); }
 | VARIABLE '=' expression { sym[$1] = $3; }
 ;
expression:
 INTEGER
 | VARIABLE { $$ = sym[$1]; }
 | '-' expression { $$ = -$2; }
 | expression '+' expression { $$ = $1 + $3; }
 | expression '-' expression { $$ = $1 - $3; }
 | expression '*' expression { $$ = $1 * $3; }
 | '(' expression ')' { $$ = $2; }
 ;
%%
void yyerror(char *s) {
 fprintf(stderr, "%s\n", s);
}
int main(void) {
 yyparse();
}

Answer: Three quick observations:
1) You're setting +, - and * to have the same precedence, which means that
 1 + 2 * 3

will be parsed as though it were
 (1 + 2) * 3   (9)

whereas the normal interpretation would be
 1 + (2 * 3)   (7)

2) Really, assignment can be considered just another case of an expression, where the = operator has lower precedence than any other operator, and associates to the right.
3) Finally, you should set a precedence for unary minus. See the bison manual for more explanation.
Making these changes results in the following simple grammar:
%token INTEGER VARIABLE
%right '='
%left '+' '-'
%left '*'
%right UNOP
%%

program:
 program statement '\n'
 | /* NULL */
 ;
statement:
 expression { printf("%d\n", $1); }
 | /* EMPTY; added to allow empty lines */
 ;
expression:
 INTEGER
 | VARIABLE                  { $$ = sym[$1]; }
 | VARIABLE '=' expression   { $$ = sym[$1] = $3; }  /* CHANGED; return result */
 | '-' expression %prec UNOP { $$ = -$2; }           /* CHANGED; add precedence */
 | expression '+' expression { $$ = $1 + $3; }
 | expression '-' expression { $$ = $1 - $3; }
 | expression '*' expression { $$ = $1 * $3; }
 | '(' expression ')'        { $$ = $2; }
 ;

Note that expression is used in both left- and right-recursive contexts in the above rules. That's normal. Notwithstanding the rather alarmist statement in the bison manual about right-recursion, it's actually totally reasonable to write right-recursive rules when that's what the semantics of the language indicates. (If there is no semantic difference, prefer left-recursion to avoid using the parser stack, but using the parser stack is rarely an issue.)
As Chris Dodd points out in a comment, the above simplified grammar alters the semantics of the program because it will print out the value of an assignment expression; in the original, assignment statement were mute. This is easy to fix, but slightly tedious. I didn't do it in the above answer because it distracts from the structure of the solution.
The simplest fix is to duplicate the assignment production, both as part of statement and of expression; this results in a reduce/reduce conflict which bison will warn you about, but since bison prefers the reduction earlier in the file, it will produce the correct result. Many people (including me) would consider relying on that rule in production code to be ugly and hard to maintain.
Another option is to separate expressions into "quiet" and "loud" expressions, which have different unit productions for statement. That would look somewhat more like the original grammar, with precedences fixed.
Yet another option would be to build an Abstract Syntax Tree (AST) rather than immediately executing the program. When the AST is executed, you can easily suppress printing the result if the top node is an assignment. (Unlike the quiet/loud solution, a naive implementation of the AST would suppress printing for both a simple assignment, a = 3, and an obvious expression assignment (a = 3), but you can work around that, too.)
Comment: One minor note -- this does change the behavior of the program causing it to print the value assigned after an assignment statement.
Comment: @chrisDodd: yes. I was going to mention that but in the end I had to go do something else. I'll add a note.
Answer: This is very easy to do with right-recursion, which unfortunately isn't very efficient in bison:
statement:
  expression {}
  | assignment {}
  ;
assigment:
  VARIABLE '=' assignment {}
  | VARIABLE '=' expression {}
  ;

Alternatively, a left-recursion solution:
statement:
  expression {}
  | assignment {}
  ;
assigment:
  recursive_assignment '=' expression {}
  ;
recursive_assignment:
  recursive_assignment '=' VARIABLE {}
  | VARIABLE  {}
  ;

Here is some useful information on recursion in bison.

Multiple Variables Calc Bison


Prove: $f: \mathbb{R} \rightarrow \mathbb{R}$ st for every $x \in \mathbb{R}$ there exists $n$ st $f^{(n)}(x) = 0$, f is a polynomial.

Question: If $f: \mathbb{R} \rightarrow \mathbb{R}$ is a smooth function such that for every $x \in \mathbb{R}$ there exists $n$ such that $f^{(n)}(x) = 0$, then f is a polynomial.
I'm kind of lost on this one. I know that I have to use Baire's category theorem somewhere here, but I'm not sure exactly how.
Comment: See [this](http://mathoverflow.net/questions/34059/if-f-is-infinitely-differentiable-then-f-coincides-with-a-polynomial).
Answer: This problem can indeed be solved using the Baire Category Theorem.
A nice discussion of variants of the problem, along with an outline of a proof of your version, can be found in the answers to this post at MathOverflow.


boot issues after converting running linux to vm manually

Question: I did a file copy of a running debian8 installation to a image. Following is the proceedure.

create a vdisk image - raw / vdi.
mount it locally.
do a file wise copy of a running linux distro:

rsync -aAXv --delete --exclude={"/dev/","/proc/","/sys/","/tmp/","/run/","/mnt/","/media/","/lost+found","/home/"} /* "$TMPDIR"

install extlinux bootloader and related /boot/extlinux.conf, update /etc/fstab, umount and boot.

I am able to boot using qemu. Able to login to console mode.
ISSUES:

It fails at trying to mount swap partitions, but no reference is provided in /etc/fstab.
It fails to load kernel modules.
I see message starting lightdm, but next VT is displayed to login.
I haven't recreated initram-fs for target, could this cause the problem?

Please help.
-- regards, JB
Comment: Next time just use `virt-p2v`.
Answer: Have been able to resolve some of the issues, resulting in making a bootable vm image from a running system.
Issue:

No effect.
No effect.
This is actually 1-issue and 1-mistake, I had a custom xorg.conf with a specific driver, removing the xorg.conf makes booting qemu into graphical mode. The other is due to plain slowness of qemu, you just need to wait for a long time for lightdm to startup.
No effect.

I've summarized the entire process in a script for convinience:
#!/bin/bash
# create bootable image from running linux distro

IMG_format="raw"
IMG_name="debian8"
IMG_size="13G"

LNX_image="vmlinuz-4.4.3"
LNX_initrd="initrd.img-4.4.3"
LNX_rootdev="/dev/sda"

TMPDIR="/mnt/vmd/"
WRKDIR="/media/domnic/tmp1"

create_img(){
  IMG="$WRKDIR/$IMG_name.$IMG_format"
  echo "image => $IMG"

  if [ -a "$IMG"]; then
    echo "vm [$IMG] already exists... skipped!"
  else
    if [ "vdi" == "$IMG_format" ]; then
      #- create .vdi
      VBoxManage createhd --filename $IMG --size $(( IMG_size * 1024 ))
    else
      #- or create image on .raw disk
      fallocate -l $IMG_size $IMG
      mkfs.ext4 -F $IMG
    fi
  fi
}

mount_img(){
  echo "mount => $TMPDIR"
  IMG="$WRKDIR/$IMG_name.$IMG_format"
  if [ ! -d "$TMPDIR" ]; then
    mkdir -p $TMPDIR
  fi

  if [ "vdi" == "$IMG_format" ]; then
    #- mount .vdi
    vdfuse -a -f $IMG /mnt/vdi
    mount -o loop /mnt/vdi/1 $TMPDIR
  else
    #- mount image to tmpdir
    mount $IMG $TMPDIR
  fi
}

clone_img(){
  echo "clone => $TMPDIR"
  #- copy files
  rsync -aAX --delete --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found","/home/*"} /* "$TMPDIR"

  #- install bootloader
  extlinux --install $TMPDIR/boot

  #- update bootloader
  #-- qemu default: root=/dev/sda
  cat > $TMPDIR/boot/syslinux/extlinux.conf <<- EOM
DEFAULT $IMG_name_$LNX_image
LABEL   $IMG_name_$LNX_image
SAY     Booting $IMG_name - $LNX_image
LINUX   /boot/$LNX_image
INITRD  /boot/$LNX_initrd
APPEND  root=$LNX_rootdev rw
EOM

  #-- remove invalid entries from $TMPDIR/etc/fstab
  echo "/dev/sda   /   ext4   defaults   0   1" > $TMPDIR/etc/fstab

  #- unmount image and boot
  umount $TMPDIR
  if [ "vdi" == "$IMG_format" ]; then
    umount /mnt/vdi
  fi
}

start_vm(){
  IMG="$WRKDIR/$IMG_name.$IMG_format"
  echo "vm => $IMG"

  qemu-system-i386 \
    -display sdl \
    -soundhw ac97 \
    -vga cirrus \
    $IMG
}

case $1 in
  create_img)
    create_img
    ;;
  mount_img)
    mount_img
    ;;
  clone_img)
    clone_img
    ;;
  start_vm)
    start_vm
    ;;
esac


Why is Java labelling this class as abstract

Question: Please see code here. Java is labeling this class as abstract, and I can't instantiate it... Any ideas why??
public class Marker {
    Location l;
    int xcoord;
    int ycoord;
    int value;

    Marker(int x, int y, int val){
        xcoord=x;
        ycoord=y;
        value = val;
        l = new Location(x,y);
    }
}

re: code to instantiate:
...I'm reading through a large file of data that's separated by tabs. After ever 16th tab there is a marker, usually of value 0. If it's not 0, I want to save the location and value as a Marker... The values for x, y, tabcounter, and currchar are being updated as I iterate through the file.
if (tabcounter == 16) { //now we are at a marker
    if (currchar != 48) { //if the marker isn't 0

        Marker m = new Marker(x,y,(int)(char)currchar);
        markers.add(m); //markers is a list of type Marker
    }
    tabcounter = 0;
    x=0;
    y=y+1;
}

Comment: What makes you say 'Java is labelling it as abstract'?
Comment: @Matt show your code where you try to instantiate the class
Comment: Do you have a name clash with an existing class then?
Comment: when i refactor the name to 'maker' with lowercase m, there's no problem...
Comment: when i try to instantiate -

Marker x = new Marker(1,2,3);

can't compile, error in netbeans says that the class 'Marker' is abstract
Comment: It's not abstract.  It just has no public constructor.
Answer: Check your buildpath to see if there are any other classes named Marker. It could be in a jar file somewhere. If you are using eclipse, use the "link with Editor" option to find which Marker it is looking for by highlighting the class name.


Is there any specific difference between multi site and multi domain?

Question: I didn't see any specific difference between multi site and multi domain. If there any specific reason to differentiate them?
Answer: Multi site is the ability to have multiple sites running on the same code base.  This can be either different domains or different base URLs.  E.g. could be http:/example.com, http:/example.org, http:/example.com/new_site.
This is done in Drupal via different subdirectories in the sites directory. E.g.
sites/default (example.com)
sites/example.org (example.org)
sites/new_site (example.com/new_site)
Multi domain is partially a subset of multi site as shown above.  But it can also indicate the same site being accessed via multiple domain names.  This is common in multilingual sites.  E.g.:
http:/example.com/ => site in english
http:/example.fr/ => same site in french
This is generally done by modifying the settings.php file to allow these alternate domains to be used.  And in the case of i18n sites, the language detection settings.
So basically these two terms intersect each other but are still different.


double integral boundaries

Question: I Have the following equation:
$$\int\int_{D}x^3 dxdy$$
With $D$ belongs to the real numbers squared. It is limited by the curve with the equation $xy=16$, the line $y=x$, the horizontal line $y=0$ en the vertical line $x=8$. I have difficulties finding the right boundaries for both integrals. If I know how to find the boundaries, solving the equation won't be so hard I think.
Answer: These are the lines mentioned in the problem:

If you compute the intersection between the lines $xy=16$ and $y=x$, you will get the point $(4,4)$. And if you comput the intersection between the lines $xy=16$ and $x=8$, you will get the point $(2,8)$. Can you take it from here?
Comment: Yes i can, thank you!
Answer: $$\int\int_{D}x^3 dxdy=\int_{2}^{4}\int_{y}^{16/y}x^3dxdy+\int_{0}^{2}\int_{y}^{8}x^3dxdy$$
Comment: Thank you very much!

double integral boundaries


Expression for $1-\sin x$

Question: Do we take $1-\sin x$ as $(\sin \frac{x}{2}-\cos \frac{x}{2})^2$ or $(\cos \frac{x}{2}-\sin \frac{x}{2})^2$. My teacher says that in most of the cases we take the latter. In one problem the interval was specified as something like $(\frac{\pi}{2},\pi)$ and my teacher told me to take the former. I am facing problem in understanding this. Can someone shed some light on this? Also what about $1+\sin x$.
Both the expressions may be the same but they yield different results (in differentiation and integration problems) and I have myself seen this.
Comment: $(a-b)^{2} = (b-a)^{2}$, hence I don't understand why it is even bothering you.
Comment: @AnikBhowmick, Both may be the same but they yield different results.
Comment: What is the context of this question? If I were to see "$1-\sin x$" in the wild, I'd leave it as-is; re-writing in either suggested form just adds visual and mental clutter. However, if I had $\sqrt{1-\sin x}$, then it would certainly be convenient to identify the expression as a square in order to cancel the radical. In this case, you could still use either suggested form, since you need to wrap it in absolute value bars anyway; however, the latter has a *sliver* of an advantage, in that you can drop the absolute value bars when you know $x$ happens to be acute.
Comment: Is this question related to taking square roots?
Comment: One of the problems did involve square roots.
Comment: *"One of the problems did involve square roots."* Please show us some of these problems ... especially ones where the different choices "yield different results". It's easier to give advice when we know just exactly how the advice needs to be applied.
Comment: I don't exactly remember the problem now.
Comment: Problem arises if you take the square roots.
Answer: Those expressions are equal so... Both. Regarding the last question, plug $x \mapsto -x$ and you'll have an almost equal expression.
Answer: Use that $$\sin^2(x/2)+\cos^2(x/2)-2sin(x/2)\cos(x/2)=1-\sin(x)$$ and $$(\sin(x/2)+\cos(x/2))^2=1+\sin(x)$$
Answer: For any real number $x$, you have that
$$x^2 = (-x)^2 $$
Since
$$\sin\frac x2 - \cos \frac x2 = -\left(\cos \frac x2 - \sin\frac x 2\right)$$
The two expressions, (1):
$$\left(\sin\frac x2 - \cos \frac x2\right)^2 $$
and (2):
$$\left(-\left(\cos \frac x2 - \sin\frac x 2\right)\right)^2 = \left(\cos\frac x2 - \sin\frac x 2\right)^2 $$
are equal.
Since they are the same, they cannot yield different results. An error must have been made. Unless I'm misunderstanding what exactly is being asked.
Answer: Hint:
As for real $a,\sqrt{a^2}=|a|$ which will be $=+a$ if $a\ge0$
Now $1-\sin2y=(\cos y-\sin y)^2=2\sin^2\left(\dfrac\pi4-y\right)$
Now $\sin u\ge0$ if $u$ lies in the first & second quadrant
Similarly, $(\sin y+\cos y)^2=?$

Expression for $1-\sin x$


Como passar um parâmetro de uma Action para outra Action em um mesmo Controller

Question: Preciso enviar um parâmetro de uma action para outra action num mesmo controller, porém o parâmetro fica "zerado". Como posso fazer isso? Abaixo o código que estou fazendo:
[Authorize]
public class ItemMaloteController : Controller
{
    public IActionResult Index(Guid id)
    {
        ViewBag.ItemsMaloteList = _itemMaloteRepository.GetAll()
                                       .Where(x => x.MaloteId.Equals(id)).ToList();

        ViewBag.Malote = _maloteRepository.GetAll()
                         .Where(x => x.Id.Equals(id)).ToList();

        ViewBag.Curso = _cursoRepository.GetAll().ToList();
        ViewBag.Documentos = _documentosRepository.GetAll();
        ViewBag.MaloteId = id;

        return View();
     }

     public IActionResult Create(ItemMalote itemMalote)
        {
            if (!ModelState.IsValid)
                return NotFound();

            itemMalote.Id = Guid.NewGuid();
            _itemMaloteRepository.Register(itemMalote);
            _itemMaloteRepository.SaveChanges();

            var maloteId = _itemMaloteRepository.GetMalote(itemMalote.MaloteId).Select(x => x.MaloteId).ToList();

            //Aqui eu chamo minha action "Index" e passo o parametro
            return RedirectToAction("Index", maloteId);
        }
}

Acontece que quando chega novamente na action "Index" o parâmetro chega "zerado". Já tentei passar via TempData, mas acontece o mesmo.
Answer: return RedirectToAction("Index", new { id = maloteId });

Com a solução acima dada pelo Pedro você terá como redirecionamento isso:

/Controller/Index/maloteId

Mas há mais overloads para o método RedirectToAction. Se precisar redirecionar para a action de outra controller, por exemplo, você pode usar dessa forma:
return RedirectToAction("MinhaAction", "MinhaController", id);

Mas nessa questão do SOen vi que ainda assim é possível não ser redirecionado e você pode usar também dessa forma, utlizando o RouteValueDictionary:
return RedirectToAction("SuaAction", new RouteValueDictionary(
       new { controller = "SuaController", action = "SuaAction", Id = id }));

Ou você pode apenas fazer isso também:
return Index(id);

Answer: Crie um tipo anônimo com o parâmetro id que sua Action Index está esperando:
//Aqui eu chamo minha action "Index" e passo o parametro
return RedirectToAction("Index", new { id = maloteId });

Comment: Faltou apenas o return :)
Comment: Verdade, havia me esquecido... Já editei a resposta. Muito obrigado!


Add  link around each row in views

Question: So basically i want to add a link to original node around each row in views. I have added the following code to the style and row template override in views. Both come up with the same result.
<?php $image = file_create_url($row->field_field_display_image[0]['rendered']['#item']['uri']); ?>

  <div class="block__inner" style="background-image: url('<?php echo $image; ?>');">
    <?php foreach ($fields as $id => $field): ?>
      <?php if (!empty($field->separator)): ?>
      <?php print $field->separator; ?>
    <?php endif; ?>

Now the issue that i am having is that the link is added to each field element that is outputted for some reason, and not just the link around the whole row and each field.
I cannot use custom field as that is making the same issue. It seems views is auto closing the a tag.
Any known workarounds?
Comment: This issue always bugged me, still does. The only workaround I have is to use jQuery. I don't get it, a `display: block` anchor is a perfectly valid wrapper element imho.
Comment: I've literally spent hours trying to debug this, seems like something that should quite easily work, and am hoping there is a way other than jquery. May raise a bug on drupal.org issue page
Answer: I usually remove all default formatting from every field, then hide all of my fields from display apart from the last field in views, and also remove all formatting, making the hidden fields plain text where possible.
Then in that last fields settings, rewrite the results, and input all of the fields as tokens from the replacement patterns.
Then instead of div elements, I use span which plays better inside an anchor, and just add unique classes for each span element.
So an example rewrite results might be...

[title]
[body]

This should not suffer the same issue if you go to each hidden field, and under the style fieldset, make sure than no default wrapper or classes are applied, and also that each field is plain text. This will strip all formatting and place it inside the rewritten span elements. Like @BeeBee says, div and p will break the anchor wrapper.
Comment: Spans inside an anchor is fine @Collins . It's the block elements such as `div` and `p` that cause anchors to auto-close, because someone in Views or Drupal team decided anchor tags are not valid wrappers, even if they're set to `display:block`
Comment: This should not suffer the same issue if you go to each hidden field, and under the style fieldset, make sure than no default wrapper or classes are applied, and also that each field is plain text. This will strip all formatting and place it inside the rewritten span elements. Like @BeeBee says, div and p will break the anchor wrapper.
Comment: found this has the same issue, but i need to use rewriting of another field, if one is empty, which means this option isn't a possibility for me.
Comment: This is a decent workaround!
Answer: Override views template for Style output
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php $i = 0;?>
<?php foreach ($rows as $id => $row): ?>
  <a href="node/<?php print $view->result[$i]->nid;?>">
  <?php $i++;?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

Make sure there are no inner links (title with link to original content for instance).
Comment: no need for the $i I think, $view->result[$id] should work
Answer: I have found that the best control for changing markup on views (by row) is to set the view to be an unformatted list.
See here:
https://api.drupal.org/api/views/theme!views-view-unformatted.tpl.php/7
Also, test carefully when you wrap elements in your anchor tag.  with older versions of IE specifically, but any browser really.  anchors don't play well with a bunch of other markup inside them.
Comment: Unformatted list is what i almost always use for views, am still having the issue and using Chrome.

Add  link around each row in views


viewdidappear not called when adding subview to navigation controller

Question: func showCustomViewController(vc : UIViewController,dummy : UIView,fromView1:UIViewController){
    datePickerShown = true
    let fromView = fromView1.navigationController?.view
    var navTopConstraint : NSLayoutConstraint!
    vc.view.translatesAutoresizingMaskIntoConstraints=false

    self.navigationController?.addChildViewController(vc)
    dummy.addSubview(vc.view)
    vc.didMove(toParentViewController: self.navigationController)

    dummy.addConstraint(NSLayoutConstraint(item: vc.view, attribute: .top, relatedBy: .equal, toItem: dummy, attribute: .top, multiplier: 1, constant: 0))
    dummy.addConstraint(NSLayoutConstraint(item: vc.view, attribute: .left, relatedBy: .equal, toItem: dummy, attribute: .left, multiplier: 1, constant: 0))
    dummy.addConstraint(NSLayoutConstraint(item: vc.view, attribute: .width, relatedBy: .equal, toItem: dummy, attribute: .width, multiplier: 1, constant: 0))
    dummy.addConstraint(NSLayoutConstraint(item: vc.view, attribute: .height, relatedBy: .equal, toItem: dummy, attribute: .height, multiplier: 1, constant: 0))
    dummy.backgroundColor=UIColor.clear

    if dummy.superview == nil{
        fromView?.addSubview(dummy)
    }

    for constraints in dummy.constraints{
        if constraints.firstAttribute == .top{
            navTopConstraint = constraints
        }
    }

    fromView?.addConstraint(NSLayoutConstraint(item: dummy, attribute: .width, relatedBy: .equal, toItem: fromView, attribute: .width, multiplier: 1, constant:0 ))
    fromView?.addConstraint(NSLayoutConstraint(item: dummy, attribute: .top, relatedBy: .equal, toItem: fromView, attribute: .top, multiplier: 1, constant: -60))
    fromView?.addConstraint(NSLayoutConstraint(item: dummy, attribute: .bottom, relatedBy: .equal, toItem: fromView, attribute: .bottom, multiplier: 1, constant: 0))
    fromView?.addConstraint(NSLayoutConstraint(item: dummy, attribute: .left, relatedBy: .equal, toItem: fromView, attribute: .left, multiplier: 1, constant: 0))

    navTopConstraint.constant = (fromView?.frame.maxY)!
    fromView?.layoutIfNeeded()

    UIView.animate(withDuration: 0.33, delay: 0, options:.curveEaseInOut, animations: {
        dummy.backgroundColor=UIColor.init(white: 0.0, alpha: 0.4)
        navTopConstraint.constant=0
        fromView?.layoutIfNeeded()
    }, completion: nil)
}

dummy view is the uiview added to the current navigation controller view.
vc is the viewcontroller to be added to the navigation controller view.
In vc viewcontroller, viewdidload is called.
But viewdidappear and viewwillappear is never called.why is it so? and how to call the same.Thanks in advance
Answer: According to Apple's documentation the order you added the view controller and view is correct, however, sometimes there seems to be a bug when you add the view controller before adding the view (possibly some sort of race condition).
Try adding the view first before adding the controller as child view controller
dummy.addSubview(vc.view)
self.navigationController?.addChildViewController(vc)

You could maybe also try to wrap the addChildViewController() method inside a defer block.


How to use torch RNN and LSTM packages and are they necessary?

Question: I have come across this brilliant site where I finally understood BPTT for RNN's and want to implement it. The code is given in python but I want to implement it in torch using lua. I have understood the code and have translated most of it to lua with torch functions. However, I have often come across packages for torch on github like this. How can we use these packages? If we were to use them, would we not need to type even a single line of code? Isn't it better if I first completely code the RNN myself to understand and then go on to the packages?
Answer: If you want to learn, implement from scratch. If you want to apply, just use some packages: the amount of tweaking the latter require depends on the package and your application.


Understanding the Java Memory Model and Garbage Collection

Question: I tend to get these questions asked by a lot by students, or by co-workers looking for a resource, so I wanted a more definite reference for them. Might as well share it with the community.

How is the Java Memory Model represented and what are its characteristics?
How does Garbage Collection work in general and in the most common JVMs?
How do I test and tune my Java applications for performance?
Comment: That's a very broad question... but I agree that it's something every java programmer should know.
Comment: Nice set of references!
Answer: Memory Basics

What Every Programmer Should Know About Memory - Ulrich Drepper [PDF]

Java Language and Virtual Machine Specifications

The Java Virtual Machine Specification [PDF and HTML for Java SE 7]

Java Memory Model

Advanced Topics in Programming: The Java Memory Model - Jeremy Manson [video]
Collection of Resources on the Java Memory Model - edited and compiled by Bill Pugh (collection)
Memory Management in the HotSpot Virtual Machine - Sun Microsystems (2006) [PDF]
Fixing the Java Memory Model - Brian Goetz, IBM Java Developer Series () [part 1, part 2]

Java Performance

9 Fallacies of Java Performance - Ben Evans [video + slides]
JVM Performance Magic Tricks - Takipi [blog + slides]
Java and the Machine - Kirk Pepperdine, Martijn Verburg [video + slides]
Performance Testing Java Applications - Martin Thompson  [video + slides]
Building Memory-Efficient Java Applications: Practices and Challenges - Mitchell, Sevitsky (2009) [PDF]

Advanced Topics and Real-Life Uses Cases

Optimizing Google's Warehouse Scale Computers: The NUMA Experience - University of California & Google [PDF]
MegaPipe: A New Programming Interface for Scalable Network I/O [Google Doc]
Mythbusting modern hardware to gain "Mechanical Sympathy" - Martin Thompson [PDF]
(slides)
Caching in: understand, measure and use your CPU Cache more effectively - Richard Warburton
[video + slides]
A JVM Does That?! - Cliff Click [video]

GC Tuning

Hotspot Garbage Collection - Tuning Guide - Martijn Verburg, John Oliver [video, slides pt 1, slides pt 2]
Are your GC logs speaking to you, the G1GC edition [slides, video]
The Principles of Java Application Performance Tuning [article]
Everything I Ever Learned About JVM Performance Tuning @Twitter - Attila Szegedi [video & slides]
Visualizing Java GC - Ben Evans [video + slides]

Complementary StackExchange Questions and Answers

Java Memory Model
JRockit JVM versus HotSpot JVM
How to destroy java objects?
Smart Garbage Collection?

And many, many more to come that I need to dig up from my archives or from the inter-tubes.
Comment: What do you think about "Java Concurrency in Practice" as a guide to writing code that works with the Java memory model?
Comment: @PatriciaShanahan: I think that in general anything by Brian Goetz is worth knowing about.
Comment: I feel this is a "link only answer". And not a good one. Do you mean that to understand the JMM and GC we need to first read a 600 pages long pdf and your 30 links?
Comment: @Matsemann: In order: it is. Arguably. No, but that'd help. So, they're helpful, and as mentioned I often get asked this question (note this is my question as well), and while most of these resources can be found with a relatively quick online search, this helps to consolidate some resources and have a single place where to point people (and that is likely to show up rather high in search results), and where it can be edited. Seems good enough for me, and useful for many. I don't deny the link-only aspect and the question really fitting here. Feel free to flag it if you must (or edit).
Comment: Someone apparently flagged the question. I think your links may be a good resource, but way too much to dig through. If something, a community wiki is a better fit.
Answer: William Pugh, one of the authors of "JSR-133: Java Memory Model and Thread Specification" maintains a webpage about the memory model here:
http://www.cs.umd.edu/~pugh/java/memoryModel/
The complete JSR-133 can be found here:
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf
Also relevant is the Java Language Specification, Section 17.4 Memory Model:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4


Is Rest API with OAuth2 available for Evernote Business?

Question: I am doing integration for Evernote Business. So, I would like to know that is Evernote for Business support Rest API with OAuth2?
Comment: Welcome to stack overflow :-) please look at [ask].
Answer: Evernote does not provide an official REST API; their API is Thrift-based.   If you're interested in why it's Thrift-based and not REST, their former CTO discusses the reasons for that decision on their tech blog.
Tadaya Tsuyukubo has written a REST-based front end for the official Evernote API which is available here on GitHub. I haven't tried it so can't personally vouch for it.  There's also a bit of discussion about it here on the Evernote discussion forum.


programmatic ally update the QnAmaker using C#

Question: I was able to programmatically add, delete the qna pair using C# and below syntax
new_kb = "{'add': { 'qnaList': [{'id': 101001,'answer': '" + answer + "','source': 'Editorial','questions': ['" + Question + "'],'metadata': []}],'urls': []},'delete': {},'update': {}}";
new_kb = "{\"add\":null,\"delete\":{\"ids\":[" + id + "],\"sources\":null},\"update\":null}";
I am having an issue with the Update syntax below is what i have tried but no luck
new_kb = "{'update': { 'qnaList': [{'id': '" + id + "','answer': '" + ans + "','source': 'Editorial','questions': ['" + qs+ "'],'metadata': []}],'urls': []},'delete': {},'add': {}}";

new_kb = "{\"add\":null,\"update\":{\"ids\":[" + id + "],\"questions\":[" + qs + "],\"answer\":[" + ans+ "],\"sources\":null},\"delete\":null}";

Answer: If you just want to update your questions/answers of your qna pair , try this :
new_kb = "{'update':{'qnaList':[{'id':"+ id +",'answer':'"+ answer + "','questions':{'add':['"+ qs_new + "'],'delete':['"+ qs_old + "']}}]}}";

If you have any further concerns , pls feel free to let me know : )
Comment: Hi @spStacker, how's going ? Has the issue been solved ?


Interpreting intercept with centered predictors in logistic mixed model

Question: I am running a logistic mixed model in lme4. The model is as follows
<code>logme <- glmer(Correct ~ PE_Condition.ct*sumspq + (1|Pt_ID),
    family = binomial, data = test_CorrectPred.ct,
    control=glmerControl(optimizer="bobyqa"))
</code>
I have one continuous predictor which is a questionnaire score (sumspq). I also have a categorical predictor (PE_Condition) with two levels: 0= 'low' and 1= 'high'.
My dependent variable is correct/incorrect responses.
In accordance with Jaeger (2008), I have centered both predictors to reduce multicollinearity (as there is an interaction).

I want to check my understanding of the intercept.

I believe the intercept assesses whether the log-likelihood of producing a correct response is significantly greater than 50% when a participant has a mean spq score?

This is a 3AFC task, meaning participants have 3 response options and only 1 is correct. Chance level is therefore 1/3 rather than 50%. Out of interest, is there any way to reflect this in the intercept (to assess chance performance as 33% rather than 50%)? I'm not quite understanding why centering makes the intercept as 50%.

Reference: Jaeger TF. Categorical Data Analysis: Away from ANOVAs (transformation or not) and towards Logit Mixed Models. J Mem Lang. 2008 Nov;59(4):434-446. doi: 10.1016/j.jml.2007.11.007. PMID: 19884961; PMCID: PMC2613284.
Comment: Please add the full reference for Jaeger 2008. The intercept is the predicted log-odds of being correct if both predictors are at their means. The corresponding hypothesis test tests the null that the intercept is 0, i.e. that the probability is 50%. To change this to a null of 1/3, calculate the test statistic as $(\hat{\beta}-(-\log(2))/\mathrm{SE}$, where $\mathrm{SE}$ is the standard error. Then use `pnorm` to calculate the p-value. The $-\log(2)$ is the log-odds for a probability of 1/3, if you're wondering.
Comment: Yes, $\hat{\beta}$ is just the estimated intercept. Your interpretation is almost correct but a bit imprecise. The intercept is the predicted log-odds (not log-likelihood) for being correct if all predictors are 0 (which means at their means if you centered them).
Comment: Yeah, centering the binary predictor in this case is very questionable, in my opinion. If you left is as it was, the intercept would be the log-odds of being correct if sumspq is average and PE_Condition was "low".
Comment: What are you trying to learn from your model exactly? The focus is usually on quantifying the effect of changes in the predictor(s), the intercept is there to model the response for all other predictor values being 0. It doesn't have much to do with response over or under 50% rather than that being the back-transformation for log-odds of *all* parameters (including intercept) being 0, and that also being the default hypothesis test.
Comment: @COOLSerdash thank you. I presume the beta hat here would be the intercept estimate? For my first question, do you know if the interpretation of the intercept is correct in this case?
Comment: Great, thanks so much. For the intercept interpretation, I understand that the continuous predictor sumspq will have its mean at the intercept. However, the categorical variable is also centered. I'm therefore uncertain how this can be interpreted.
Answer: For those interested in future, I attempt to answer Q1 to the best of my ability. In this explanation, 'centering' refers to grand-mean centering. The binary predictor is dummy coded.
I would recommend two papers that provide insight into centering categorical predictors in mixed models:
Enders, Craig K, and Davood Tofighi. "Centering Predictor Variables in Cross-Sectional Multilevel Models." Psychological Methods 12.2 (2007): 121-38. Web.
Yaremych, Haley E, Kristopher J Preacher, and Donald Hedeker. "Centering Categorical Predictors in Multilevel Models: Best Practices and Interpretation." Psychological Methods 28.3 (2023): 613-30. Web.
Of particular relevance is Enders & Tofighi's (2007) detailed explanation of interpreting the intercept with a level 1 binary predictor (equivalent to my high vs low PE_Condition variable) on pg 134.
In my example, the intercept for a model with only 'PE_Condition' (high vs low) included as a fixed effect would be the adjusted mean log-odds of producing a correct response. The mean is 'adjusted' as it is conditional on an equal proportion of 'high' and 'low' responses for each participant. Given the inclusion of a random participant intercept, this intercept will vary between participants.
Adding the (centered) continuous predictor 'sumspq' to the model will change the intercept to be the adjusted mean log-odds of producing a correct response, holding sumspq constant at the grand mean.
For my study, this intercept is not particularly useful, and I am focusing instead on the main effects and interaction. However, it is recommended to center both continuous and categorical predictors to reduce collinearity in models with interactions (refer to the above papers as well as Jaeger (2008) in my original question for further details).


Custom View is only displayed on the upper left corner

Question: what I want to do is to add a custom view to my activity and freely drag and drop it wherever I want to. I create a new class "Square". When I construct a new Square it is displayed in the upper left Corner of the Display. When I set X and Y coordinates it disappears. If I set X and Y to 30 I see that the Square is displayed partiatelly. So it seems that my view is only displayed in a small Frame on the top Left of the Display.
Please help me to move my custom view oder the Display. Thanks!
MainActivity:
private Button btnNewSquare;
private RelativeLayout relativeLayout;
private Square[] square = new Square[10];
int squareId = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnNewSquare = (Button)findViewById(R.id.button1);
    relativeLayout = (RelativeLayout)findViewById(R.id.RelativeLayout);

    btnNewSquare.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v == btnNewSquare) {
        squareId++;
        square[squareId] = new Square(this);
        square[squareId].setX(30);
                    square[squareId].setY(30);
        square[squareId].setOnTouchListener(square[squareId]);
        relativeLayout.addView(square[squareId]);
        relativeLayout.invalidate();
        Toast.makeText(getApplication(), "Square" + squareId, Toast.LENGTH_SHORT).show();
        square[squareId].invalidate();
    }
}

Square
private int squareWidth = 100;
private Paint paint;

public Square(Context context) {
    super(context);
    initSquare();
    // TODO Auto-generated constructor stub
}

public Square(Context context, AttributeSet attrs) {
    super(context, attrs);
    initSquare();
}

private final void initSquare() {
    paint = new Paint();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

   setMeasuredDimension(squareWidth, squareWidth);
}

@Override
protected void onDraw(Canvas canvas) {
    //super.onDraw(canvas);
    paint.setStyle(Style.FILL);
    paint.setColor(Color.BLACK);
    paint.setStrokeWidth(3);
    canvas.drawRect(getX(), getY(), getX() + squareWidth, getY() + squareWidth, paint);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_UP) {
        v.setVisibility(View.VISIBLE);
    }
    return false;
}

My XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/RelativeLayout"
    tools:context="${relativePackage}.${activityClass}" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="38dp"
        android:text="New Square" />

</RelativeLayout>

Comment: I investigate further. It has nothing to do with drag and drop. I set X and Y to 30 on the creation of my square, it is only painted partilly. It seems that there is some Kind of mask on the top left Corner of the app, and the square is only displayed there.
Answer: The answer is simple. The coordinates in the onDraw() method are belonging to the view, not to the Screen. So if I move my view via Drag and Drop to let's say (500, 500) I have to draw my rectangle in the onDraw method still at (0,0,100,100) and not at (500, 500, 600, 600) so the correct line of code would be:
canvas.drawRect(0, 0, squareWidth, squareWidth, paint);
and not
canvas.drawRect(getX(), getY(), getX() + squareWidth, getY() + squareWidth, paint);


Prove that the equation of two planes inclined at an angle $\alpha$ to x-y plane

Question: Prove that the equation of two planes inclined at an angle $\alpha$ to x-y plane and containing the line $y=0, z \cos\beta=x\sin\beta$ is  $~~(x^2+y^2) \tan^2\beta+z^2-2zx~\tan\beta=y^2\tan^2\alpha$.
My approach: Let $l_1 x+m_1y+n_1z=d_1$ and $l_2 x+m_2y+n_2z=d_2$ be the two planes containing the lines formed by intersection of two planes then angle between direction ratios of planes and lines will be 90 degree.
Answer: Since the plane contains the line which passes through the origin, we can write the equation of the plane as $$Ax+By+z=0$$
It contains the line described, so $$A\cos\beta+\sin\beta=0$$
Meanwhile, using scalar product, the the angle $ \alpha$ satisfies $$\cos\alpha=\frac{1}{\sqrt{A^2+B^2+1}}=\frac{1}{\sqrt{B^2+\sec^2\beta}}$$
Rearranging this gives $$B=\pm\sqrt{\sec^2\alpha-\sec^2\beta}$$
Substituting in the values of $A$ and $B$ into the plane equation gives
$$-x\tan\beta\pm y\sqrt{\sec^2\alpha-\sec^2\beta}+z=0$$
You can now rearrange this so that the square root gets squared, and required result follows almost immediately.
I hope this helps
Comment: You can accept the answer and close the question if this answer is what you are looking for.
Comment: Thanks@David Quinn for your help


Drupal Views Datasource and Flag Links

Question: I want to use Views Datasource module to output JSON, i then want to construct the JSON output using REACT JS or alike. I am currently stuck on how to output the Flag Link, it just comes back with an OPS field. Ideally i want this as a plain link so I can trigger it through jquery/ajax.

UPDATE: as requested using the php field i managed to get the output i was after which is something like:
Comment: I might have a possible alternative for you to consider. But can you first enhance your question to better explain what I should see (or not see) in the JSON sample in your (last) picture. Maybe something like "this is what I get, but this is what I would like to get"?
Comment: @Pierre.Vriens done
Comment: OK, that helps already quite a bit to better understand. But is your new result now something like the first JSON picture, in which the lines in your last picture are inserted somewhere? And also: did you actually "manage" to do so using Views PHP (as in your answer)? Last question: do you insist in using "Views datasource" (and views PHP), or are you open to an alternative solution that does not require those 2 modules? Just to make sure my possible answer might fit "also", ok?
Comment: @Pierre.Vriens, my new result is in the right format i.e. showing me the path to the flag and with token. yes i did manage to do it with Views PHP and no i don;t insist on using View data source and Views PHP (would much rather avoid using Views PHP), but Viewsdata source makes it very easy.
Answer: Unfortunately I couldn't get the perfect solution to this so I had to use Views PHP. Remember to add a hidden field for the nid of the node
<code><?php
$link = flag_create_link('MyFlagMachineName', $row->nid);
preg_match_all('/<a[^>]+href=([\'"])(.+?)\1[^>]*>/i', $link, $result);
if (!empty($result)) {
  echo $result[2][0];
}
?>
</code>

Drupal Views Datasource and Flag Links


How do I know where to place holes on an instrument?

Question: I've been trying to build a double reeded instrument out of plastic straws. I've run into a problem though, when I place fingering holes, the instrument doesn't seem to follow the $$f=/frac{nv}{4L}$$ formula. Is there a formula that would allow me to calculate where along the instrument I should place the holes?
Comment: It seems that MathJax (the fraction code) isn't supported on Music SE.
Comment: I guess the answer is *guess*! :D It may also be trial and error.
Answer: For a pipe without any holes, the fundamental pitch of a pipe is determined by f = v/2L, where v is the speed of sound and L is the length of the pipe.
But when you start putting holes in, you get a mix of pipe lengths. It gets messy (mathematically) in a big hurry.
Placing a hole in the pipe shortens its length, but the new length - the effective length - isn't the distance to the hole, because that isn't the end of the pipe.  The larger the hole, the more it will behave like the ideal.  The smaller the hole, the longer the effective length will be.
Because the hole size is a variable, you're not going to find a formula that's going to fit every situation.  That's because the hole size is a variable in relation to the diameter of the tube: a 1cm hole in a 10cm tube will have a different effective length than a 1cm hole in a 9cm tube.
Since no formula is going to work for all situations, you have do some trial and error.  If the pitch is flat, you can enlarge the hole to shorten the effective length.  If the pitch is sharp, you'll have to figure out a way to make that hole smaller (or make the whole tube longer - there's a reason woodwinds have multiple pieces!)
There are other variables, too... conical bores behave differently than cylindrical ones.  But I'm assuming you're using a cylindrical tube.
Comment: "In a perfect world" is a common idiom that means a world that conforms to the model in use. You're taking it too literally.
Comment: "In a perfect world" – that's a bit of a silly way to put it. You might also say in a perfect world the air flow is perfectly linear and laminar – however, in that case the mechanism by which flutes bring the air to vibrate in the first place also wouldn't work! And even assuming you get the air to vibrate in the perfect cylinder: _nobody would be able to hear the sound_, because all the energy is trapped! I wouldn't call that perfect. No, the world is exactly as good as is actually happens to be – what's imperfect are the models with which we describe certain phenomena in the world.
Comment: @leftaroundabout I changed the answer -- see if it is more readable now.
Comment: @CarlWitthoft - I altered your edit.  Helmholtz resonance is the frequency created by air "bouncing" at the mouth hole.  It contributes to the overall timbre whether there are holes or not, and introducing holes does not change the Helmholtz resonance - that's fixed by the size of the mouth hole and the thickness of the tube material.  Open holes don't have Helmholtz resonance frequencies, because the air pressure in the tube is always higher than that outside; the air simply escapes without additional vibration.
Comment: @TomSerb thanks for doing that.  I should have emphasized where Helmholtz was applicable (see "Ocarina"  :-) )
Answer: The main problem is that it's an oversimplified assumption to consider an open hole as a perfect open boundary condition for the air column. In fact such a hole still has a significant impedance. On the other side, the mouthpiece is not a perfect closed (reeds) or open (flutes) boundary condition, and also a closed hole still affects the column somewhat. A pitch formula would need to take all those factors into account, which depend on hole size and bore. Doing this accurately would require a big CFD model.
In practice, probably almost every wind instrument maker has instead used empirical models, i.e. basically trial and error. It should certainly be possible to fit a formula to that which is more accurate than the overidealisation but still reasonably accurate, but whether one is available publicly I don't know.
Comment: I suspect that Adolphe Sax used the same spacing ratios in (soprano, alto, tenor, bari) at least as a starting point, given the similarity in the bore shapes.


A pair of non group homeomorphic topological groups

Question: The following assertion is true:
If $A$ and $B$ are dense group homeomorphic subgroups of complete Hausdorff topological groups $X$ and $Y$ respectively, then $X$ and $Y$ are group homeomorphic.
I wonder if we can find $A$ and $B$ such that $A$ is homeomorphic to $B$, but not group homomorphic and that $A$ and $B$ are dense in topological groups $X$ and $Y$ respectively, but $X$ and $Y$ are not homeomorphic.
Then what about $X$ and $Y$ are homeomorphic but not group homomorphic?
The the topological groups are assumed to be commutative, by group homeomorphic we mean that (topological) homeomorphic that is also (group) homomorphic.
Comment: For the second question, you can just take $A=X$ and $B=Y$ whenever you have $X$ and $Y$ that are homeomorphic but not group-homeomorphic.
Comment: I miss the completeness, in fact, it is an assertion from Narici Topological Vector Spaces second edition, I have edited the assertion to include the desired completeness.
Comment: @EricWofsey I'm having a silly moment - are there homeomorphic, non-group-homeomorphic Lie groups?
Comment: @NoahSchweber: Sure; just consider discrete groups.  If you want them to be connected and abelian, however, then homeomorphic implies group-homeomorphic.
Answer: Sure, there's lots of examples.

$A$, $B$ homeomorphic, not group homeomorphic, and $X, Y$ not homeomorphic: Take $X=\mathbb{R}$, $Y=\mathbb{R}^2$ with the usual topologies and group structures. Let $A=\mathbb{Q}\subseteq X$ and $B=\mathbb{Q}^2\subseteq Y$. Then $A$ and $B$ are dense in $X$ and $Y$ respectively, are topological subgroups, and are homeomorphic (this might be a bit surprising, but it's true, and a good exercise) - but clearly $X$ and $Y$ are not homeomorphic!
$A$, $B$ homeomorphic, $X$, $Y$ homeomorphic, but $X$, $Y$ not group homeomorphic: Consider the sets $2^\omega$ and $3^\omega$ of infinite strings from $\{0, 1\}$ and infinite strings from $\{0, 1, 2\}$ respectively. These sets carry natural group structures - the $\omega$-fold products of $\mathbb{Z}/2\mathbb{Z}$ and $\mathbb{Z}/3\mathbb{Z}$, respectively. They also have a natural topological structure (the product topology, with the discrete topology on each fact), and form topological groups. As spaces, they are homeomorphic, but obviously they are not group isomorphic; these will be our $A$ and $B$. Now let $X$ and $Y$ be arbitrary countable dense subgroups of $A$ and $B$, respectively. We will have $X$ and $Y$ homeomorphic as topological spaces.


React Axios get a 404 with jsonbin

Question: I'm using JSONBin to mock-up data from a JSON fake list of users.
The code works fine in a public bin but I'm getting a 404 req as soon I send headers in Axios
My code is:
useEffect(() => {
    axios.get(`${baseURL}/63be860ddfc...[bin-ID etc]/latest`, {
      headers: {
        "X-Master-Key": "<MASTER-KEY-HERE>",
        "X-Access-Key": "<ACCESS-KEY-HERE>"
      }
    })
    .then((res) => {
      setUsers(res.data.record);
      console.log('theRes:', res)
    })
    .catch(error => {
      console.log('theError:', error);
      setError(error);
    })
  }, []);

Console error is:
AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code: "ERR_BAD_REQUEST"
config:
adapter:(2) ['xhr', 'http']
data: undefined
env: {FormData: ƒ, Blob: ƒ}
headers:
AxiosHeaders Accept: "application/json, text/plain, */*"
Content-Type: null
X-Access-Key:"<THE-ACCESS-KEY-...>"
X-Master-Key:"<THE-MASTER-KEY-...>"
Symbol(Symbol.toStringTag): (...)
[[Prototype]]: Object
maxBodyLength: -1
maxContentLength: -1
method:"get"
timeout: 0
transformRequest: [ƒ]
transformResponse: [ƒ]

I followed this documentation https://jsonbin.io/api-reference/bins/read but I guess I missed something
Comment: FYI: You are not supposed to use `X-Access-Key` and `X-Master-Key` at the same time, you need only one
Answer: This was a configuration issue on the .env file.
The var url was adding an extra "/"
baseURL = <URL>/

result was: <URL>//63be860ddfc

React Axios get a 404 with jsonbin


Special function related to a nonlinear ODE

Question: I am interested in finding a special function solution of the following ODE
$ (r S)^{\prime \prime} = - 2 r S^2 $
with initial conditions
$ S(0)=1, S^\prime(0) = 0 $.
The method of Frobenius gives the infinite series
$
S=
1 -\frac{{{r}^{2}}}{3}+\frac{{{r}^{4}}}{15}-\frac{11 {{r}^{6}}}{945}+\frac{16 {{r}^{8}}}{8505}-\frac{97 {{r}^{10}}}{334125} +\frac{914 {{r}^{12}}}{21049875} +H.O.T
$
and the following recursion among the coefficients:
$ a_n= - \frac{2}{n (n+1)}\sum\limits_{j=0}^{n-2}{\left. a_j a_{n-j-2} \right.}$
The question is: is this function related to the generalized hypergeometric functions?
If yes - what is the relationship?
Comment: I can't say for sure, but hypergeometric functions are solutions to linear ODEs
Comment: It could be related to elliptic functions, especially since for $r \to \infty$ the equation $rS'' + 2S'+ 2 r S^2=0$ becomes $S'' +  2 S^2=0$ which Mathematica solves in terms of https://en.wikipedia.org/wiki/Weierstrass%27s_elliptic_functions
Answer: Let $U=rS$ ,
Then $U''=-\dfrac{2U^2}{r}$ with initial conditions $U(0)=0$ , $U'(0)=1$
Which reduces to an Emden–Fowler equation.


Java gson convert error

Question: İ'm trying to develop swing app on netbeans.İ'm using gson to decode json.İ get json data from php site. İ couldn't convert json data to java array.
How could i convert getting json file to java array. And then İ need to set jcombobox datasource this array.
My json file like this on url
[{"id":"1",
"ad":"jack",
"latitude":"41.0000",
"longitude":"32.000",
"speed":"",
"hour":"01:28:56",
"day":"18.04.2016",
"adres":"adres",
"resimyol":"http:\/\/maps.google.com\/maps\/api\/staticmap?.jpg"},
{"id":"2",
"ad":"Abraham",
"latitude":"41.0000",
"longitude":"41.0000",
"speed":"",
"hour":"01:28:56",
"day":"18.04.2016",
"adres":"adres",
"resimyol":"http:\/\/maps.google.com\/maps\/api\/staticmap?.jpg"}]

And here my java file
public class JsonPojo {
public String id;
public String ad;
public String latitude;
public String longitude;
public String speed;
public String hour;
public String day;
public String adres;
public String resimyol;
public String getId() { return id; }
public String getName() { return ad; }
public String getlat() { return latitude; }
public String getlon() { return longitude; }
public String getspeed() { return speed; }
public String gethour() { return hour; }
public String getday() { return day; }
public String getadres() { return adres; }
public String getresim() { return resimyol; }

}

public static void main(String args[]) {
public void run() {
            new KonumGoster().setVisible(true);
             String json = null;
            try {
                json = readUrl("http://url.com/"
                        + "json.php");
            } catch (Exception ex) {
                Logger.getLogger(KonumGoster.class.getName()).log(Level.SEVERE, null, ex);
            }

Gson gson = new Gson();
JsonPojo[] array = gson.fromJson(gson, JsonPojo[].class);
JsonPojo obj = new Gson().fromJson(json, JsonPojo.class);
System.out.println("ID: " +obj.getId());
System.out.println("ID: " +obj.getName());
System.out.println("ID: " +obj.getlat());
System.out.println("ID: " +obj.getlon());
System.out.println("ID: " +obj.getspeed());
System.out.println("ID: " +obj.gethour());
System.out.println("ID: " +obj.getday());
System.out.println("ID: " +obj.getadres());
System.out.println("ID: " +obj.getresim());

}

When am i trying to run project its give me error like this
run:
Exception in thread "AWT-EventQueue-0" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 2 column 13 path $
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    at com.google.gson.Gson.fromJson(Gson.java:852)
    at com.google.gson.Gson.fromJson(Gson.java:801)
    at com.google.gson.Gson.fromJson(Gson.java:773)
    at KonumGoster$1.run(KonumGoster.java:145)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 2 column 13 path $
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:213)
    ... 19 more
BUILD SUCCESSFUL (total time: 5 minutes 5 seconds)

Answer: Gson gson = new Gson();
JsonPojo[] array = gson.fromJson(gson, JsonPojo[].class);
JsonPojo obj = new Gson().fromJson(json, JsonPojo.class);

The second statement uses gson instead of json as the first argument of Gson::fromJson. If you change this to json, GSON will do its job correctly.
And the error message in your build comes from the third statement, where you are trying to read a single oject out of a JSON array of objects. You only need the second statement and then iterate over its result to print each item.
Gson gson = new Gson();
JsonPojo[] array = gson.fromJson(json, JsonPojo[].class);
for (JsonPojo obj : array) {
    System.out.println("id: " + obj.getId());
    // etc
}

Java gson convert error


Does Drupal support Multitenancy?

Question: I have not been able to determine whether Drupal supports multitenancy:

Multitenancy refers to a principle in software architecture where a
  single instance of the software runs on a server, serving multiple
  client-organizations (tenants).

Specifically, I am interested in a single Drupal installation supporting multiple user organizations that would share the same environment but be able to have separate interface configurations and settings, and otherwise being totally unaware of other tenants (users).
An example would be a single install of Drupal being used to serve up multiple organizational websites in a SaaS type offering.
Does anyone have any information on this?
Comment: In Drupal we simply call it Multisites. https://drupal.org/documentation/install/multi-site
Answer: One of the strengths of Drupal is that it's not just a tool for building a single website. It can be used equally well for managing multiple companion sites together. This capability has existed for many years, but is not always well understood.
And in true Drupal fashion, modern Drupal has several different options available for users looking to run a series of Drupal sites together, each with its own trade-offs.

Separate installs
Features-based installs
Multi-site
Domain Access
Organic Groups
Mix and match

Separate installs :
Sometimes the best strategy is to not unify sites at all. In this case, any similarity between different sites is largely coincidental. If there will be a large number of sites then some automation tools such as Drush or Aegir may make spinning up new sites easier, but from a site building perspective they are different sites.
Features-based installs :
As a slight variation of separate installs, it's possible to run multiple installs with the Features module. For those not yet familiar with it (and you should be), Features is essentially an automation tool for those pieces of configuration that Drupal allows to be mirrored to code so that they may be checked into version control. These days much (but sadly not all) of Drupal's configuration can be feature-ized. The most effective configuration components to manage this way include content types, views, panels, and image styles.
Multi-site :
For years Drupal has had the ability to run multiple sites off of a single install base. In this case, there is a single copy of Drupal's code base but each college or department has its own settings.php file, which points to a different database. From a site builder perspective, this is almost the same as having separate installs. Every site must be configured independently, but every site may also be configured independently. Each site may also live on its own domain or in subdirectories, although the latter requires some symbolic link trickery and editing the Apache .htaccess file to make work.
Domain Access :
Domain Access (DA) is actually an access control module that uses the node grants system. With DA, a site administrator can point multiple domains to a single Drupal install. Drupal will then self-filter any nodes in the system to display only on specific domains. There is still a single database, single code base, single user base, and single content pool.
Organic Groups :
With OG, each node (any entity, really) can be made into a "group", and then other nodes can be associated to one or more groups. Depending on the configuration, that could impact navigation, path aliases, theme selection, and so forth, to give the impression of different "sites".
Mix and match :
When planning a large-scale Drupal rollout, it's also possible to consider combining strategies. For instance, both Domain Access and Organic Groups can run on their own Drupal instance that just so happens to be multi-site... and have other Drupal sites hosted on it as well. Workbench can be used for administration of content on a single Drupal instance independently of whether it uses DA or OG, and can easily be enabled on multiple instances on the same install as well. As of this writing Workbench does not integrate with either module, so for instance Organic Groups or Domains cannot be used to define "sections" in Workbench, but such integration is possible.

Conclusion
Drupal offers a variety of solutions to address multiple sites with shared and separate content. As with all things Drupal there is no right solution — just options for your specific needs. Evaluate your goals and make decisions based on them; you may find that Domain Access is a better fit for your content editors or a multi-site setup is much easier to manage for your system administrators.
Answer: Has anyone considered recommending Organic Groups? this is a lightweight less complete solution, but uses one Drupal installation and separates out each group as a unique and independent section.
Also. A much more elegant and true solution would be to use Aegir as a Host manager that spins up any number of unique sites for organizations.
Comment: In Drupal 8, Organic Groups has been superseded by [Group](https://www.drupal.org/project/group), which would definitely be a good way to do this.

As far as Aegir goes, that wouldn't be pure multi-tenant.  It would be a hybrid or "isolated tenant" as the application layer would be shared, but each customer would have her own database.  I believe this to be a much better approach.

Just to state my bias, I'm an Aegir maintainer, and have been working on facilitating this solution.  See [Aegir Site Subscriptions](https://www.drupal.org/project/aegir_site_subscriptions) for details.

Does Drupal support Multitenancy?


How to build an url to access filtered view?

Question: From a first view I need to dynamically build an URL to add a link to another filtered view named gallery_details.
I created a tpl template for my view where I build the URL like this one:

http://www.example.org/?q=gallery-details&field_main_categorie_value=Anciens&field_categorie_value=dessin&page=2

where field_main_categorie and field_categorie are the two used filters.
When the two filters are "exposed" it works, but if I uncheck the exposed filters, this URL become invalid.
I don't want to let the user to directly select the filters on gallery_details, also a solution may be to hide the exposed filters in gallery_details view.
I guess that there is a better solution.
Comment: If the filter isn't exposed, you shouldn't be able to set it via the URL - that would be be a bug, because, well, the filter would be exposed when you'd specifically asked for it not to be. If you don't want the form as an entry point to the filter, the simplest solution might be to use CSS to hide it
Comment: `dynamically build an URL` is this url going to change? If yes, based on what?
Comment: @Clive use CSS to hide the form is what I would have to do if there is no other solution.
Comment: @No Sssweat, yes the URL is aimed to change according to the filter used by the view where the URL is build.
Answer: Have you tried using Contextual Filters in your view? It sounds like they do what you want.
Comment: Thanks Chris, it seems that's the solution. I did several tests without fully understand how filters are used. It seems that I can't use `field_category=Anciens` as in the classical filter
Comment: Ok, now it works. I switched from "filter criteria" to "Contextual Filters" using the same filter fields, and building the following URL: `http://www.example.org/?q=gallery-details/Anciens/dessin&page=2` where Anciens and dessin are the expected values for the two fields.


Read data using countries module in view

Question: I am using the countries module to add countries in my content type project.
I create a view with type = Default node index to display my content.
I added the Indexed Nœud: Countries (Countries)
But the data saved in my field_countries is not displaying yet it is displayed well in the details page (node project).
Any idea to display the countries data in my view?
Thank you
Comment: @a-sana I haven't tried this module, but on its [project page](https://www.drupal.org/project/countries) it says you need to add a **Relationship** `Field: Country (field-country)`. After that you can add a field showing countries, this field must use the Relationship you created in order to show the countries.
Comment: @prkos, thanks for response, I added the relationship but nothing was changed
Comment: @a-sana adding a Relationship only opens the possibility for that View to add more fields and filters, it doesn't happen automatically. After you add the Relationship, you also need to add a new Field called Countries. Did you do those 2 steps listed on the module project page?
Answer: While adding relationship with countries, the most important, Check the checkbox Require this relationship and then add Countries: Name as fields you want.
It works for me (see) and hope for you too


Is backupAgent attribute necessary for application element?

Question: The documentation for AndroidManifest.xml says: There is no default. The name must be specified. on this page: http://developer.android.com/guide/topics/manifest/application-element.html
But I have the code for a working sample project that does not include it.  What gives?
Answer: If you want use backup agent - you have to provide this attribute. Otherwise your application will work without backups.


Can $v$ be a linear combination of nonzero independent vectors it is orthogonal to?

Question: Let $u,v,w$ be nonzero vectors in $\mathbb{C}^{n} $ such that $ \langle w,u \rangle = \langle w,v \rangle = 0$. Suppose that $u,v$ are linearly independent.
Is it possible that $w \in span(u,v)$ ? Proof?
Comment: Hint: What is $\langle w, au+bv\rangle$?
Answer: Suppose $w \in \operatorname{span}{\{u,v\}}$. Then $w=au+bv$ for some scalars $a,b$. Then
$$ \langle w,w \rangle = \langle w, au+bv \rangle = a\langle w,u \rangle + b \langle w,v \rangle = 0, $$
so if $\langle \cdot,\cdot \rangle$ is a true inner product (i.e. nondegenerate), $w=0$.


Strongly convex function evaluated over a mean of n points

Question: Let f(x) be a Strongly-convex function under some m > 0.
Given two points x, y it is known that:
$$f(\frac{x + y}{2}) \leq \frac{f(x) + f(y)}{2} - \frac{1}{2^3} \cdot m \cdot ||x - y||^2$$
What is the exact formulation when looking at the mean of n points.
$$f( \frac{1}{n}\sum_{i=1}^{n} x_i) \leq \ \  ?$$
Comment: Whatever be $m>0$ this inequality is not true for a linear function which is convex, hence it will not hold either for a strictly convex function which is very close to a linear function.
Comment: Thanks you @Yves. I was mistaken and meant strongly-convex
Answer: The standard definition of strong convexity with a constant $m>0$ would read as follows: for $t \in [0,1]$,
                  $$ f(tx+(1-t)y) \leq t f(x) + (1-t) f(y) - mt(1-t) \left \| x-y  \right \|^2.$$
Now, there is a famous theorem that says that a function $f$ is strongly convex with constant $m>0$ if and only if the function $$g(x)=f(x)-m\left \| x \right \|^2$$ is convex.
By Jensen's inequality for convex functions, $$ g\Bigg(\frac{\sum_{i=1}^{n} x_i }{n} \Bigg)  \leq \frac{1}{n} \sum_{i=1}^{n} g(x_i).$$ Equivalently,
$$ f\Bigg(\frac{\sum_{i=1}^{n} x_i }{n} \Bigg)   \leq m \left \| \frac{\sum_{i=1}^{n} x_i }{n} \right \|^2 + \frac{1}{n} \sum_{i=1}^{n} \Big(f(x_i)- m \left \| x_i\right \|^2\Big) \\ \leq \frac{m(1-n)}{n^2} \sum_{i=1}^{n} \left \| x_i\right \|^2 + \frac{1}{n} \sum_{i=1}^{n} f(x_i),$$
where the last step follows from the triangle inequality.
See for example

Nikodem, K. and Pales, Z., (2011). Characterizations of inner product spaces by strongly convex functions, Banach Journal of Mathematical Analysis, 5.1, 83-87.

for reference.
Comment: Seems that $\|x_i\|^2$ has to be replaced by $m \|x_i\|^2$ in the inequality.
Comment: @Yves Well spotted. Thank you!
Comment: By further using  $\|\sum x_i\|^2 \leq \sum \|x_i\|^2$ you can get a simpler inequality that can be useful.
Comment: Of course. I usually prefer to establish the strongest form of an inequality (given a set of arguments) and leave the consequences to the user's discretion.