text:
Q: GWT: Remote Logging and deobfuscating the stack trace with the StackTraceDeobfuscator I have an issue where I am using remote logging and my stack trace is obfuscated.  I have done quite a bit of research on this, and this blog was probably the most helpful reference I found. However, looking at tip 5 and 6 from the blog, I get the impression that the StackTraceDeobfuscator can be used without adding the following to my GWT module
<set-property name="compiler.stackMode" value="emulated" />
<set-configuration-property name="compiler.emulatedStack.recordLineNumbers"
value="true" />

I would prefer to NOT set the compiler.stackMode property and increase the size of my javascript bundle, but I am starting to doubt it's possible.  Is the above property in fact a requirement for deobfuscating my client stack traces?  Are there any alternatives?  I want to avoid making a change that can impact the performance or security of my application.
Thanks!

A: My initial means of providing the deobfuscated stacktrace involved reluctantly setting the properties that I mentioned in my description.
<set-property name="compiler.stackMode" value="emulated" />
<set-configuration-property name="compiler.emulatedStack.recordLineNumbers"
value="true" />

However, these new compile instructions did increase the size of my Javascript, and cause performance issues.  When using Internet Explorer 8, which some of our customers still use, there were a couple of things you could do on the website that would result in a "long running script" popup.
An important detail that I failed to mention in the description is that this issue surfaced during a GWT upgrade.
Previously, we were using com.google.gwt.logging.server.StackTraceDeobfuscator in a child class of GWT's RemoteServiceServlet.  That Deobfuscator is now deprecated and we moved to com.google.gwt.core.server.StackTradeDeobfuscator.  It turns out that the issue noted was tied to the symbol maps directory path that was used to attain the StackTraceDeobfuscator from the new static factory methods.  Once that was fixed, I was able to remove both the compiler.stackMode and the compiler.emulatedStack.recordLineNumbers properties, while still receiving a deobfuscated stacktrace from the client.


text:
Q: how to create multidimensional array in javascript In my project i am using highcart for that i should give the input in below format.
Here is my sample data:
[{"A",23},{"B",24},{"C",25},{"D",26},{"E",27}]

I have to convert the above json array to below format.
data=[["A",23],["B",24],["C",25],["D",26],["E",27]]

How to iterate my sample data and convert the above format.
Any help will be greatly appreciated!!!

A: [{"A",23},{"B",24},{"C",25},{"D",26},{"E",27}] is wrong,
it should be like [{"A":23},{"B":24},{"C":25},{"D":26},{"E":27}];

var data = [{"A":23},{"B":24},{"C":25},{"D":26},{"E":27}];
var newData = [];
data.forEach(function(val,index){
    var keys = Object.keys(val);
    keys.push(val[keys]);
    newData.push(keys);

});
alert(JSON.stringify(newData));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does the Newton-Raphson method not converge for some functions? $f(x)=2x^2-x^3-2$. This is a cubic type graph as shown.  The real root of this graph is $(-0.839,0)$.
So, the question is to use Newton's approximation method twice to approximate a solution to this $f(x)$.
I use an initial starting value of $x_0=1$.
My first approximation is $x_1=2$, and my second one is $x_2=1.5$.
I seem to not move any closer to the real solution as I keep iterating through the method.
Am I misunderstanding how to use this approximation?  Is the issue that my first guess was too far from the actual solution?

A: There are several articles about the convergence of Newton's method. There is something called the Newton-Kantorovich theorem which gives rigour to the notion of convergence regions.. your starting point must be within the Fatou set which encloses the point of attraction of the dynamical system formed by the iterates of the Newton iteration.
On the Newton–Kantorovich hypothesis for solving equations
I used the Method here to explore the convergence regions for asserting convergence of Newton's method for the Gram points of the zeta function
Convergence of the Newton-Kantorovich Method for the Gram Points

A: In fact, you gave up too early ; The method eventually converges :
1   2.000000000000000000000000000
2   1.500000000000000000000000000
3   0.3333333333333333333333333333
4   2.148148148148148148148148148
5   1.637079608343976160068114091
6   0.9483928480399477528436835979
7   1.910874140183680201544963299
8   1.405089904362402921055022221
9   -1.324018083676046424512855515
10  -0.9614381794507316717924414480
11  -0.8500221808505758631523579893
12  -0.8393807176849843501240483025
13  -0.8392867625049899194321196645
14  -0.8392867552141611764525252322
15  -0.8392867552141611325518525647
16  -0.8392867552141611325518525647
17  -0.8392867552141611325518525647
18  -0.8392867552141611325518525647
19  -0.8392867552141611325518525647
20  -0.8392867552141611325518525647
?

A: Newton's method does not always converge. Its convergence theory is for "local" convergence which means you should start close to the root, where "close" is relative to the function you're dealing with. Far away from the root you can have highly nontrivial dynamics.
One qualitative property is that, in the 1D case, you should not have an extremum between the root you want and your initial guess. If you have an odd number of extrema in the way, then you will start going away from the root you want, as you see here. If you have an even number of extrema in the way, then you will start going the right way, but you may later find yourself in a spot with an odd number of extrema in the way, leading to problems later.
Of course you may eventually find an occasion where there are an even number of extrema in the way, and then you manage to skip over all of them and get to the right side. At that point things will usually work out (not always, though). In this problem with your initial guess, that eventually happens, because the system eventually finds its way just slightly to the right of the extremum on the right, which sends it far off to the left.

A: The other answers are great. I'd just like to add a concrete example of weird behavior of which the Ian's answer speaks.
Let's consider a function $f(x) = \operatorname{sgn} x \sqrt{|x|}$. According to the algorithm, we iterate
$$x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}.$$
Now for the derivative (if we're not doing the derivative at $x = 0$, the $\operatorname{sgn} x$ is just a constant, and $|x| = x \operatorname{sgn} x$):
$$f' = [\operatorname{sgn} x \sqrt{x \operatorname{sgn} x}]' = \operatorname{sgn} x \frac{1}{2\sqrt{x \operatorname{sgn} x}} \operatorname{sgn} x = \frac{1}{2\sqrt{|x|}}.$$
Plugging in:
$$x_{n+1} = x_n - \frac{\operatorname{sgn} x \sqrt{|x|}}{1/(2\sqrt{|x|})} = x_n - 2 \operatorname{sgn} x \left(\sqrt{|x|}\right)^2 =\\
=x_n - 2\operatorname{sgn} x |x| = x_n - 2 x_n = - x_n.$$
So if we start iterating in $x = a$ (where $a \not = 0$), we get the sequence $a, -a, a, -a, \ldots$ and the method loops forever between those two points, never getting to the root $x = 0$!
Edit: Here's a gnuplotted image:

(In each iteration, we make a tangent in the current point (the blue dashed line) and the $x$ for which the tangent crosses 0 is taken to be the next approximation (so we go along the magenta line in order to get the starting point for the next iteration).)
By the way, have a look at this image from Wikipedia:

It shows the complex plane colored with 5 colors, each color corresponding to one root of the complex equation $z^5 = 1$. Each point then has the color corresponding to the root to which Newton's method converges, if we start from that point. The "flowers" are beautiful to behold but totally abhorrent from the numerical point of view.

A: Newton's method has no global convergence guarantee for arbitrary functions, as you just learned.
Now, people have posted examples of where Newton's method doesn't converge, but they're all rather "unusual" functions (some being very non-smooth), so it's natural to assume they're pathological and won't happen in practice.
Your example is one where Newton just takes more iterations than expected to converge, so it's not too bad.
But here is an example of a cubic polynomial for which Newton's method won't converge!
\begin{align*}
f(x) &= -0.74 + 0.765 x + 1.1 x^2 - 3.55 x^3  \\
x_0 &= 5/9
\end{align*}
Not only that, but it's in fact a stable oscillation—small perturbations won't change the behavior.

And for bonus points, you can generate as many of these as you want!
Just let the Newton step be $$g(x) = x - f'(x)^{-1} f(x)$$ and then you're just looking for a nontrivial solution to the equation $$x_0 = g^3(x_0) = g(g(g(x_0)))$$ where a solution $x_0$ would be trivial if $g(x_0) = 0$.
Notice the equation above is just another polynomial equation (although of a
 much higher order)—which means its solutions can be readily found numerically.
The only caveat is that these solutions might not necessarily be stable. I suspect you should be able to place a second-derivative condition to ensure stable solutions, but the exact equation is not obvious to me at the moment, so I'll leave it as an exercise for the reader. :-)
Mathematica code for the plot:
Manipulate[
  With[{f = Evaluate[Rationalize[d + c # + b #^2 + a #^3]] &}, Plot[
    f[x], {x, -0.61, 1},
    PlotStyle -> {Thickness[Tiny]},
    Prolog -> {Thickness[Tiny],
      Line[Flatten[Map[
     {{#, 0}, {#, f[#]}} &,
     NestList[Compile[t, t - f[t]/f'[t]], x0, n]], 1]]}]],
  {{a, -3.55}, -4, 4},
  {{b, 1.1}, -2, 2},
  {{c, 0.765}, -1, 1},
  {{d, -0.74}, -1, 1},
  {{x0, 5/9}, 0, 1},
  {{n, 100}, 0, 1000, 1}]

Update:
I wrote some code to purposefully find both stable and unstable iterations:
Newton[f_] := t \[Function] t - f[t]/f'[t];
NewtonPlot[f_, xmin_, xmax_, x0_, n_, args___] :=
  Plot[f[x], {x, xmin, xmax}, args,
   Prolog -> {Thickness[Tiny],
     Line[Flatten[Map[
        {{#, 0}, {#, f[#]}} &,
        NestList[Compile[t, Newton[f][t]], x0, n]], 1]]}];
FindOscillatoryNewtonSolutions[f_, n_, h_](* {Stables,Unstables} *):=
  With[{step = Newton[f]},
   With[{nstep = t \[Function] Nest[step, t, n]},
    GroupBy[
     Map[#[[1]][[2]] &,
      Solve[{nstep[t] == t, Abs[step[t] - t] >= h}, t, Reals]],
     t \[Function]
      With[{step1hp = nstep[t + h], step1hm = nstep[t - h]}, True \[And]
        Abs[N[step1hp - t]] >= Abs[N[nstep[step1hp] - t]] \[And]
        Abs[N[step1hm - t]] >= Abs[N[nstep[step1hm] - t]]]]]];
With[{z = 400, xmin = -1.1, xmax = +0.65, h = 10^-3},
 Manipulate[
  With[{f =
     t \[Function] Evaluate[Rationalize[d + c t + b t^2 + a t^3]],
    n = 3, m = 8},
   With[{solcategories = FindOscillatoryNewtonSolutions[f, n, h]},
    If[Length[solcategories] >= 2,
     Map[{Transpose@{N@SortBy[NestList[Newton[f], #1, n - 1], N]},
        NewtonPlot[f, xmin, xmax, N[#1 + dx], n*m,
         PlotStyle -> {Thickness[Tiny]},
         ImageSize -> Scaled[0.2],
         PerformanceGoal -> "Quality"]} &, {First@Lookup[solcategories, True],
       First@Lookup[solcategories, False]}],
     Throw["Did not manage to find both a stable and an unstable solution."]]]],
  {{dx, h}, -4 h, +4 h, h/4},
  {{a, -355}, -z, +z, 1}, {{b, 110}, -z, +z, 1},
  {{c, 77}, -z, +z, 1}, {{d, -74}, -z, +z, 1},
  SynchronousUpdating -> False]]

Notice, below, that the first point iterates stably, whereas the second one iterates unstably. (The iterations would diverge further, but I cut them off at some point.)

A: The Newton-Raphson method basically asks you to draw the tangent to the function at the point $x_0$, and $x_1$ is the point where that tangent hits the $x$-axis. This obviously works well if the function follows reasonably close to the tangent up to the point where $y = 0$, and not so well otherwise.
You can see that between $x = 0$ and $x \approx 1.4$ the tangent actually points in the wrong direction, away from the $0$. And where the tangent is parallel or almost to the $x$-axis, close to $x = 0$ and $x = 1.4$, following the tangent will get you far away from the zero.
For $x_0 < -0.346, \ x_1$ will be closer to the solution than $x_0$, and will be in the same range again, so the sequence will converge towards the solution. For $x_0 > 1.5, \ x_1$ will also be closer to the solution than $x_0$, but you need to get over the area from $-0.346 \to 1.5$.
And $\approx 1.081792$ there is a point where $3$ iterations get you back to the point where you started :-)

A: Newton-Raphson can behave badly even in seemingly easy situations. I am considering the use of N-R for minimization (rather than root finding, but the same applies). Even in the case of convex functions, N-R may not converge.
For example:
$$f(x)=\ln(e^x+e^{-x})$$
is $C^{\infty}$, strictly convex and admits a single (global) minimum in 0.

Yet, if we try to use N-R to find the minimum (i.e. the root of the derivative), the algorithm fails if started from a point $|x|>1.09$ (approx).
To see this, consider that $f'(x)=\tanh(x)$ and $f''(x)=\cosh^{-2}(x)$. Therefore, the N-R update rule maps the current $x$ to the new $x$ according to:
$$x \leftarrow x - \frac{f'(x)}{f''(x)} = x - \frac12 \sinh(2x)$$
Whenever $|\frac12 \sinh(2x)| > |2x|$, the new iterate will be bigger in modulus than the previous one, i.e. N-R will diverge away from the solution. This happens for $|x|>1.09$ (approx).

A: The relationship between starting point and eventual convergence point for Newton's method is complicated.  Consider this image (from Wolfram's MathWorld, Newton's Method):

showing the basis of attraction in the complex plane for $x^3 - 1$, $x^4 - 1$, ... $x^{11} - 1$.  Each colour corresponds to a root of the polynomial.  Each point is colored to match the root that Newton's method eventually takes that point to.
These basins are typically quite complicated, but if you look at what is going on in the complex plane, it can be a little clearer what's going on.  The real line runs horizontally, halfway down these plots.  If all you know is what is happening on the real axis, which is what you are seeing in your problem, it can be difficult to predict where a given point is going to end up.


text:
Q: Unable to get returned data in redirected page from previously sent form I need some help understanding the concepts needed to get my application to work. I am running two instances of localhost, one on 5000: and one on 8000:. One is a Flask instance (backend) and the other is a VUE instance (frontend). On my frontend, I have an onSubmit() function that does two things:

*

*Sends the form data to the Flask instance via axios.post

*Redirects the frontend to a result webpage.

On my backend, my Flask instance is supposed to return the information I need.
    if request.method == "GET":
        #Accessing page for first time
        response_object['msg'] = "Waiting for user input"
    elif request.method == "POST":
        #Form has been submitted
        data = request.get_json()
        user = parseFormData(data)
        itinerary = getResults(user)
        return itinerary

I am unsure / unable how to check if this is working. On the redirected page, I have the following method that is called when the page is created.
        getResponse(){
            const path = "http://127.0.0.1:5000";
            axios.post(path)
            .then((res) => {
                this.tmp = res.data;
                console.log(this.tmp);
            })
            .catch((err) => {
            console.error(err);
            });
        },

I am unable to get anything from this page actually. Any advice on where to go from here will be appreciated!
Edit:
The problem appears to lie in the sequence of events. On my Frontend, the form is submitted then the page is immediately redirected to a result page. While this is happening, my Backend receives the data, processes it and returns the information. That information appears to be lost. I believe this is sort of an example of async but I am unfamiliar with that concept as of now.


text:
Q: Heroku rake db:migrate fails - Missing tasks/rails I am just diving into Heroku and have hit a bit of a snag. Whenever I attempt to create my database I am getting the following error.
$ heroku rake db:migrate
 rake aborted!
 no such file to load -- tasks/rails
 /disk1/home/slugs/274236_54c3556_0822-55414a07-d565-459a-9412-67cc0e995790/mnt/Rakefile:10:in `require'
 (See full trace by running task with --trace)
 (in /disk1/home/slugs/274236_54c3556_0822-55414a07-d565-459a-9412-67cc0e995790/mnt)

I am a little confused about what, exactly, the error message is trying to tell me. I can verify that no file exists called 'rails' or 'rails.rb' in my lib/tasks folder. But just for sanity sake I also used scaffold to create a new RoR app in a clean dirty and verified it's not present their either.
This application was previously running under Rails 2 before I upgraded it to Rails 3. So there is a distinct chance I foo bared something up when I upgraded.
Also, in case it helps, here is the same command as above with tracing enabled:
$ heroku rake db:migrate --trace
  rake aborted!
  no such file to load -- tasks/rails
  /disk1/home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/Rakefile:10:in `require'
  /disk1/home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/Rakefile:10
  /home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/.bundle/gems/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2383:in `load'
  /home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/.bundle/gems/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2383:in `raw_load_rakefile'
  /home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/.bundle/gems/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2017:in `load_rakefile'
  /home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/.bundle/gems/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
  /home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/.bundle/gems/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2016:in `load_rakefile'
  /home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/.bundle/gems/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2000:in `run'
  /home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/.bundle/gems/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
  /home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/.bundle/gems/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
  /home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt/.bundle/gems/ruby/1.8/gems/rake-0.8.7/bin/rake:31
  /usr/ruby1.8.7/bin/rake:19:in `load'
  /usr/ruby1.8.7/bin/rake:19
  (in /disk1/home/slugs/274236_54c3556_0822-d0995817-4e57-4415-9e95-18e86d90348d/mnt)

Any clues as to which direction to investigate would be highly appreciated.
Thanks!
EDIT
I am starting to think that Heroku is a red herring. I can attempt to run db:migrate locally and it produces the same errors (obviously with local paths instead of Heroku's paths).
This is a basic application with no special gem dependencies. Here is my Gemfile:
source :gemcutter

gem 'mysql', '2.7'
gem 'rails', '3.0.1'
#gem 'rfacebook'
gem 'sqlite3-ruby', :require => 'sqlite3'

Here is also my database.yml:
# SQLite version 3.x
#   gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

A: Looks like maybe your Rakefile has some Rails 2 artifacts in it or something. I'd start there, maybe comparing the default Rails 2 and Rails 3 Rakefiles.


text:
Q: How to write proper loop in [C] I need to make 10 numbers display using "loops" like this:
1
2 3
4 5 6
7 8 9 10

I managed to make it happen with the code below. But I feel like there must be an easier way to do this. What if I needed to do the same pattern, but had 1000 numbers? That would be a lot of code.
#include <stdio.h>

int main(){

    int x;
    x=1;

    do {
        printf("%i \n", x);
        x++;
    }   while (x<=1);

        do {
            printf("%i ", x);
            x++;

    }   while (x<=3); {
        printf("\n");
    }

    do {
        printf("%i ", x);
        x++;

    }   while (x<=6); {
        printf("\n");
    }
    do {
        printf("%i ", x);
        x++;

    }   while (x<=10); {
        printf("\n");
    }

    return 0;
}

A: Writing a separate loop for each row is insane. When you're doing the same thing over and over with slight variation, that means you need another wrapping loop. This should really only require a pair of for loops:
unsigned maxval = ...;
for (unsigned rowlen = 1, val = 1; val <= maxval; ++rowlen) {
    for (unsigned item = 0; item < rowlen && val <= maxval; ++item) {
        printf("%u ", val++);
    }
    printf("\n");
}

A: You can do it with a single loop.
void print_tri(unsigned int max_val) {
    unsigned int row_lim = 1;
    unsigned int row_len = 0;

    for (unsigned int i = 1; i <= max_val; i++) {
        printf("%u ", i);
        if (++row_len == row_lim) {
            putchar('\n');
            row_lim++;
            row_len = 0;
        }
    }
}

A: If you're doing this to practice the do while use this piece of code if you arent though go with @ShadowRanger's answer since i feel that it is better for this case scenario
int x,y,counter, row;
row = 1;
counter = 0;
y=10;
x=1;

do {
    do {

    counter --;
    printf("%i ", x);
    x++;

    } while(counter > 0);
        printf("\n");
        row++;
        counter = row;

}   while (x<=y);

This adds 1 to the row variable each time the first do while loops to check in which row you're currently in then the counter is set to the row number that you're currently in to know how many numbers there will be in that row  the x variable is for the number that will be printed and the y variable is for how many numbers will be printed.

Note: this code will finish any row that has missing numbers Example:
  If you want to print 4 numbers this is what the code will print:
  1
  2 3
  4 5 6
  If you do NOT want this to happen change the first do while condition to
  this: while(counter > 0 && x<=y);

A: #include <stdio.h>

void main() {
    int row = 1;
    int column = 1;

    for (int i = 1; i <= 10; i++) {
        printf("%d", i);

        if (column == row) {
            printf("\n");
            row++;
            column = 1;
        }
        else {
            printf(" ");
            column++;
        }
    }
}

A: There are a number of ways to approach the logic, all are fine. Here is was that specifies a b begin variable to control the spacing logic (none on the first, a single space before for the remainder in the row) and provides two format strings (fmt1 and fmt2) to accommodate. The code increment a c - count of values to print per row until it reaches n - the number of counts per row.
Take a look at all answers and let me know if you have any questions:
#include <stdio.h>

int main (void) {

    /* i, b - begin, c - count, n - num per row */
    int i, b = 1, c = 0, n = 1;
    char *fmt1 = "%d", *fmt2 = " %d";

    for (i = 1; i < 11; i++) {
        printf (i == b ? fmt1 : fmt2, i);
        c++;
        if (c == n) {
            b = i + 1, c = 0, n++;
            putchar ('\n');
        }
    }

    return 0;
}

Example Use/Output
$ ./bin/looppyrimid
1
2 3
4 5 6
7 8 9 10

A: Thanks to all of you.The answer i was looking for is the answer that Marcel Jacques Machado and Ivan posted.I am just a beginner.And the exercise was to practice nested loops. The other post were helpful as well.


text:
Q: Using cross-sectional data for OLS/logit models (Stata) I have a cross-sectional dataset with the data example below, where the variable (id) refers to each individual in the df and rows represent the different number of Reddit posts written by each username, which vary across individuals.
My goal is to use OLS regression to predict average sentiment, based on individual-level covariates which are all measured at the username-level. For instance, the indicator "collective_action_prop" counts the proportion of mentions across all posts for a given username.
Currently, I ran the OLS model as follows:
regress avg_sentiment avg_response economic_demand_prop

However, I am not sure if I am correctly running the OLS regression at the username-level with the current data structure where each row represents a Reddit post but the variable id refers to usernames:

* Example generated by -dataex-. For more info, type help dataex
clear
input float id double float double()
 1                 -1         1                  0                 1
 2                 -1         0                  0                 1
 3                  0         0                  0                 0
 4                  0         .                  0                 0
 4                  0         .                  0                 0
 5                  1         6                  0                 0
----

A: If your average sentiment is bounded between (0,1) then OLS would not be right since it assumes that the outcome variable is continuous (-Inf,Inf). You need to re-conceptualize your problem via transformation of the outcome variable or a beta regression


text:
Q: MongoDB:How to call an external function you load with load funcion? I created a simple java script with a function.
I'm named Create(X) that execute db.mycollect.insert
x times inside in a for loop.
When i executed load function on mongo shell it runs correct.
Then when i execute Create(10) for example.
It doesn't create the 10 new documents.
My steps are:

*

*I create a simple script,

like this:
function Create(x)
{
    db.runCommand("use mycollect");
    for(i=i;i<x;i++)
    {
         db.departaments.insert([{"id":i,"name":"IT","acces":"T"}])
    }
}

*

*I ran load("simple.js").It returns true

*And finally i ran Create(10). It seems corrects

*But when i ran db.departments.find().The collection is void.

If the response could be in simple english or spanish i'll apreccite it.
<--Solution-->

The answer was on the script.
It was an error as user jao said.
Thanks for all answers.

A: You need to use db.getSiblingDB('<db>') to switch to a database.
function Create(x)
{
    db = db.getSiblingDB('mycollect');
    for(var i=0;i<x;i++)
    {
         db.departaments.insert([{"id":i,"name":"IT","acces":"T"}])
    }
}


text:
Q: Comparing two lists keeping duplicates but removing same items in indexed positions in Python I have two lists:
List1 = ['One', 'Two', 'Three', 'Five', 'Seven', 'Ten', ' Two', 'One']
List2 = ['Nine', 'Two', 'Seven', 'Five' , 'Five', 'Three',  'One', 'One']

The lists are of the same size.
What I want is, to match list1 with list2 by indexes and remove the matching items in list2 if the corresponding indexed item is the same. Otherwise it shouldn't remove the items. Duplicates can exist in non indexed positions in the Newlist2.
This is what I expect:
List1:#Same as the previous

NewList2 = ['Nine', 'Seven', 'Five', 'Three', 'One']

A: NewList2 = [ y for (x, y) in zip(List1, List2) if x != y ]

A: using list comprehension and zip:
list1 = ['One', 'Two', 'Three', 'Five', 'Seven', 'Ten', ' Two', 'One']
list2 = ['Nine', 'Two', 'Seven', 'Five' , 'Five', 'Three',  'One', 'One']

new_list = [ele2 for ele1, ele2 in zip(list1, list2) if ele1 != ele2]
print(new_list)

output
['Nine', 'Seven', 'Five', 'Three', 'One']

A: You can do
ls1 = ['One', 'Two', 'Three', 'Five', 'Seven', 'Ten', ' Two', 'One']
ls2 = ['Nine', 'Two', 'Seven', 'Five' , 'Five', 'Three',  'One', 'One']
new_list = [v for i , v in enumerate(ls2) if v != ls1[i]]

Output
['Nine', 'Seven', 'Five', 'Three', 'One']


text:
Q: Error in Simple User Define function related to data conversion in R The purpose of this very simple function is just to transform a date column to a date variable and a numeric time (hourly) column to a factor variable, which will be used with plyr later in the code.
I can get this code to run successfully in the command line, but when I attempt to run it in the function I get an error.
 # setting up some fake data
    set.seed(31)
    foo <- function(myHour, myDate){
    rlnorm(1, meanlog=0,sdlog=1)*(myHour) + (150*myDate)
     }
    Hour <- 1:24
    Day <-1:1080
    dates <-seq(as.Date("2010-01-01"), by = "day", length.out= 1080)
    myData <- expand.grid( Day, Hour)
    names(myData) <- c("Date","Hour")

    myData$Adspend <- apply(myData, 1, function(x) foo(x[2], x[1]))
    myData$Date <-dates

    myData$Demand <-(rnorm(1,mean = 0, sd=1)+.75*myData$Adspend)
    #############################################################

    myData

# Function Creation
    AddCal <-function(DF,Date,Time) {

    DF$Date<-as.Date(DF$Date, format="%m/%d/%Y")#Change Date variable into a date type

    DF$Time<-factor(DF$Time,levels=`c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24))

    }
#Test Function
    Bob<-AddCal(myData,Date,Hour)
#Error I receive
    Error in `$<-.data.frame`(`*tmp*`, "Time", value = integer(0)) :
    replacement has 0 rows, data has 25920

I spent about 2 hours searching for answers and trying different things. Because I can run the individual lines of code at the command line and get the desired result, I am assuming this is an advanced coding problem beyond my novice capabilities.

A: In your function, replace all instances DF$Time  with DF[[Time]]  same for DF$Date.
Also see the two comments below from @Dwin & @mrip:

*

*Make sure to return a value

*Make sure to pass string arguments where strings are expected

What's going on:
When you use DF$Time, R is looking for a column named Time in DF.  It is not treating Time as the string variable that you expect.
DF[[Time]] on the other hand does treat Time as a variable.
The reason the error only refers to Time and not Date is because Date is both the name of your variable and the name of a column in DF.   (If in your function call you would have used something like AddCal(.. Date=Demand) or whatever other column name, you would not get back the results you would expect)
Side Note:
c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24)
is equivalent to
seq(24)  and to 1:24


text:
Q: QSlider in PySide6 Won't Emit a Signal So I've been trying to develop a video player with Qt's PySide 6 using VLC as a backend to render the video just for the fun of it. I've gotten the player and a QSlider to appear as a widget in the main window, but no matter what I try with the slider it just doesn't seem to want to connect a signal to a function within the same class. I've even had the function empty except for a print function, so nothing should really be impeding the script from running unless I'm missing something. So I'm not really sure what I'm getting wrong here.
import sys, vlc
from PySide6.QtCore import QSize, Qt
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QMainWindow, QFrame, QSlider, QVBoxLayout
from PySide6.QtGui import QPalette, QColor

class Player(QWidget):
    def __init__(self):
        super(Player, self).__init__()
        self.instance = vlc.Instance()
        self.player = self.instance.media_player_new()
        self.media = self.instance.media_new("Untitled Project.webm")
        self.create_ui()
        self.player.set_media(self.media)
        self.player.play()
        self.player.set_position(0.2)

    def create_ui(self):
        self.widget = QWidget(self)
        self.videoframe = QFrame()
        if sys.platform.startswith("linux"):
            self.player.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32":
            self.player.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin":
            self.player.set_nsobject(self.videoframe.winId())
        self.palette = self.videoframe.palette()
        self.palette.setColor(QPalette.Window, QColor(0,0,0))

        self.positionslider = QSlider(Qt.Horizontal)
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderPressed.connect(self.slider_position)
        self.vboxlay = QVBoxLayout()
        self.vboxlay.addWidget(self.videoframe)
        self.vboxlay.addWidget(self.positionslider)
        self.widget.setLayout(self.vboxlay)
        self.positionslider.sliderMoved.connect(self.slider_position)
    def slider_position(self):
        print("Slider moved")
        pos = self.positionslider.value()
        self.player.set_position(pos / 1000)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Test")
        video = Player()
        self.setCentralWidget(video.widget)
        self.resize(QSize(640, 430))

if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

A: So the issue, pointed out to me by musicamante, was that I actually had the widget I was going to embed, also be a widget within itself. This led to an odd miscommunication within PySide (or so I believe) that led to having the signals not connect. Thank you again, musicamante, and I'll post the updated code below so that others can see the fix to my mistake.
import sys, vlc
from PySide6.QtCore import QSize, Qt
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QMainWindow, QFrame, QSlider, QVBoxLayout
from PySide6.QtGui import QPalette, QColor

class Player(QWidget):
    def __init__(self):
        super(Player, self).__init__()
        self.instance = vlc.Instance()
        self.player = self.instance.media_player_new()
        self.media = self.instance.media_new("Untitled Project.webm")
        self.create_ui()
        self.player.set_media(self.media)
        self.player.play()
        self.player.set_position(0.2)

    def create_ui(self):
        self.videoframe = QFrame()
        if sys.platform.startswith("linux"):
            self.player.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32":
            self.player.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin":
            self.player.set_nsobject(self.videoframe.winId())
        self.palette = self.videoframe.palette()
        self.palette.setColor(QPalette.Window, QColor(0,0,0))

        self.positionslider = QSlider(Qt.Horizontal)
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderPressed.connect(self.slider_position)
        self.vboxlay = QVBoxLayout()
        self.vboxlay.addWidget(self.videoframe)
        self.vboxlay.addWidget(self.positionslider)
        self.setLayout(self.vboxlay)
        self.positionslider.sliderMoved.connect(self.slider_position)
    def slider_position(self):
        print("Slider moved")
        pos = self.positionslider.value()
        self.player.set_position(pos / 1000)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Test")
        self.video = Player()
        self.setCentralWidget(self.video)
        self.resize(QSize(640, 430))

if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec())


text:
Q: What HTML element does jQuery $(document) correspond to? I thought is was the <HTML> tag but that doesn't seem to be correct. Am I missing something?
If so, is there any reason I shouldn't give the <HTML>/$(document) an id or other attributes which I could manipulate using jQuery/Javascript?

A: The document is a browser object that is the entry point for HTML content, accessing the URL, and other functionality. It contains the DOM tree, which in turn contains your HTML elements.
https://developer.mozilla.org/en-US/docs/DOM/document

A: The document variable refers to a memory object in JavaScript that does not correspond to anything in the HTML or the DOM tree.  It is, instead, the object that contains the DOM tree.  It is, in turn, contained by the Window object, which is the global object in browser-based Javascript.
The <html> element, on the other hand, is part of the DOM tree.  So you can get it the same way you can get any other element, with e.g. document.getElementsByTagName('html')[0].  But since it's the root of the DOM tree, that's kind of silly; you can access it directly as document.documentElement.  That works for the root of any DOM document, including XML (perhaps returned by an Ajax call).  In the usual case of an HTML document, you would probably just use document.html.  Or the jQuery equivalent.


text:
Q: Angular 2 - Call a function that exists outside of the current class I want to call a function that exists in HomePage class which is outside of the (class Popover) that I want to use the function on, I've already done some research, and I guess that I need to do something like dependency injection, I've tried to follow some tutorials but I was not lucky enough to solve the issue.
Popover class:
    @Component({
      template: `
        <div>
               <button ion-item *ngFor="let city of cities" (click)="switchToThisCity(city.cityName);close();">{{city.cityName | uppercase}}</button>
        </div>
      `
    })

        class MyPopover{
    static get parameters(){
      return [[Http], [ViewController]];
    }
     constructor(http, viewCtrl) {
      this.http    = http;
      this.viewCtrl = viewCtrl;
      //Async Call
      var getCities = new URLSearchParams();
      this.http.get('https://restApi.com/class/outlet', {headers: ParseHeaders}).subscribe(data => {
      this.cities = data.json().results;
      });
      ///
    }
     close() {
      this.viewCtrl.dismiss();
    }
    switchToThisCity(currentCity){
      //I WANT TO CALL THIS FUNCTION WHICH EXISTS ON HomePage CLASS
      return getQueries(currentCity);
    }
  }

HomePage Class:
  @Component({
    templateUrl: 'build/pages/home/home.html',
  })

        export class HomePage {
  static get parameters(){
      return [[NavController],[Http], [NavParams]];
    }

     // this.cartLength = this.cart.items.length;
    constructor() {}

   //I NEED TO USE THIS IN THE POPOVER CLASS

    getQueries(city){
    var cities = new URLSearchParams();
    cities.set('cityName', city);
   this.http.get('https://restApi.com/classes/citiesList', { search :   dishesParams, headers: ParseHeaders}).subscribe(data => {
   this.getCities = data.json().results;
   });
    }
 }

A: I would extract the getQueries method into a service:
@Injectable()
export class QueryService {

  constructor(http) {
    this.http = http;
  }

  static get parameters(){
    return [[Http]];
  }
}

and inject it into both components:
@Component({
  templateUrl: 'build/pages/home/home.html',
  providers: [ QueryService ]
})

export class HomePage {
  static get parameters(){
    return [[NavController],[NavParams], [QueryService];
  }

  constructor(nav, params, service) {
    this.service = service;
  }

  getQueries(city){
    this.service.getQueries(city)...
  }
}

and the same in the MyPopover class.

A: Create a Service class
cities.service
@Injectable()
export class CitiesService {
  getQueries(city) {
    var cities = new URLSearchParams();
    cities.set('cityName', city);
    return this.http.get('https://restApi.com/classes/citiesList', {
      search: dishesParams,
      headers: ParseHeaders
    }) // here we return an observable so we can subscribe to it in our class
  }

and in Popover: (Same with homepage class)
export class MyPopover{
  constructor(private citiesService:CitiesService) {
  }

  // and this is how you use the function
  this.citiesService.getQueries().subscribe(data => {
   this.getCities = data.json().results;
   });
 }

UPDATE : have a look at this article: http://nicholasjohnson.com/blog/how-to-do-everything-in-angular2-using-es6/

First up, anything is injectable in Angular, so PetService can be just a newable function.
The Angular DI mechanism will automatically use it to create a
  singleton that is local to the correct branch of the injector tree. If
  you only have a root injector (made automatically by Angular 2 on
  bootstrap), this will be a global singleton, just like Angular

the principle here is to create a service that handles the request and inject it, return an observable object and subscribe, then you can do whatever you want with the response...


text:
Q: Remember Me with Spring Security 3.1.3 - deprecated default constructors I'm doing a login with Spring Security 3.1 but I get a warning to deprecated and I could not get erased, it seems that this configuration is for version 3.0
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                    http://www.springframework.org/schema/security
                    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/pages/admin/**" access="hasRole('ROLE_ADMIN')" />
        <intercept-url pattern="/**" access="permitAll"/>
        <form-login login-page="/pages/login.jsf"/>
        <remember-me key="jsfspring-sec" services-ref="rememberMeServices"/>
        <logout
            invalidate-session="true"
            delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"
            logout-success-url="/pages/login.jsf"/>
    </http>

    <authentication-manager alias="authenticationManager">
        <authentication-provider ref="rememberMeAuthenticationProvider">
        </authentication-provider>
        <authentication-provider>
            <user-service id="userDetailsService">
                <user authorities="ROLE_ADMIN" name="admin" password="admin" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="rememberMeServices"
        class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
        <beans:property  name="key" value="jsfspring-sec" />
        <beans:property  name="userDetailsService" ref="userDetailsService" />
        <beans:property  name="alwaysRemember" value="true" />
        <beans:property  name="tokenValiditySeconds" value="60" />
    </beans:bean>

    <beans:bean id="rememberMeAuthenticationProvider"
        class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
        <beans:property name="key" value="jsfspring-sec"/>
    </beans:bean>

    <beans:bean id="rememberMeFilter"
        class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
        <beans:property name="rememberMeServices" ref="rememberMeServices"/>
        <beans:property name="authenticationManager" ref="authenticationManager" />
    </beans:bean>

</beans:beans>

I could not find how to do it with Spring 3.1. Can someone help me? The last three beans are deprecated, I would appreciate help. Here is the url of the repository in GitHub: https://github.com/wmanriques/spring_template

A: Default constructors are deprecated as Spring Security has moved to constructor injection in several classes lately.
/**
* @deprecated Use constructor injection
*/

Now required components need to be injected with constructor-arg:
<beans:bean id="rememberMeServices"
            class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
    //First two with constructor - required elements
    <beans:constructor-arg value="jsfspring-sec"/>
    <beans:constructor-arg ref="userDetailsService"/>

    //Last two with properties
    <beans:property name="alwaysRemember" value="true"/>
    <beans:property name="tokenValiditySeconds" value="60" />
</beans:bean>

Same with next 2 beans:
<beans:bean id="rememberMeAuthenticationProvider"
            class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
    <beans:constructor-arg value="jsfspring-sec"/>
</beans:bean>

<beans:bean id="rememberMeFilter"
            class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
    <beans:constructor-arg ref="authenticationManager"/>
    <beans:constructor-arg ref="rememberMeServices"/>
</beans:bean>


text:
Q: Enable VMWare web client? I have a dedicated server that was upgraded from VMWare Exsi 5.5 to VMWare 6 recently. I used to use the desktop application to control remotely my dedicated server however I kept get a warning since the upgrade that any VM configuration above VMWare V8 will have to use the Web Client to configure in order to be able to configure all aspects of the VM.
However I do not think I actually have web client installed on the machine, when I go to https://MY_VM_IP all I see is a link to download the installer.
How do I enable the web client? If it is enabled how do I access it? Is it via a specific port number?


text:
Q: localhost for fluentd-address is not working when fluentd container created I'm trying to connect my custom web server to fluentd on Docker.
My docker-compose.yml is like below.
version: "2"
services:
  web:
    build:
      context: ..
      dockerfile: ./DockerTest/Dockerfile
    container_name: web
    depends_on: [ fluentd ]
    networks:
      test_net:
       ipv4_address: 172.20.10.1
    ports:
      - "8080:80"
    links:
      - fluentd
    logging:
      driver: fluentd
      options:
        fluentd-address: localhost:24224
        tag: "docker.{{.ID}}"
  fluentd:
    build:
      context: ./fluentd
      dockerfile: Dockerfile
    container_name: fluentd
    volumes:
      - ./fluentd/conf:/fluentd/etc
    networks:
      test_net:
        ipv4_address: 172.20.10.2
    ports:
      - "24224:24224"
      - "24224:24224/udp"
networks:
  test_net:
    ipam:
      config:
        - subnet: 172.20.0.0/16

When I run this first, so if fluentd container is newly created, it occurs an error: Error response from daemon: failed to initialize logging driver: dial tcp [::1]:24224: connect: connection refused. At this time, it works well if I set fluentd-address: 172.20.10.2:24224.
But when I run this again, so if remained fluentd container is changed into RUNNING status, it works well. At this time, it is not working with fluentd-address: 172.20.10.2:24224.
I wonder why fluentd address should be changed depending on container creation, and how can I solve this problem?


text:
Q: Rendering canvas "sub-elements" in React I am trying to set up a canvas render system for some React components (they also can render in SVG, depending on their properties). I haven't settled on how best to do this, but the approach I'm currently taking is to have a CanvasManager component, combined with canvasContents methods on the child components that take a context and draw their intended contents. This is set up like so:
export default class CanvasManager extends React.Component {
  constructor(...args) {
    super(...args);

    this.childElements = [];
    this.canvasRender = this.canvasRender.bind(this);
  }

  componentDidMount(...args) {
    super.componentDidMount && super.componentDidMount(...args);
    this.canvasRender();
  }

  componentDidUpdate(...args) {
    super.componentDidMount && super.componentDidMount(...args);
    this.canvasRender();
  }

  canvasRender() {
    const ctx = this.canvas.getContext('2d');
    const { width, height } = this.props;

    ctx.clearRect(0, 0, width, height);
    this.childElements.forEach((child) => {
      child.canvasContents(ctx);
    });
  }

  render() {
    const { width, height, positionStyle, children } = this.props;

    const canvasChildren = React.Children.map(
      children,
      (child) => {
        const props = extend({}, child.props, {
          ref: (el) => {
            if (el) { this.childElements.push(el); }
          },
        });
        return extend({}, child, { props });
      },
    );

    return (<div style={ positionStyle }>
      <canvas
        ref={ (canvas) => { this.canvas = canvas; } }
        height={ height }
        width={ width }
      />
      { canvasChildren }
    </div>);
  }
}

The idea here is that the CanvasManager will let me handle full redraws of the canvas as needed, so any time any of the children get new properties they can call forceRender on the CanvasManager and clear and redraw the entire canvas as desired.
However, the ref function on the children seems to never actually fire, and this.childElements is always an empty array. (For reasons I don't understand, it does sometimes fire with el=null, hence the if statement.) How can I get access to the canvasContents methods on my child elements in canvasRender?
(Alternatively, if there is a better and entirely different way of doing this, I'm very much open to ideas.)


text:
Q: MoxieManager mc_access file not overwriting config options I am using moxiemanager for some image work for a website I am working on and in my config.php I have read and write access for the filesystem set to false for security reasons. Then in any folder that needs read or write permission I want to use the mc_access file to set those permissions. So the settings look like so:
$moxieManagerConfig['filesystem.readable'] = false;
$moxieManagerConfig['filesystem.writable'] = false;

Then in the mc_access I have it set like so:
_filesystem.writable=true
_filesystem.readable=true

I have other settings in there that are pulled from the mc_config file (upload.maxsize), and I am following the format given by the docs at moxiemanager.com. In addition if I set the permissions in reverse (the config.php has them true and the mc_access has them false) the mc_access file configurations stick. But when it is set up as I have above the mc_access settings do not stick and the folders remain unwritable and unreadable.

A: This is actually a hard one, but as I can figure out setting filesystem.readable to false in the config.php will prevent reading anything in the filesystem, including those mc_access files. The solution is most lightly to do it in reverse as you mentioned, by setting filesystem.readable to true - and then use mc_access in your various sensitive folders to make them not readable. MoxieManager is poorly documented and tutorials are none-existent, so you need to try this out the hard way.

A: This was  bug in the moxie manager software. I contacted their support team and they patched the issue in November


text:
Q: mongoid embeds_many associated collection remain empty I have two models
class Supplier < User
  include Mongoid::Document
  embeds_many :images
  accepts_nested_attributes_for :images
end

class Image
 include Mongoid::Document
 embedded_in :supplier
end

When I save images in nested form it gets save embeded in supplier collection i.e
 s = Supplier.first
 s.images #some Image records

But the problem is image collection itself remains empty i.e
 Image.count # gives 0

A: The documents of your Image model are stored inside the document of your Supplier model. So basically there is no collection with name images created in mongo. Check that in your mongo console. You only will be having a suppliers collection and no images collection.
If you want to access Images directly without accessing a particular you can do this
Supplier.all.pluck(:images)
#It will give you an array of all images

Or implement has_many
class Supplier < User
  include Mongoid::Document
  has_many :images
  accepts_nested_attributes_for :images
end

class Image
  include Mongoid::Document
  belongs_to :supplier
end


text:
Q: Javascript result not as expectecd with css This code works perfectly as I expected but the problem is when I refresh the page the t_con stays in absolute which should be fixed and when I resize the window less than 980px it is in absolute like what I need and if I resize again more than 980px it goes fixed.
I need it to stay fixed from start. I don't know why it is in absolute at first.
HTML CODE

CSS CODE
#t_con {
    width: 100%;
    position: absolute;
    top: 0;
}
#t {
    margin: 0px auto 0 auto;
    background-color: #976398;
    width: 980px;
    height: 30px;
}

Javascript CODE
window.onresize = function(){
    var header = document.getElementById('t');
    var window_width = document.body.offsetWidth;
    if(window_width < 980) {
        header.style.position = "absolute";
    } else {
        header.style.position = "fixed";
    }
}

Can anyone tell what am I doing wrong in here? And I don't want to use jQuery for this. So please do not suggest it. The reason I don't like jQuery is it already takes 90kb plus the code we are trying to execute.

A: You're setting window.onresize twice so your first function will never be called.
Try:
window.onresize = function(){
    document.getElementById('t_con').style.position = window.outerWidth < 980 ? 'absolute' : 'fixed';
    document.getElementById('t').style.position = document.body.offsetWidth < 980 ? 'absolute' : 'fixed';
}


text:
Q: Origin and connotations of RBF (Resting Bitch Face) Well, I don't know how or why, but until a week ago I had never come across the initialism RBF. I read it in a comment that had a very nasty tone, like so many of the comments posted nowadays on social media, so I guessed it had to have a negative slant.

The target? A young North American woman currently working in television. For what it's worth, she's attractive-looking, slim, and appears to come from a good family.
Finding it impossible to work out the meaning of RBF on my own, I asked Google and found a Wikipedia page containing the following information.

Resting bitch face, also known as RBF or bitchy resting face, is a term for a facial expression (or lack thereof) which unintentionally appears angry, annoyed, irritated, or contemptuous.

The initialism  appears to be sexist, and  offensive because of the word bitch.  Which Merriam-Webster defines as

*a often offensive :  a lewd or immoral woman
b often offensive :  a malicious, spiteful, or overbearing woman —sometimes used as a generalized term of abuse

And,  as I discovered two years ago — to my chagrin — bitchy is an emotionally charged expression on EL&U, far more than I had anticipated, when I posted a question with that adjective in its title. In the end it was rewarded with 9 downvotes.
Although the terms bitch and bitchy are not compliments in the UK, they are (or were)  less loaded. Dog breeders, and dog lovers  use the term bitch for female dogs, as is only right and proper.  I doubt whether the following title, first printed in 1988, The Book of the Bitch: A Complete Guide to Understanding and Caring for Bitches, would be possible in the US.
Thanks to Breaking Bad, we (non-Americans) know that bitch can be directed at  both genders. But would an American English speaker describe Conan's relaxed face as being bitchy?

He might look sour, grumpy, tired, drawn, or depressed but a "bitch face"? I don't think so.
Origin
Grant Barrett, a New York Times journalist, said the concept of a person's sour expression by default existed at least ten years before Resting Bitch Face, Bitchy Resting Face, and Bitch Face came to light in 2013.
And an article on CNN reports,

RBF first gained attention when a meme took over the Internet in 2013. That, plus a viral mock-public service announcement on "Bitchy Resting Face" made the "condition" somewhat of a joke.

The YouTube video, Bitchy Resting Face, posted 22 May, 2013, is a parody of those TV commercials which talk about pseudo afflictions and disorders.
The Guardian, a British paper, dedicated an article to the neologism in July that year, stating

The real cause is that it wasn't coined until – amazingly – May of this year. Needless to say, it instantly grabbed the media's attention. Truly, a titbit with such potential for female anxiety and self-loathing is like an iron filing to the media's magnet.

Further on, the British journalist smugly added

The weirdest thing is the BRF does not actually exist: the video that coined the term was made by comedian Taylor Orci and is a joke, as some of you might have guessed from the very name BRF.[sic] Yet this has not stopped plastic surgeons eagerly offering cures for this non-existent problem.

However, digging around, I found a teen magazine online called xo Vain, and an article by Olga, dated April 10 2013, in which she wrote:

I've been afflicted with chronic bitchface for as long as I can remember. The first time a girl said to me "You know, I really don't like you, but now that we have to work on this project together, I'm having so much fun with you," was in the third grade. I was eight.
Bitchface starts early, y'all. Like really early.

On the very same day, a YouTube video by Madeline Mann,  entitled: "My Struggle With Resting B*tch Face", was posted. In the video she utters the initialism, RBF, and confesses earnestly to the camera

So, erm, this song is about, er... well, I've been told that I have an RBF, which is a 'resting bitch face'. And that pretty much means — like my friend once told me that he would never come up to me in a bar because I just look so freakin', like I would just—like, bite off his head.

Digging further, I discovered what might be the predecessor of RBF, the term chronic bitchface.  The British blogger/illustrator, Kristina, mentions  it in her post dated March 26th, 2011, two years before "resting bitch face" had became viral.

Just doing my bit to spread awareness for this common, but little understood condition. Thousands around the world are affected by chronic bitchface, with sufferers having to endure being told to "SMILE" and "cheer up" by well meaning, but irritating strangers. There is no known cure.

Questions

*

*In light of the comment posted by 'justposting' above, is RBF an emotionally charged term in the US? How offensive or derogatory is it?

*Has this initialism, or expression caught on in the UK? If not, is there an equivalent?

*When did RBF, Rest Bitch Face, or any of its variants first appear?
Research:
1. Resting bitch face (Wikipedia)
2. A Wordnado of Words in 2013 The New York Times
3. Resting bitch face' is real, scientists say CNN (February 4, 2016)
4. Non-derogatory word/phrase analog of "bi**** resting face" but for a young kid (EL&U)
5. Bitchy resting face: must it be taken so seriously? The Guardian
6. Does My Snobby Face Make Me Less Attractive?
7. My Struggle With Resting B*tch Face (YouTube)

A: The BRF video is my first exposure to this meme, but as an American and Texan I have encountered references to this phenomenon (if not the specific acronym) far earlier than the mentioned dates. In light of that, in my experience RBF is mentioned as a way of adding humor to an awkward situation of misunderstanding or in defense of a person seen as having a cold personality without the accuser having yet met that person. It is a description of a condition, not normally a personal attack. It is normally used as a way to defuse situations, and as such is not generally seen as offensive.
However, if someone in the conversation uses the phrase "Resting Bitch Face" with persons who are not familiar with the phrase it may then provoke offense by the listener for having uttered the word "bitch", and further misunderstanding may ensue. This is especially likely in cases where conversationalists happen to be from the southern United States, are especially religious, in an older demographic, or any combination of the previous.
To clarify earlier encounters: As a US Southerner I am accustomed to hearing the essence of the RBF spirit worded in a variety of colorful Southern expressions. For instance, when a woman here is told she would look prettier if she smiled, common responses might be (all most likely uttered while walking away):

*

*"Tell the Governor to buy me a horse. Tell me when it happens."

*"I bet you want banjos to whistle for you, too."

*"I bet you think the roosters talk to you in the morning."

*"You just make me tired all over."

*"I'm saving my muscles for a man I'd like to kiss."

*"Whoever told you you're God's gift (to women) was wrong."

*"Not if you were the [frog prince | King of England | richest man alive]."

Or the military version: "Duly noted."
Also of note are expressions used in defense of a friend's disheveled or unhappy appearance. These are used in defense of the friend, and meant to imply that despite appearances, the friend is in fact a good or nice person.

*

*"You just caught her on a bad day | after a rainstorm | when her makeup ran out."

*"She's busier than a cat covering crap on a marble floor."

*"The horse she rode in on was a mule." (implying that either the vehicle she drives is in poor repair or her husband is difficult to deal with)

I am told there are similar (more biting) versions used in the Northern United States.
Though (as stated) I am not British, I have not yet seen anyone from Britain any similar acronym or phrase in traditional or social. My roommate (also American) is a writer for a prominent David Tennant fan club and has not mentioned any such occurrence. Both myself and my roommate have heard such usage in Scotland and Ireland.
Regarding the first appearance, the first recorded instance appears to be a submission on the Urban Dictionary on August 18, 2009. The related KnowYourMeme site appears to still be researching the topic.


text:
Q: Funq: Register the same object multiple times and using an identifier (from session) to resolve them What I currently have:
I have a simple dictionary of type string, DbContext
I am registering my Dictionary like this
container.Register<IDictionary<string, DbContext>>(x => dbContexts).ReusedWithin(ReuseScope.Request);

and using the dictionary again by simply injecting it in my constructors. So I am always injecting the whole dictionary with every DbContext in it. Later I then get the right DbContext by using an identifier, stored in my usersession. So using a DbContext looks like this:
private readonly IDictionary<string, DbContext> _dbContexts;
public FooService(IDictionary<string, DbContext> dbContexts)
{
    _dbContexts = dbContexts;
}

public void Bar()
{
    var userSession = GetSession();

    var data = _dbContexts[userSession.TargetConnectionIdentifier].Table.ToList();
}

What I want
I want to inject only one DbContext into my classes. Using the same property from my session as an identifier. I have seen that Funq offers methods to register instances with a name (e.g. RegisterAs<>()). But I am not quite sure how to use them correctly.
private readonly DbContext _dbContext;

public FooService(DbContext dbContext)
{
    _dbContext = dbContext;
}

I want that Funq automatically resolves the right object for me, depending on what value a specific property from my session has.
If anybody knows an answer I would highly appreciate it.

A: The IOC doesn't have access to the runtime Request context so you couldn't do this within the IOC.
My approach would be to register a factory with the db contexts, e.g:
container.Register<IDbContexts>(c => new DbContexts(dbContexts));

Then you could have a base class that provides a helper to access the DbContext behind a helper, e.g:
public class ServiceBase : Service
{
    public IDbContexts DbContexts { get; set; }

    DbContext dbContext;
    public DbContext DbContext => dbContext ?? (dbContext = DbContexts.Get(GetSession()));
}

Or you could use Extension methods if you don't want a base class, e.g:
public static class MyServiceExtensions
{
    public static DbContext GetDbContext(this Service service)
    {
        var dbContexts = service.TryResolve<IDbContexts>();
        return dbContexts.Get(service.GetSession());
    }
}

Then lazily load it in your Service class like:
DbContext dbContext;
public DbContext DbContext => dbContext ?? (dbContext = this.GetDbContext());


text:
Q: How does a Spark task access HDFS? Suppose that

*

*input to a Spark application is a 1GB text file on HDFS,

*HDFS block size is 16MB,

*Spark cluster has 4 worker nodes.

In the first stage of the application, we read the file from HDFS by sc.textFile("hdfs://..."). Since the block size is 16MB, this stage will have 64 tasks (one task per partition/block). These tasks will be dispatched to the cluster nodes. My questions are:

*

*Does each individual task fetch its own block from HDFS, or does the driver fetch the data for all tasks before dispatching them, and then sends data to the nodes?

*If each task fetches its own block from HDFS by itself, does it ask HDFS for a specific block, or does it fetch the whole file and then processes its own block?

*Suppose that HDFS doesn't have a copy of the text file on one of the nodes, say node one. Does HDFS make a copy of the file on node one first time a task from node one asks for a block of the file? If not, does it mean that each time a task asks for a block of the file from node one, it has to wait for HDFS to fetch data from other nodes?

Thanks!

A: In general, Spark's access to HDFS is probably as efficient as you think it should be.  Spark uses Hadoop's FileSystem object to access data in HDFS.

Does each individual task fetch its own block from HDFS, or does the driver fetch the data for all tasks before dispatching them, and then sends data to the nodes?

Each task fetches its own block from HDFS.

If each task fetches its own block from HDFS by itself, does it ask HDFS for a specific block, or does it fetch the whole file and then processes its own block?

It pulls a specific block.  It does not scan the entire file to get to the block.

Suppose that HDFS doesn't have a copy of the text file on one of the nodes, say node one. Does HDFS make a copy of the file on node one first time a task from node one asks for a block of the file? If not, does it mean that each time a task asks for a block of the file from node one, it has to wait for HDFS to fetch data from other nodes?

Spark will attempt to assign tasks based on the location preferences of the partitions in the RDD.  In the case of a HadoopRDD (which you get from sc.textFile), the location preference for each partition is the set of datanodes that have the block local.  If a task is not able to be run local to the data, it will run on a separate node and the block will be streamed from a datanode that has the block to the task that is executing on the block.


text:
Q: How to specify arbitrary monomial ordering in Macaulay2? Suppose you are given an arbitrary order such as $w>x>y>z>a$ order. You can do renaming so that it becomes lex or similar errorsome renaming things to satisfy some of the more typical monomial orderings such as lex, glex and grevlex here. Is there any way to specify an arbitrary monomial ordering in Macaulay2?

A: You can use the Weights option to specify a given ordering:

i1 : R = QQ[w..z,a, MonomialOrder=>{Weights => {4,3,2,1,0}}];
i2 : toString (a+z+y+x+w)^2
o2  = w^2 + 2*w*x + x^2 + 2*w*y + 2*x*y + 2*w*z + y^2+2*x*z + 2*w*a +
  2*y*z + 2*x*a + z^2+2*y*a + 2*z*a + a^2

If you want to produce a more or less arbitrary ordering, you can use Weights together with random:

i1 : R = QQ[w..z,a, MonomialOrder=>{Weights => for i in 0..4 list
  random 20}];
i2 : (options R).MonomialOrder
o2 = {MonomialSize => 32           }
{Weights => {14, 15, 12, 9, 1}}
{GRevLex => {1, 1, 1, 1, 1}   }
{Position => Up               }
o2 : VerticalList
i3 : toString (a+z+y+x+w)^2
o3 =
  x^2+2*w*x+w^2+2*x*y+2*w*y+y^2+2*x*z+2*w*z+2*y*z+z^2+2*x*a+2*w*a+2*y*a+2*z*a+a^2


text:
Q: Chaging dynamically Reference.cs of WCF Service I am in the process of developing a WCF Service(WCFManager) which would send out request to other services and get response back. For this I developed a WCF service.
Trying to accomplish the following (Assuming that my service name is WCFManager)
What I did so far

*

*Added a service reference of Service X to WCFManager which created a reference.cs and a WCF Client.

*Using the WCF Client generated by adding service reference and sending the request to Service X by using the following code
WCFManagerClient client = new WCFManagerClient();
Response response = client.GetResponse(request);

What am I trying to accomplish

*

*I want to add few config settings in a App.Config file of Service X, Service Y, Service Z which I did.

*Reuse the same WCFManagerClient to send the request to Service Y or Service Z by reading the endpoint information from the config file. My assumption is that when I use the WCFManagerClient to send the request it uses the reference.cs created in the service reference of the WCFManager service.If my assumption is true can I change the reference.cs on the fly to include the Service Y binding information when I send the request to Service Y and same with the Service Z. This way I don't have to create a proxy for each Service.

*Is it possible to reuse the same reference.cs file generated but include the binding information on the fly from config file.
3.I have no control over the Service Y or Service Z but all I know is services Endpoint information and the method names and the schema of each service would be the same.

I am not sure if  this is possible in WCF if some one has gone through such design with WCF but any suggestions about my approach is apreciated.


text:
Q: Which software can I use for backups?
Possible Duplicate:
What is a simple home backup software which works with a variety of OSes?

I need software that will take incremental backups of a few folders on my drive and back them up to an external HDD.  I want to have a feature where I can 'mount' the backup and get files out of it should I need to. Acronis does this but unfotunately doesn't work properly on my setup... :-( Any ideas what I can use?

A: Use Genie Timeline Home. Its free edition is also available.
It does incremental backup very smoothly & features Time Machine of Mac OS X. Means, you can move back & forth in time to access your file system snapshots at that time. Its the true power of incremental backup (beyond storage saving etc).

A: Many external drives ship with software that does this type of backup. Western Digital and Maxtor on many.  I am sure others as well.  What make external drive do you have?  Check the vendor site.


text:
Q: Fighting client-side caching in Django I'm using the render_to_response shortcut and don't want to craft a specific Response object to add additional headers to prevent client-side caching.
I'd like to have a response that contains:

*

*Pragma: no-cache

*Cache-control : no-cache

*Cache-control: must-revalidate

And all the other nifty ways that browsers will hopefully interpret as directives to avoid caching.
Is there a no-cache middleware or something similar that can do the trick with minimal code intrusion?

A: Actually writing my own middleware was easy enough:
from django.http import HttpResponse

class NoCacheMiddleware(object):

    def process_response(self, request, response):

        response['Pragma'] = 'no-cache'
        response['Cache-Control'] = 'no-cache must-revalidate proxy-revalidate'

        return response

Still doesn't really behave like i wanted but so neither does the @never_cache decorator

A: Regarding the Google Chrome browser (Version 34.0.1847.116 m) and the other browsers, I found that only the @cache_control decorator is working. I use Django 1.6.2.
Use it like this:
@cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True)
def view(request):
    ...

A: Here is a rewrite of @Meilo's answer for Django 1.10+:
from django.utils.cache import add_never_cache_headers

class DisableClientCachingMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        add_never_cache_headers(response)
        return response

A: This approach (slight modification of L. De Leo's solution) with a custom middleware has worked well for me as a site wide solution:
from django.utils.cache import add_never_cache_headers

class DisableClientSideCachingMiddleware(object):
    def process_response(self, request, response):
        add_never_cache_headers(response)
        return response

This makes use of add_never_cache_headers.

If you want to combine this with UpdateCacheMiddleware and FetchFromCacheMiddleware, to enable server-side caching while disabling client-side caching, you need to add DisableClientSideCachingMiddleware before everything else, like this:
MIDDLEWARE_CLASSES = (
    'custom.middleware.DisableClientSideCachingMiddleware',
    'django.middleware.cache.UpdateCacheMiddleware',
    # ... all other middleware ...
    'django.middleware.cache.FetchFromCacheMiddleware',
)

A: To supplement existing answers. Here is a decorator that adds additional headers to disable caching:
from django.views.decorators.cache import patch_cache_control
from functools import wraps

def never_ever_cache(decorated_function):
    """Like Django @never_cache but sets more valid cache disabling headers.

    @never_cache only sets Cache-Control:max-age=0 which is not
    enough. For example, with max-axe=0 Firefox returns cached results
    of GET calls when it is restarted.
    """
    @wraps(decorated_function)
    def wrapper(*args, **kwargs):
        response = decorated_function(*args, **kwargs)
        patch_cache_control(
            response, no_cache=True, no_store=True, must_revalidate=True,
            max_age=0)
        return response
    return wrapper

And you can use it like:
class SomeView(View):
    @method_decorator(never_ever_cache)
    def get(self, request):
        return HttpResponse('Hello')

A: I was scratching my head when the three magic meta didn't work in Firefox and Safari.
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

Apparently it can happen because some browsers will ignore the client side meta, so it should be handled at server side.
I tried all the answers from this post for my class based views (django==1.11.6). But referring to answers from @Lorenzo and @Zags, I decided to write a middleware which I think is a simple one.
So adding to other good answers,
# middleware.py
class DisableBrowserCacheMiddleware(object):

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['Pragma'] = 'no-cache'
        response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        response['Expires'] = '0'
        return response

# settings.py
MIDDLEWARE = [
    'myapp.middleware.DisableBrowserCacheMiddleware',
    ...

A: You can achieve this using the cache_control decorator. Example from the documentation:
from django.views.decorators.cache import never_cache

@never_cache
def myview(request):
   # ...

A: For Django 4+:
from django.utils.cache import add_never_cache_headers

def disable_client_side_caching_middleware(get_response):
    def middleware(request):
        response = get_response(request)
        add_never_cache_headers(response)
        return response

    return middleware

MIDDLEWARE_CLASSES = (
    ...
    'my_app.middleware.disable_client_side_caching_middleware'
    ...
)


text:
Q: load array data mysql to ElasticSearch using logstash jdbc Hi i am new to ES and i m trying to load data from 'MYSQL' to 'Elasticsearch'
I am getting below error when trying to loadata in array format, any help
Here is mysql data, need array data for new & hex value columns
cid  color      new     hex      create            modified
1    100 euro   abcd   #86c67c  5/5/2016 15:48   5/13/2016 14:15
1    100 euro    1234   #fdf8ff  5/5/2016 15:48   5/13/2016 14:15

Here us the logstash config
input {
 jdbc {
   jdbc_driver_library => "/etc/logstash/mysql/mysql-connector-java-5.1.39-bin.jar"
   jdbc_driver_class => "com.mysql.jdbc.Driver"
   jdbc_connection_string => "jdbc:mysql://127.0.0.1:3306/test"
   jdbc_user => "root"
   jdbc_password => "*****"
   schedule => "* * * * *"

   statement => "select cid,color, new as 'cvalue.new',hexa_value as 'cvalue.hexa',created,modified from colors_hex_test order by cid"
   jdbc_paging_enabled => "true"
   jdbc_page_size => "50000"
}
}

output {
    elasticsearch {
        index => "colors_hexa"
        document_type => "colors"
        document_id => "%{cid}"
        hosts => "localhost:9200"

Need array data for cvalue (new, hexa) like
{
  "_index": "colors_hexa",
  "_type": "colors",
  "_id": "1",
  "_version": 218,
  "found": true,
  "_source": {
    "cid": 1,
    "color": "100 euro",
    "cvalue" : {
            "new": "1234",
            "hexa_value": "#fdf8ff",
        }
    "created": "2016-05-05T10:18:51.000Z",
    "modified": "2016-05-13T08:45:30.000Z",
    "@version": "1",
    "@timestamp": "2016-05-14T01:30:00.059Z"
  }
}

this is the error i m getting while running logstash
 "status"=>400, "error"=>{"type"=>"mapper_parsing_exception",
 "reason"=>"Field name [cvalue.hexa] cannot contain '.'"}}}, :level=>:warn}

A: You cant give a field name with .. But you can try to add:
filter {
  mutate {
    rename => { "new" => "[cvalue][new]" }
    rename => { "hexa" => "[cvalue][hexa]" }
  }
}


text:
Q: How to synchronize data between multiple Orions For example, I have built Orion and DB in AWS and GCP respectively and want to synchronize data between each other.
I registered a subscription to each Orion specifying "/v2/op/nority" of the other Orion, but when there is a communication failure, the failed subscription notification does not remain, so I could not synchronize even if the failure is resolved.
Is there any synchronization method that assumes a communication failure period due to failure of the respective service?


text:
Q: Generate random chars and integers in C++ How do I generate random chars and integers within a method so that the method can be called in main() and so that the method generates random chars and integers together. I do not want a method that genrates chars and another methods that generates integers.

A: You can write a method like (assuming you want only lower case English characters, you can extend it):
void generate(char& ranChar, int& ranNmber)
{
  //Generate a random number in the range 0-25 and add the ascii value 'a'
  ranChar = rand() % 26 + 'a';
  ranNumber = rand();
}

int main()
{
   //Seed the random number generator with the current time
   srand(time(NULL));
   char ch;
   int n= 0;
   generate(ch,n);
   return 0;
}

A: You could use boost::tuple, like this:
boost::tuple<int, char> gen () {
// srand() etc
return make_tuple(rand(), (rand() % ('z' - 'a' + 1)) + 'a');
}


text:
Q: Monotonicity of $\mathbf{P} ( \bar{X}_N > 0 )$ in $N$ Let $X$ be a real-valued random variable with positive expectation (wlog, $\mathbf{E}[X] = 1$, say).
For $N \in \mathbf{N}$, let $X_1, \cdots, X_N$ be independent, identically-distributed copies of $X$, and let $\bar{X}_N = \frac{1}{N} \sum_{i =1}^N X_i$ be their sample mean. Now, consider the quantity
$$p_N \triangleq \mathbf{P} ( \bar{X}_N > 0 ) \in [0, 1].$$
My question is: Is it known whether $p_N$ is increasing with $N$?
Intuitively, it seems like it ought to be (edit, added after answer: I meant to say `eventually' here). If it can be proved with some moment assumption on $X$, I would also be happy with that, though it would be nice to do so without this assumption. A counter-example would also be interesting.

A: The answer is, that $p_N$ is not necessarily increasing. Not that $\mathbb{P}(\bar X_N > 0) = \mathbb{P}(X_1 + \ldots + X_N > 0)$. Put $\mathbb{P}(X=1) = 0.99$ and $\mathbb{P}(X=-98) = 0.01$. Then $\mathbb{E}X_1 = 0.01$, but $p_2 < p_1$.


text:
Q: Change loop to write results in additional cells I have been using the following code for awhile but need some help in making one change. I've tried and tried but it won't work. If someone could kindly take a look, my research says I'm looking for a "change loop to write results to additional cells".  Please see my Excel image below.
Right now the code finds all matching number(s) entered in the A1 cell and posts them in the appropriate cells L1:l12. I need the code to also post the same information in only one of the following cells: C17, C18, F17, F18. Also, if the code could copy and paste the number in the cell below the matching number (from cell A1), see sample result below) into the cell to the left of the above change loop paste in the following cells: B17, B18, E17, E18.
Example with expected result as per the sample Excel image. Number 8 was entered in cell A1 and found 8 in cell A34. So 8-15 would be copied and pasted to L8 and C17. It would also copy the number 7 from cell A35 (the following number) to cell B17. The code would also do the same for cell F20 and E21. After all the coping and pasting all the cells B34, C34 and D34 need to be deleted and so would be blank. Same for F20, G20 and H20. I hope this is clear, if not please advise and I will clarify.
My working code is below and my attempt is below that code.

Working code:
Sub do_it()

    Dim n, sht As Worksheet, cell As Range, num, tmp, rngDest As Range

    Set sht = ActiveSheet

    n = sht.Range("A1")

    For Each cell In sht.Range("A20:A34,D20:D34,G20:G34").Cells

        tmp = cell.Offset(0, 1).Value

        If cell.Value = n And tmp Like "*#-#*" Then

            'get the first number
            num = CLng(Trim(Split(tmp, "-")(0)))
            Debug.Print "Found a positive result in " & cell.Address
 'find the next empty cell in the appropriate row
         Set rngDest = sht.Cells(num, sht.Columns.Count).End(xlToLeft).Offset(0, 1)
            'make sure not to add before col L
            If rngDest.Column < 12 Then Set rngDest = sht.Cells(num, 12)

            cell.Offset(0, 1).Copy rngDest

        End If
    Next

End Sub

My attempt:
Sub do_it()

    Dim n, sht As Worksheet, cell As Range, num, tmp, rngDest As Range

    Set sht = ActiveSheet

    n = sht.Range("A1")

    For Each cell In sht.Range("A20:A34,D20:D34,G20:G34").Cells

        tmp = cell.Offset(0, 1).Value

        If cell.Value = n And tmp Like "*#-#*" Then

            'get the first number
            num = CLng(Trim(Split(tmp, "-")(0)))
            Debug.Print "Found a positive result in " & cell.Address
 'find the next empty cell in the appropriate row
         Set rngDest = (" C17, C18, F17, F18')
             cell.Offset(0, 1).Copy rngDest

        End If
    Next

End Sub

A: It might not be pretty or scalable, but since I'm not sure exactly what you are trying to achieve in the long run, here is something that should work.
First of, the row For Each cell In sht.Range("A20:A34,D20:D34,G20:G34").Cells does not correspond with the cells used in your example, so I changed that to:
For Each cell In sht.Range("A20:A34,E20:E34,I20:I34").Cells

Then I Hijacked the tmp variable at the end, because it's not used anymore, and set it to find the last cell of the column where it found a match, like so:
Set tmp = sht.Cells(Cells(Rows.Count, cell.Column).End(xlUp).Row, cell.Column)

Then we need to specify the new boxes, and make sure we only fill each once.
You could do this by checking is the first one is empty, or with a counter.
Either way, it will only work properly as long as you find less than 4 matches.
End result was this, modify as needed;
Sub do_it()

Dim sht As Worksheet, n As String, cell, num, tmp, rngDest As Range, i As Integer
Set sht = ActiveSheet
n = sht.Range("A1").Value
i = 0
For Each cell In sht.Range("A20:A34,E20:E34,I20:I34").Cells
    tmp = cell.Offset(0, 1).Value
    If cell.Value = n And tmp Like "*#-#*" Then
       'get the first number
        num = CLng(Trim(Split(tmp, "-")(0)))
        'find the next empty cell in the appropriate row
        Set rngDest = sht.Cells(num, sht.Columns.Count).End(xlToLeft).Offset(0, 1)
        'make sure not to add before col L
        If rngDest.Column < 12 Then Set rngDest = sht.Cells(num, 12)
        cell.Offset(0, 1).Copy rngDest

' This is getting the next number in A/E/I----
        Set tmp = cell.Offset(1, 0)

' This is filling up B17 - F18 in order until filled
        If sht.Range("B17").Value = "" Then
            sht.Range("C17").Value = cell.Offset(0, 1).Value
            sht.Range("B17").Value = tmp.Value
        ElseIf sht.Range("B18").Value = "" Then
            sht.Range("C18").Value = cell.Offset(0, 1).Value
            sht.Range("B18").Value = tmp.Value
        ElseIf sht.Range("E17").Value = "" Then
            sht.Range("F17").Value = cell.Offset(0, 1).Value
            sht.Range("E17").Value = tmp.Value
        ElseIf sht.Range("E18").Value = "" Then
            sht.Range("F18").Value = cell.Offset(0, 1).Value
            sht.Range("E18").Value = tmp.Value
        End If
  '---- This clears the BCD/FGH/JKL columns after using the value ----
        'cell.Offset(0, 1).Resize(, 3).Value = ""

   End If
Next cell
End Sub


text:
Q: Can Maven ref a parent POM from a private s3 bucket? When using a private AWS S3 bucket as a Maven repo, there's plenty of working s3 wagon providers that work just fine for deploying and pulling dependencies using the s3://[bucket]/folder protocol.
However, when you try to do this with a parent POM reference, i.e.
  <parent>
    <groupId>com.my.company</groupId>
    <artifactId>my-parent-pom</artifactId>
    <version>1.0.0</version>
  </parent>

Which exists only in a private S3 Maven repo, it seems that Maven only checks the HTTP based defined repositories, and doesn't attempt to look in the S3 repo.
The S3 wagon in this project is defined as
<build>
<extensions>
  <extension>
    <groupId>org.springframework.build</groupId>
    <artifactId>aws-maven</artifactId>
    <version>5.0.0.RELEASE</version>
  </extension>
</extensions>
</build>

Which, again, works fine for normal dependencies, just not for a parent POM reference
Looking for some way to have a parent POM be properly resolved inside an S3 Maven repo

A: Per my comment on the other post in this thread: If you're using Maven 3.2.5 or later, you can specify the plugin as a JAR on the command line.
If you're using Maven 3.3.1 or later, create a .mvn/extensions.xml file in your project that defines the S3 wagon so that it's pre-loaded by the time the parent POM is being resolved.
See Maven's 3.3.1 release notes for details:
https://maven.apache.org/docs/3.3.1/release-notes.html

A: The answer is No.
The main issue with Maven and S3 repo is that Maven loads a parent POM before a S3 wagon.
Check here for details: http://www.sonatype.org/nexus/2015/03/03/why-s3-is-not-the-perfect-maven-repository/


text:
Q: How to reduce the load from Disk by improving my.ini settings for MySQL I have created a time tracking app which captures every minute activity of 400 people.
Means if no one query my database I still have 400 insert request to MySQL every minute.
Everything working fine till now but then I have to give the user a dashboard where they can see every entry of their tracked time.
Now I have 400 people querying my database, after launching query page the system becomes very slow, Disk usage go to 100% much time. I'm planning to deploy more apps on the server but before moving forward I want to solve this problem.
I'm thinking of changing my hard disk from HHD to SSD to increase read-write speed but wondering If there are any settings I can tweak in my default my.ini file to get better MySQL performance
Below is the my.ini file I have modified with the help of my-innodb-heavy-4G.ini my PC running MySQL 10.1.36-MariaDB,64bit, 3.60GHz, i7 with 8 GB RAM.
I just wanted to know if the below settings are correct or not. I don't want my server to crash and stop working. Please help me in addition or deletion of any setting line which can cause an issue.
[client]
# password       = your_password
port            = 3306
socket          = "E:/xampp2/mysql/mysql.sock"

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port= 3306
socket = "E:/xampp2/mysql/mysql.sock"
basedir = "E:/xampp2/mysql"
tmpdir = "E:/xampp2/tmp"
datadir = "E:/xampp2/mysql/data"
pid_file = "mysql.pid"
# enable-named-pipe
key_buffer_size = 32M
max_allowed_packet = 16M

#
back_log = 50
slow_query_log
long_query_time = 8

#
table_open_cache = 2048
binlog_cache_size = 5M
max_heap_table_size = 64M
join_buffer_size = 8M
tmp_table_size = 64M

sort_buffer_size = 8M
net_buffer_length = 8M
read_buffer_size = 8M
read_rnd_buffer_size = 32M
myisam_sort_buffer_size = 128M
bulk_insert_buffer_size = 64M
myisam_max_sort_file_size = 10G
myisam_repair_threads = 1
myisam_recover

#
thread_cache_size = 8M
query_cache_size = 64M
query_cache_limit = 2M
thread_concurrency = 8M
thread_stack = 240K

max_connections = 5000
log_error = "mysql_error.log"

plugin_dir = "E:/xampp2/mysql/lib/plugin/"

server-id   = 1

innodb_data_home_dir = "E:/xampp2/mysql/data"
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = "E:/xampp2/mysql/data"

innodb_buffer_pool_size = 2G
innodb_additional_mem_pool_size = 200M

innodb_log_file_size = 256M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 120
innodb_write_io_threads = 8
innodb_read_io_threads = 8
innodb_thread_concurrency = 16
innodb_log_files_in_group = 3
innodb_max_dirty_pages_pct = 90

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash

[myisamchk]
key_buffer_size = 512M
sort_buffer_size = 512M
read_buffer = 8M
write_buffer = 8M

[mysqlhotcopy]
interactive-timeout

A: Please Try this.
# Example MySQL config file for small systems. # # This is for a system with little memory (<= 64M) where MySQL is only used # from time to time and it's important that the mysqld daemon # doesn't use much resources. # # You can copy this file to # E:/xampp2/mysql/bin/my.cnf to set global options, # mysql-data-dir/my.cnf to set server-specific options (in this # installation this directory is E:/xampp2/mysql/data) or # ~/.my.cnf to set user-specific options. # # In this file, you can use all long options that a program supports. # If you want to know which options a program supports, run the program # with the "--help" option. # The following options will be passed to all MySQL clients [client] # password       = your_password port            = 3306 socket          = "E:/xampp2/mysql/mysql.sock" # Here follows entries for some specific programs # The MySQL server [mysqld] port= 3306 socket = "E:/xampp2/mysql/mysql.sock" basedir = "E:/xampp2/mysql" tmpdir = "E:/xampp2/tmp" datadir = "E:/xampp2/mysql/data" pid_file = "mysql.pid" # enable-named-pipe key_buffer_size = 32M max_allowed_packet = 16M # back_log = 50 slow_query_log long_query_time = 8 # table_open_cache = 2048 binlog_cache_size = 5M max_heap_table_size = 64M join_buffer_size = 8M tmp_table_size = 64M sort_buffer_size = 8M net_buffer_length = 8M read_buffer_size = 8M read_rnd_buffer_size = 32M myisam_sort_buffer_size = 128M bulk_insert_buffer_size = 64M myisam_max_sort_file_size = 10G myisam_repair_threads = 1 myisam_recover # thread_cache_size = 8M query_cache_size = 64M query_cache_limit = 2M thread_concurrency = 8M thread_stack = 240K max_connections = 5000 log_error = "mysql_error.log" # Change here for bind listening # bind-address="127.0.0.1" # bind-address = ::1          # for ipv6 # Where do all the plugins live plugin_dir = "E:/xampp2/mysql/lib/plugin/" # Don't listen on a TCP/IP port at all. This can be a security enhancement, # if all processes that need to connect to mysqld run on the same host. # All interaction with mysqld must be made via Unix sockets or named pipes. # Note that using this option without enabling named pipes on Windows # (via the "enable-named-pipe" option) will render mysqld useless! # # commented in by lampp security #skip-networking #skip-federated # Replication Master Server (default) # binary logging is required for replication # log-bin deactivated by default since XAMPP 1.4.11 #log-bin=mysql-bin # required unique id between 1 and 2^32 - 1 # defaults to 1 if master-host is not set # but will not function as a master if omitted server-id    = 1 # Replication Slave (comment out master section to use this) # # To configure this host as a replication slave, you can choose between # two methods : # # 1) Use the CHANGE MASTER TO command (fully described in our manual) - #    the syntax is: # #    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>, #    MASTER_USER=<user>, MASTER_PASSWORD=<password> ; # #    where you replace <host>, <user>, <password> by quoted strings and #    <port> by the master's port number (3306 by default). # #    Example: # #    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306, #    MASTER_USER='joe', MASTER_PASSWORD='secret'; # # OR # # 2) Set the variables below. However, in case you choose this method, then #    start replication for the first time (even unsuccessfully, for example #    if you mistyped the password in master-password and the slave fails to #    connect), the slave will create a master.info file, and any later #    change in this file to the variables' values below will be ignored and #    overridden by the content of the master.info file, unless you shutdown #    the slave server, delete master.info and restart the slaver server. #    For that reason, you may want to leave the lines below untouched #    (commented) and instead use CHANGE MASTER TO (see above) # # required unique id between 2 and 2^32 - 1 # (and different from the master) # defaults to 2 if master-host is set # but will not function as a slave if omitted #server-id       = 2 # # The replication master for this slave - required #master-host     =   <hostname> # # The username the slave will use for authentication when connecting # to the master - required #master-user     =   <username> # # The password the slave will authenticate with when connecting to # the master - required #master-password =   <password> # # The port the master is listening on. # optional - defaults to 3306 #master-port     =  <port> # # binary logging - not required for slaves, but recommended #log-bin=mysql-bin # Point the following paths to different dedicated disks #tmpdir = "E:/xampp2/tmp" #log-update = /path-to-dedicated-directory/hostname # Uncomment the following if you are using BDB tables #bdb_cache_size = 40M #bdb_max_lock = 10000 # Comment the following if you are using InnoDB tables #skip-innodb innodb_data_home_dir = "E:/xampp2/mysql/data" innodb_data_file_path = ibdata1:10M:autoextend innodb_log_group_home_dir = "E:/xampp2/mysql/data" #innodb_log_arch_dir = "E:/xampp2/mysql/data" ## You can set .._buffer_pool_size up to 50 - 80 % ## of RAM but beware of setting memory usage too high innodb_buffer_pool_size = 2G innodb_additional_mem_pool_size = 200M ## Set .._log_file_size to 25 % of buffer pool size innodb_log_file_size = 256M innodb_log_buffer_size = 8M innodb_flush_log_at_trx_commit = 1 innodb_lock_wait_timeout = 120 innodb_write_io_threads = 8 innodb_read_io_threads = 8 innodb_thread_concurrency = 16 innodb_log_files_in_group = 3 innodb_max_dirty_pages_pct = 90 ## UTF 8 Settings #init-connect=\'SET NAMES utf8\' #collation_server=utf8_unicode_ci #character_set_server=utf8 #skip-character-set-client-handshake #character_sets-dir="E:/xampp2/mysql/share/charsets" [mysqldump] quick max_allowed_packet = 16M [mysql] no-auto-rehash # Remove the next comment character if you are not familiar with SQL #safe-updates [myisamchk] key_buffer_size = 512M sort_buffer_size = 512M read_buffer = 8M write_buffer = 8M [mysqlhotcopy] interactive-timeout


text:
Q: Template flick when modifying subscription I have a Meteor template that renders the documents of a collection. The subscription is set up in the template's autorun:
Template.userSearch.rendered = ->

   Session.set "userSearchLimit", 5

   @autorun ->
      Meteor.subscribe "userSearch", "something to find", Session.get "userSearchLimit"

When the user pressed a "Load more" button I increment the userSearchLimit session variable, which causes the autorun to rerun. The subscription changes since I ask for more data, so the old subscription will be torn down and a new one created, however the first part of the actual data will be the same.
The problem is that the entire list is being redrawn, causing a horrible flicker. When I put debug logging into the find() method as suggested here, then I see that the documents are first being removed, then added back again.
I would have expected the server to avoid resending data that already exists on the client.
How can I solve this?
To further confuse the issue I also tried using ddp-analyzer to see what data was being sent. As soon as I use that then only the new data gets sent and the flicker is eliminated. As soon as I stop using it the problem comes back.

A: I've solved this by manually waiting for the new subscription to be ready before taking down the previous one:
currentMatchingSub = null
prevMatchingSub = null

subscribeToUserSearch = (limit) ->

   prevMatchingSub = currentMatchingSub
   currentMatchingSub = Meteor.subscribe "userSearch", "john baker", limit, ->

      # Only once the new subscription is ready should be take down the previous one. This ensure's
      # that there's no flicker...

      prevMatchingSub.stop() if prevMatchingSub?
      prevMatchingSub = null

Template.userSearch.rendered = ->

   limit = 5
   Session.set "userSearchLimit", limit
   subscribeToUserSearch limit

Template.userSearch.destroyed = ->

   prevMatchingSub.stop() if prevMatchingSub?
   currentMatchingSub.stop() if currentMatchingSub?