Markov Chains Proof using Statistics

Question: Source: This came from "Introduction to probability" by Charles Miller Grinstead, and James Aurie Snell. It was located on page 407 and is Theorem 11.1 in the section 11.1 Introduction.
Theorem: The Theorem 11.1 states: Let $P$ be the transition matrix of a Markov chain. The $ij$th entry $P_{ij}(n)$ of the matrix $P(n)$ gives the probability that the Markov chain, starting in the state $S_i$, will be in state $S_j$, after $n$ steps.
Proof: You start with the probability distribution $Pr(X_{k+n}=S_j | X_k = S_i)$ which can be written as a$\sum_h^\infty Pr(X_{k+n}=S_j | X_{k+n-1}=S_h)Pr(X_{k+n-1}=S_h | X_k= S_i)$. Which can be simplified down even further to the $\sum_1^n P_{jh}P_{hi}^{(n-1)}$. Which can then be simplified to the final version of $P_{ij}(n)$
Class: This is for a class called Seminar. It's a class were supposed to take the year we graduate. It is a class that we do a research essay that we then present to the class and do a set of problems every week with a new topic. (I.E. functions one week, inequalities next, then derivatives, and so on). It's supposed to be a capstone class for our degree that goes over a little bit of everything from the previous three years, but makes you think more and put things together. So we're mathematically mature, but we're not graduate level or anything. If that helps.
What I Need: I could use some help fleshing out this proof to a way that would be understandable for any college mathematics students. I'm doing it for a class and need to be able to teach anyone in my class to understand this proof, but statistics isn't my strong suit and any help would be appreciated.
Comment: May I ask what class this is? You may not need to go through the details of the proof, but rather using an example to see what happens if the transition matrix is raised to an incredibly high power. If it is a "closed" model of a transition matrix (i.e. the sum of columns add to 1) then eigenvectors and eigenvalues are needed. What I mean is that the dominant eigenvector is 1, the other one is a fraction less than 1 and so the eigenvector of 1 will represent the Steady State vector. Please provide some more details of what this class entails
Comment: I edited the question for if that helps. Examples would help, but he wants us to be able to understand the proof and reproduce it for the class so that they understand it also.
Answer: This proof of the Chapman-Kolmogorov Equations can be simplified without losing the essence: Consider a chain with states 1, 2, and 3, and a $3 \times 3$ transition matrix. Also consider three adjacent steps in time. To simplify notation,
let $\{X_1 = 1\} = A$, $\{X_3 = 3\} = C$, and $\{X_2 = h\} = B_h$, for $h = 1,2,3$, so that alphabetical order is time order.
Now we wish to explore the conditional probability $P(C|A)$, that is the probability of a 2-step transition from state 1 to step 3. There are three ways that can occur, which we might diagram as $1 \rightarrow 1 \rightarrow 3$,
$1 \rightarrow 2 \rightarrow 3$ or $1 \rightarrow 3 \rightarrow 3$. Accordingly,
$$P(C|A) = \frac{P(AC)}{P(A)} = \frac{P(AB_1C) + P(AB_2C) + P(AB_3C)}{P(A)}
= \sum_h \frac{P(AB_hC)}{P(A)}.$$
Now consider the $h$th term.
$$\frac{P(AB_hC)}{P(A)} = \frac{P(C|AB_h)P(AB_h)}{P(A)} = \frac{P(C|B_h)P(AB_h)}{P(A)}
= P(B_h|A)P(C|B_h),$$
in which the second equal sign is due to the Markov property. Back in the full original notation, we now have
$$P_{13}(2) = P\{X_3 = 3|X_1 = 1\} = \sum_h P\{X_2 =h|X_1 = 1\} P\{X_3 = 3|X_2 = h\}
= \sum_h P_{1h}P_{h3},$$
and we recognize this sum as element (1,3) of the square of the transition matrix.This expresses the 2-step transition (conditional) probability from step 1 to step 3.  Notice that a one-step transition probability from state $i$ to state $j$ can be written as $P_{ij}$ when it is considered as an element of the transition matrix or as $P_{ij}(1)$ when considered as a one-step transition probability.
Key elements illustreated in these three displayed equations are taking into account possible intermediate paths, the role of the Markov property and the relevance of matrix multiplication. Once students have absorbed these ideas, they have little difficulty expanding to a chain with more states or considering more intermediate steps.
Finally, it might be helpful to illustrate with a concrete example; perhaps use a $3 \times 3$ transition matrix with 1/2 in each diagonal element and 1/4 in all other elements. Then find the square and rewrite appropriate equations above with numbers instead of symbols. Also, such a matrix with 0's along the diagonal and 1/2 elsewhere and states 0, 1, 2 models a random walk on three elements around a circle mod 2 with movement controlled by the flip of a fair coin. For this example it is instructive to see which probabilities in the above equations are zero.
This question lies at the heart of understanding Markov chains. Even though it was proposed a while ago, I believe an answer will be of broader interest. (I'll be covering this at the beginning of a class that starts in early April '15.)

Markov Chains Proof using Statistics


Nginx to split web traffic to a blog hosted on my domain

Question: At the moment, I am using an Nginx frontend to cache static content for my DotNetNuke based website hosted at the hypotetical address www.mydomain.com, along with some other tasks.
In this era of inbound marketing, I am thinking about hosting a blog or some other kind of article database with relevant content, but I want to have the blog hosted on my main domain, not a sub domain.
So, can i use Nginx to forward all traffic from www.mydomain.com/blog/* to a separate web application (possibly wordpress), while still send all other traffic to www.mydomain.com/* except for the /blog/* folder to DNN like before?
And would google and other search engines then completely accept and index the wordpress articles as pages at the main url along with the dnn stuff?
Edit:
Since SEO is my main objective with this, is there antall gotchas with regards to getting the optimal http response codes for the content pages?
Comment: Yes, you can do this with an nginx reverse proxy. It's the same idea of using `/app1` and `/app2` going to different backends. Take a look at some nginx tutorials.
Answer: You can use the reverse proxy feature along with an ip and port to point the server at another address.
<code>server{
    listen    80;
    location /blog/ {
        proxy_pass http://localhost:81;
    }
}

server {
    listen    81;
    location / {
        root   /sites/blog/;
    }
}
</code>
http://nginx.com/resources/admin-guide/reverse-proxy/


Tkinter click event error after third click

Question: I have created this very simple code that generates a message depending if I single or double click on a bar on a barplot.
What I don't understand is why it works for the first two times and the third time that click anywhere it generates an error.
It doesn't matter where I click, if it's left or right and so on. It's always the third time.
I would be glad to understand why this happens.
The error that I get is

canvas = property(lambda self: self.ref_artist.figure.canvas)

AttributeError: 'NoneType' object has no attribute 'canvas'

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
import mplcursors

# create tkinter app window
root = tk.Tk()
root.title("Barplot with Cursor")

# create Figure object in matplotlib
fig, ax = plt.subplots()

# add data to the plot
data = [5, 10, 15, 20, 25]
ax.bar(range(len(data)), data)

# embed plot into tkinter app using FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

# class to keep track of latest event
class LatestEvent:
    def __init__(self):
        self.event = None

    def update(self, event):
        self.event = event

    def get(self):
        return self.event

latest_event = LatestEvent()

# function to handle selection event
def on_select(sel):
    print(f"Selected region: ({sel.target[0]:.2f}, {sel.target[1]:.2f})")

# function to handle left-click event
def on_left_click(event):
    if event.dblclick:
        print('Left double')
    else:
        print('Left single')

# bind left-click events to on_left_click function
def left_click_handler(event):
    latest_event.update(event)
    root.after(300, on_left_click_wrapper)

def on_left_click_wrapper():
    event = latest_event.get()
    if event:
        on_left_click(event)
        latest_event.update(None)

canvas.mpl_connect("button_press_event", lambda event: left_click_handler(event) if event.button == 1 else None)

# function to handle right-click event
def on_right_click(event):
    if event.button == 3:
        if event.dblclick:
            print("Right double-click message")
        else:
            print("Right single-click message")

# bind right-click events to on_right_click function
canvas.mpl_connect("button_press_event", lambda event: on_right_click(event) if event.button in (1,3) else None)

# bind left-click events to on_select function
c = mplcursors.cursor(ax, hover=False)
c.connect("add", lambda sel: on_select(sel))

# start tkinter mainloop
root.mainloop()

Answer: It's a bug of Matplotlib. See the issue#25440 for details.
For now, you can downgrade to the 3.7.0 version like this.
$ pip3 install matplotlib==3.7.0


Addition to an integer field with a form

Question: I have a bundle of image nodes of the same content type that I create in my custom form. Each image node has a field that contains a unique reference number to that node. Currently it is up to the user to add +1 to the previous image node saved and type that in the form for the next reference number. How can I add +1 to the last saved field and use the result to populate the saved field displayed on the saved node? More advanced: If I use an AJAX form that allows users to add more fields to add more pictures on the image creation form, how could I save the images with consecutive IDs?
Comment: Have you got some snippets of your code so far? If you are creating nodes with node_save, IDs will be set and returned for you...
Comment: You can use [Rules](http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&sqi=2&ved=0CBwQFjAA&url=http://drupal.org/project/rules&ei=HcJ6UP-0OI24hAf-6oAI&usg=AFQjCNE3czi2hZQFEPxrPw2ah2DpUTc7Sg) module, you should see simple videos to learn how to do it if you does not use Rules yet.
Comment: Keep in mind file attachments already have a unique id in the file id ( fid )
Answer: You can use the module Prepopulate ; latest release is dev but I use it on a production site and it works like a charm.
If it doesn't work tell me, there are two other solutions : send an arg in the URL to the form (and then use Panels or the php template) and JavaScript (I can give you the code if you need it).


Is it possible to add second horizontal Menu below Main Menu?

Question:
I use "user menu" on top, for user related links.
I use "main menu", in reaching my main contents of site.

I need one more horizontal menu below the "main menu".
So second priority links will be there.
Can it be possible?
(I'm not interested with drop down menus. "Main Menu" and "Second Horizontal Menu" will be independent of each other)
Thank you very much for your help.
Answer:
Go to /admin/structure/menu/add and add a new menu
Go to /admin/structure/block and place the new menu block in the region of your choosing.
Comment: Your going to have to add some css to display them inline. e.g. .YOUR_MENU_NAME li {display: inline;}
Comment: That way doesn't give a horizontal menu.   It gives an unordered list of links, vertically. I need a horizontal menu under the main menu.


Will I be able to run my site on PHP 7.0?

Question: I've started reading about some performance benchmarks with PHP 7.0 which suggest that it is spectacularly much faster. I've searched all over for information on Drupal support for PHP 7.0, but all that I can find concerns Drupal 8 whereas I am still working for the moment on Drupal 7.
I have found this article that concerns Drupal on Windows, which suggests that D7 on PHP7 works, however since I am running on Centos or Ubuntu I would welcome any information anyone might have on this.
My concern is particularly strong because I am just getting started on a project with massive data inputs, which will thus be very performance sensitive.
Comment: Now that there is PHP 7 support in D7 core and PHP 7 has officially been released, I think this question should be reopened.
Comment: PHP 7 is still in RC isn't it? I don't think it's a good idea to put all your eggs in that one basket until there's at least a stable release. What if the answer now is "yes", but "no" when that release happens?
Comment: Voted to close as too broad, because there was 28 bugfixes beetween RC1 and RC2, and more are expected to come. Without knowing if and how they will be resolved, we can't answer. Also, whilst I believe core will work (my faith, not any actual data), nobody can tell about your choice of modules. First, because you didn't provide it, second, because it would be way too long for Q&A format.
Answer: The canonical Drupal 8 issue is tagged "Needs backport to D7", which indicates the community intends to support Drupal 7 on PHP 7 but it may take a little time.
Comment: Note that there is a separate issue for Drupal 7, which is close to wrapping up now that Drupal 7.50 has been released: [Fully support PHP 7 in Drupal 7](https://www.drupal.org/node/2656548)
Comment: Not quite. It only indicates community want it to happen. It does not indicate that anyone declared to put his effort for it to happen...
Comment: Drupal 8 core committers have commented on that issue and have discussed the Drupal 7 situation and a co-maintainer of Drupal 7 marked it for backport to Drupal 7. I disagree with your comment entirely and I don't know what other vote of support you are looking for.


Flask app: Heroku Postgres cannot load remembered user from db

Question: I have a simple Flask app on Heroku with '/login' route that is very standard (pretty much copied from famous Flask Mega Tutorial) and login form with 'remember me' functionality.
Occasionally, I get the following server error when loading the app (error log is large, but the end is):
<code>2020-05-25T18:01:05.614460+00:00 app[web.1]: sqlalchemy.exc.OperationalError: (psycopg2.errors.AdminShutdown) terminating connection due to administrator command
2020-05-25T18:01:05.614460+00:00 app[web.1]: SSL connection has been closed unexpectedly
2020-05-25T18:01:05.614460+00:00 app[web.1]:
2020-05-25T18:01:05.614462+00:00 app[web.1]: [SQL: SELECT "user".id AS user_id, "user".username AS user_username, "user".email AS user_email, "user".password_hash AS user_password_hash
2020-05-25T18:01:05.614462+00:00 app[web.1]: FROM "user"
2020-05-25T18:01:05.614463+00:00 app[web.1]: WHERE "user".id = %(param_1)s]
2020-05-25T18:01:05.614463+00:00 app[web.1]: [parameters: {'param_1': 1}]
2020-05-25T18:01:05.614621+00:00 app[web.1]: (Background on this error at: http://sqlalche.me/e/e3q8)
</code>
I believe the problem is that I have a logged in user that is 'remembered'. When loading the app next time, the app logs in 'remembered' user but sometimes drops the connection with the database (hence OperationaError above). The error is solved by simply loading the page once or twice again.
The link http://sqlalche.me/e/e3q8 has the explanation that this is something outside of the control of the programmer. I do not have the skills to prevent this type of error, but I could at least detect it and reroute the user for better user experience.
Where in the typical Flask code could I check for this problem and instead of the user seeing ugly standard 'internal server error', reroute the user to my custom error page?
Normal entry point for a user is '/index' that does not require login but has this check to see if the user is logged in:
<code>{% if current_user.is_authenticated %}
</code>
Here is the beginning of my '/login' route code:
<code>@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
</code>
Comment: Have you tried removing the remember me functionality to check if it works without it?
Comment: Hi @Patch, sorry if the post wasn't clear. The app works 95% of time with or without 'remember me', but sometimes it gives the above message. So it seems it drops the db connection sometimes. Error only happens with 'remember me' enabled. I prefer not to remove that functionality. I think it is very useful for users.
Comment: It can't work randomly you need to check when it works and when it doesn't. Maybe try debugging your program when the error arrives. It can't just randomly drop the connection with the db it doesn't work like that. And the error happened in the `\login` route?
Comment: According to the sqlalchemy documentation this can happen - this is a quote from sqlalchemy documentation relating to this type of error: "Exception raised for errors that are related to the database's operation and not necessarily under the control of the programmer, e.g. an unexpected disconnect occurs ..."
Comment: The question is are you sure it's that? Because it looks like you have a simple program running and it looks like if it does happen it's like 1 in a million maybe your db setup isn't correct?. It never happened to me I can say that. Why is your current.is_autenticated is a problem? Should be good
Answer: I have found a solution for the problem above. Flask has a inbuilt errorhandler decorator that will catch this error and render a custom error template:
<code>@app.errorhandler(500)
def internal_error(error):
    db.session.rollback()
    return render_template('500.html'), 500
</code>
Please see details in the Flask Mega-Tutorial, error handling section.


Specifying and Interpreting Mixed effects logistic regression

Question: I am trying to make sure that I am specifying and interpreting this model correctly.
In my experiment, participants take two tests (test1, test2) and answer four questions on each test (it's the same test twice). They can either get each question right (1) or wrong (0). I am trying to see to what extent getting the question right on the first test predicts whether they'll get the question right on the second test.
Example data frame
df <- read.table(header = T, text = "
     subj question test1 test2
1     1        1     0     0
2     1        2     1     0
3     1        3     0     1
4     1        4     0     0
5     2        1     0     0
6     2        2     0     1
7     2        3     0     0
8     2        4     0     0
9     3        1     1     0
10    3        2     1     1
11    3        3     0     1
12    3        4     0     1
13    4        1     1     1
14    4        2     1     1
15    4        3     1     0
16    4        4     1     0
17    5        1     0     1
18    5        2     0     0
19    5        3     1     1
20    5        4     1     1
")

I am specifying the model as
fit <- glmer(test2 ~ test1 + (1 | subj),
             data = df,
             family = "binomial", na.action = na.exclude)

And here's the output
summary(fit)
Fixed effects:
              Estimate Std. Error z value Pr(>|z|)
(Intercept)  -0.1823     0.6055  -0.301    0.763
test1         0.4055     0.9037   0.449    0.654

# exponentiate the log odds to get odds ratio
exp(fixef(fit))

(Intercept)       test1
  0.8333333   1.5000000

So according to this sample data & output, and ignoring the p-value, the odds of getting a question correct on test2 are about 50% higher if you got the question correct on test1.
Are my specification and interpretation correct?
Answer: In mixed-effects logistic regression, the fixed coefficients have an interpretation conditional on the random effects. For an explanation of the issue have a look here. Like in your case, I'd say that you want to see the effect of a correct response in test1 in the odds of test2 averaged over the subjects.
You can obtain coefficients with a marginal interpretation using the marginal_coefs() function from the GLMMadaptive package. For example, for your data you can try:
library("GLMMadaptive")

fm <- mixed_model(test2 ~ test1, random = ~ 1 | subj, data = df,
                  family = binomial())

# conditional odds and odds ratio
exp(fixef(fm))

mcoefs <- marginal_coefs(fm)

# marginal odds and odds ratio
exp(coef(mcoefs))

Here you don't see any differences because the variance of the random effects is relatively small. The bigger the variance the greater the difference between the two sets of coefficients.


Bounding an expected hitting time

Question: Consider a stochastic differential equation:
$$dX_t = dW_t + \sin(X_t) dt, \, X_0 = x$$
where $W_t$ is a Wiener process. Define
$$\tau_1 = \inf \{ t : X_t \in 2 \pi \mathbb{Z} \} \\
\tau_2 = \inf \left \{ t : X_t \in 2 \pi \mathbb{Z} \setminus \left \{ X_{\tau_1} \right \} \right \}.$$
My goal is to show that $\tau_1$ and $\tau_2$ both have finite expectation; this will allow me to solve a larger problem about recurrence using very standard arguments.
Since the drift is $2 \pi$ periodic in space and homogeneous in time while the diffusion is homogeneous in both space and time, it is enough to consider $x \in (0,2 \pi)$ for the first part and $X_{\tau_1}=0$ for the second part. In the first case we will be done provided the problem
$$\frac{1}{2} u'' + \sin(x) u' = -1, \, u(0)=u(2\pi)=0$$
has a nonnegative solution. In the second case we will be done provided the problem
$$\frac{1}{2} u'' + \sin(x) u' = -1, \, u(-2\pi)=u(2\pi)=0$$
has a nonnegative solution. These equations may be solved in explicit form, but in terms of some non-elementary integrals, through reduction of order and integrating factors. For instance the solution to the first problem may be written as
$$u(x) = -2 w(x) + 2 \frac{w(2 \pi) v(x)}{v(2 \pi)}$$
where
$$v(x) = \int_0^x e^{2 \cos(y)} dy \\
w(x) = \int_0^x \int_0^y e^{2(\cos(y)-\cos(z))} dz dy.
$$
If I can prove $u \geq 0$ then I will be done. I'm fairly sure that any proof that this $u \geq 0$ will work on the second one. Any suggestions?
Edit: a quick numerical check shows that $u \geq 0$ should indeed hold.
Answer: A simple approach (which avoids the task of checking the nonnegativity of the function in your question) is to compare the hitting times $\tau_1$ and $\tau_2$ with the hitting time $\theta$ of $\pm2\pi$ by the process $$dY=\mathrm dW-\mathrm{sgn}(Y)\,\mathrm dt,$$ starting from some $|y|\leqslant2\pi$.
Since $|\sin|\leqslant1$, $\tau_1$ and $\tau_2$ are dominated stochastically by $\theta$, and $\theta$ starting from any $|y|\leqslant2\pi$ is stochastically dominated by $\theta$ starting from $0$. Finally, $s(y)=E_y(\theta)$ solves $\frac12s''-s'=-1$ with $s(\pm2\pi)=0$ and $s'(0)=0$ hence a standard computation shows that $$8s(x)=\mathrm e^{4\pi}-\mathrm e^{2|x|}+2(|x|-2\pi),$$ in particular, for every $x$, $$E_x(\tau_1)\leqslant E_x(\tau_2)\leqslant E_0(\theta)=\tfrac18(\mathrm e^{4\pi}-1-4\pi),$$ which is finite.

Bounding an expected hitting time


Unit test in golang with structure

Question: I use the VSCode generation for test file of my project,
currenlty it generate the folloing structure
tests := []struct {
        name    string
        args    args
        wantOut ZTR
    }{
        name: "test123",
        args: args{
            ztrFile: "./testdata/ztrfile.yaml",
        },
        wantOut: "ZTR.Modules",
    }

The test should cover parse of yaml and testing the properties
Here it calles to parse file
for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if gotOut := parseFile(tt.args.ztrFile); !reflect.DeepEqual(gotOut, tt.wantOut) {
                t.Errorf("parseFile() = %v, want %v", gotOut, tt.wantOut)
            }
        })

This is the struct
type Modules struct {
    Name       string
    Type       string
    cwd       string     `yaml:"cwd,omitempty"`
}

Not sure what I need to put here to make it work, I try to play with the types but Im getting errors
        {
            name: "test123",
            args: args{
                mtaFile: "./testdata/ztrfile.yaml",
            },
            wantOut: "ZTR.Modules",
        }

The errors I got is
message: 'cannot use "test123" (type string) as type struct { name string; args args; wantOut ZTR } in array or slice literal'
at: '41,3'
source: ''
code: 'undefined'
Comment: You're missing some braces. Remember, you're giving it *entries in a slice of structs*.
Comment: Which is line 41 of your source?
Comment: @Flimzy - `name: "test123",` and I've also error on `wantOut: "ZTR.Modules",`
Answer: Your tests declaration is incorrect.  You need to provide a slice of structs, but you're providing just keys/values:
tests := []struct {
    name    string
    args    args
    wantOut ZTR
}{
    name: "test123",
    args: args{
        mtaFile: "./testdata/ztrfile.yaml",
    },
    wantOut: "ZTR.Modules",
}

should be:
tests := []struct {
    name    string
    args    args
    wantOut ZTR
}{
    {
        name: "test123",
        args: args{
            mtaFile: "./testdata/ztrfile.yaml",
        },
        wantOut: "ZTR.Modules",
    },
}

Comment: Thanks a lot this solve the issue, last question now I've error in the `wantOut` , what I should put there ? for example if the name of the `modules` should be like `name="just name"` `type="justType"`
Comment: I usderstad that this is what I want to verify `expected` but how should I put it there ?
Comment: It's hard to answer your question without knowing what the error is.
Comment: if I need to verify the output of the parse of the structure, how should I put it there , any example will help
Comment: When I put `wantOut: Modules,` I got error `type module is not expression`

Unit test in golang with structure


Problem With Refreshing Answer In Flutter Addition Calculator Problem

Question: I was making a small addition calculator in flutter but do not know how to get the text showing the answer to refresh. I am currently a beginner trying to learn flutter and wanted to do this as a nice small project to extend my knowledge. I know at least that it has to be inside a stateful widget. Here is my current code:
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: MyHomePage());
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Calculator"),
      ),
      body: TextFields(),
    );
  }
}

class TextFields extends StatefulWidget {
  @override
  _TextFieldsState createState() => _TextFieldsState();
}

class _TextFieldsState extends State<TextFields> {
  int num1 = 0;
  int num2 = 0;

  void assignNum1(value) {
    num1 = int.parse(value);
  }

  void assignNum2(value) {
    num2 = int.parse(value);
  }

  String ans() {
    return (num1 + num2).toString();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        TextField(
          decoration: InputDecoration(
            labelText: "Enter Your 1st number",
          ),
          onChanged: (value) => assignNum1(value),
        ),
        TextField(
          decoration: InputDecoration(
            labelText: "Enter Your 2nd number",
          ),
          onChanged: (value) => assignNum2(value),
        ),
        Text(ans())
      ]
    );
  }
}

Answer: You need to make a setState(), this is an example:
TextField(
      decoration: InputDecoration(
        labelText: "Enter Your 1st number",
      ),
      onChanged: setState(() {
                 (value) => assignNum1(value)
                 }),
    ),


How to get object out of inner class

Question: I am trying to make this application in Android, I am getting data from foursquare's API in JSON format and I need to Parse it to present it in another intent.
I am using Android's volley library to get the JSON but the problem is the onResponse() function of JsonObjectRequest has no return parameter.so I cannot get the JSON object gotten from url outside of the the onResponse.
I haven't worked with volley before and hence don't know much about it, any help is appreciated. Here is the code that I am trying to make it work.
Edit: The main problem I'm facing is that I cannot assign a value to global variable in this case myPlaces inside the JsonObjectRequest's onResponse method. Or to be exact, the variable assigned inside means nothing outside, thus in the last line
            Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();

when I try to access the myPlaces[2] it gives me an null pointer exception.
Thanks.
 public void onClick(View v) {

            RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlString, null, new com.android.volley.Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        JSONObject meta = response.getJSONObject("meta");
                        String status = meta.getString("code");
                        Toast.makeText(MainActivity.this, status, Toast.LENGTH_SHORT).show();

                        if(status.equals("200"))
                        {
                            JSONObject responseJson = response.getJSONObject("response");
                            JSONArray venues = responseJson.getJSONArray("venues");
                            Places[] tempPlaces = new Places[venues.length()];
                            for (int i = 0 ; i < venues.length(); i++)
                            {
                                Places place = new Places();
                                JSONObject venueObject = venues.getJSONObject(i);
                                place.setName(venueObject.getString("name"));
                                JSONObject locatVenue = venueObject.getJSONObject("location");
                                place.setLat(locatVenue.getDouble("lat"));
                                place.setLon(locatVenue.getDouble("lng"));
                                tempPlaces[i] = place;
                            }

                            Toast.makeText(MainActivity.this, tempPlaces[2].getName(), Toast.LENGTH_LONG).show();
                            myPlaces = tempPlaces;
                        }

                        else
                        {
                            Toast.makeText(MainActivity.this, "No response from API", Toast.LENGTH_LONG).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this, "There is some error here", Toast.LENGTH_LONG).show();
                    }

                }
            }, new com.android.volley.Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this, "There has been some error", Toast.LENGTH_LONG).show();
                }
            });

            requestQueue.add(jsonObjectRequest);
            Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();

Comment: Possible duplicate of [using inner class object in outer class java](http://stackoverflow.com/questions/18292824/using-inner-class-object-in-outer-class-java)
Answer: Volley itself isn't an inner class; the response is an anonymous class.
You don't need a return in Volley,  you just use the variables already defined in your class.
I'm assuming myPlaces is a field in your class? Otherwise, I'm not sure where it is declared outside the onClick..
This line assigns myPlaces and looks like it would work fine
myPlaces = tempPlaces;

You could define a method in your class to parse the whole JSONObject instead of needing to return from Volley. This just passes the logic to another method, so you don't need to think about "returning" inside Volley.
public void parseJSON(JsonObject object)

And pass the response from volley into that and do your normal parsing and variable assignment and you can Toast myPlaces inside that method.
Also, note that Volley is asynchronous, meaning you aren't guaranteed an immediate result, so
Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();

Would likely have thrown either a NullPointerException or IndexOutOfBoundsException because myPlaces was either undeclared or empty before the Volley request. I say that because it does not appear to be assigned before the Volley request.
Comment: Oh this was really, helpful. now I feel stupid for not thinking about the creating the method and just passing down the object. Thanks. Hope this helps other people.
Comment: Your main problem is that volley is asynchronous, so you were getting a NullPointerException

How to get object out of inner class


Tests for a custom class that load entities

Question: I've managed to write some simple PHPUnit tests, but because the classes within my module have some methods that try to load entities (Content Types built via standard Drupal UI) and then do various thing with them, I am having trouble how to bridge this gap.
Currently when I run my tests most of the assertions pass as they are fairly simply but the one is giving me a warning:

The data provider specified for Drupal\Tests\lrgContentTypes\Unit\AuctionEventTest::testGetNodeFields is invalid. \Drupal::$container is not initialised yet. \Drupal::setContainer() must be called with a real container.

This has only occurred recently because I have now fleshed out the code for the entity class that the parent is trying to pass in the provider.
I am unsure where to go from here, the Drupal 8 documentation seems to be spotty and gives no clear guidance from a basics point of view.
Are there examples that show how to test methods that try to load a node via Node::load() and where entity reference revision objects are expected?
Comment: Drupal 8 docs are not going to tell you a lot about PHPUnit testing as its a PHP thing more than it is a Drupal thing and testing, in general, isn't really a PHP thing more than it is a programming discipline. My only guess here is that the objects here should be mocked and not depend on the entire system, and there is possibly an initialization error in the data provider function that is crashing the test. I think you should also be extending UnitTestCase and not TestCase.
Comment: In fact these may be more functional tests than they are unit, if you are doing Node loads and other interactions.
Comment: @Kevin, I have updated everything to use UnitTestCase. Also have started using Prophecy to mock the objects needed instead. I Thought Functional testing was for browser based stuff. I was following the video at: https://www.youtube.com/watch?v=nd7DUVNxTxE
Comment: Are you not interacting with the database and other services?
Comment: @Kevin Not in the tests I've written so far, this is where I was stumbling because I had thought that there would be a way to grab data from the test development DB and run tests against that (Thought that was Kernal testing) but been told PHPUnit on its own requires mocking. So will be trying Jaypans recommendation today, see below.
Answer: If you are doing Unit tests (and not functional tests), you will need to mock the objects you want to use, in the setup of the test. You can read more here: https://www.drupal.org/docs/8/phpunit/mocking-entities-and-services-with-phpunit-and-mocks
If you are using Drupal functions, you should first try to find out if there is an OOP method that can be used to do the same thing - later versions of Drupal have tried to deprecate such functions, and provide OOP alternatives instead. An example is the Time (datetime.time) service, that replaces things like REQUEST_TIME.
If there is no OOP alternative, you can do the following. Imagine you are using db_query() (which, you shouldn't). Instead of using that function direct in your code, you can create a protected function as follows:
protected function dbQuery($query, array $args = [], array $options = []) {
  return db_query($query, $array, $options);
}

Next, for your text, you will create a class that extends the original class. In this test class, you override dbQuery() above:
protected function dbQuery($query, array $args = [], array $options = []) {
  return ['row1' => ['col1' => 'val1'], 'row2' => ['col2' => 'val2']];
}

This mocks a call to db_query by returning an array of values. The last step is to use this new class in your Unit tests, so that when dbQuery() is called, it uses your extended version that returns the array, instead of calling db_query() which is not available to the Unit test.
Comment: thanks I will look into trying your method out tomorrow, when I get back to the tests. Appreciate the time. As a side note (See comment above) I started attempting to use Prophecy to mock the objects.


Is it necessary to use a dash to indicate a suspension in a figured bass?

Question: In the ABRSM theory exams, a 4-3, 7-6 or 9-8 suspension always has a dash between the two numbers in the figured bass. I have not found this to be the case in analyses that I have looked at. So is the dash just to make suspensions obvious to students or is it common practice to figure suspensions this way?
Comment: @Dekkadeci Thanks for checking. Yes, it is certainly figured bass but I'm struggling to clearly articulate what I mean. I've added an example. A picture is worth a thousand words after all ;-)
Comment: Just in case, are you sure those numbers are figured bass? If there is ever more than one note in the bass playing at once, I don't think it's figured bass anymore.
Answer:
or is it common practice to figure suspensions this way?

I can't tell you whether it was common practice for that period. But the explanation of musescore shows that it's possible to notate this today.
The dash assigns that the upper voices or the bass don't change.

A  horizontal line indicates a changes of voicing or a change of harmony. This may take place over a stable or an active bass. Note that in this situation it is customary not to abbreviate a five-three chord.
https://musescore.org/sites/musescore.org/files/Figured-Bass-Notation.pdf
Comment: That function of the dash applies when the bass note changes but the upper voice note (or an upper voice note) does not.  But here, the bass note remains the same while the upper voice changes.
Comment: @phoog: thank you. I've edited my example and my comment.
Comment: I agree with this answer, but would note the difference in the styles of "dash" employed.  The sort of long extended dash that connects two numbers is most frequently seen in theory book examples and in analyses, rather than practical examples of figured bass.  As phoog notes, in practical figured bass, *short* dashes are generally used to indicate the upper voices extending over a change in bass.  The example quoted in the question seems to be poorly edited or using a hybrid system.
Answer:
Is it necessary to use a dash to indicate a suspension in a figured bass?

No.  It is both unnecessary and unusual.
As Albrecht Hügli notes, a dash is used when the bass note changes but the harmony (or perhaps one voice in the harmony) does not.  But that's not what's happening here.  In this case, an upper voice is moving, while the bass is not.
The dashes may perhaps be intended to underscore that the motion in the upper voice does not represent a change in the harmony, since in both cases the voice is leaping from one chord tone to another.  But this notation is not commonly seen in figured bass writing from the baroque period.  A suspension is normally indicated by placing the figures for the moving voice in sequence horizontally.  In other words, the hyphen appearing between the seven and the six in your example would be absent.
Comment: I agree with this answer in terms of historical figured bass notations, though the question asks about *theory exams* and "analyses."  In both of those cases, extended dashes are commonly employed to indicate upper voice motion such as suspensions.
Answer:
...is it common practice to figure suspensions this way?

It seems no. The line after a figure means hold the initial chord while the bass changes.
I had to look this up so I can't claim scholarly knowledge.
Resources to compare against...
J.G. Albrechtsberger's collected writings on thorough-bass, harmony, and composition

Robert Kelley, Ph.D., How to Realize a Figured Bass: An Introduction to Thoroughbass

George Frideric Handel, David Ledbetter, Continuo playing according to Handel: his figured bass exercises, Oxford University Press, 1990


Salvar imagens no dispositivo sem expirar

Question: Tenho um aplicativo feito com Intel XDK, rodando em iOS e Android. O intuito é exibir imagens que estão no servidor, e armazená-las no dispositivo para não fazer o download toda vez que ela for exibida.
Então, além de armazenar, precisaria verificar se ela já existe no dispositivo.
É algo similar ao LazyAdapter presente no Java e usado em diversos aplicativos.
Isso é possível?
Comment: confesso que nunca ouvi falar desse XDK, mas como colocou a tag cordova-plugin, pode ser que o [plugin file](https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file) funcione para voce
Comment: O XDK usa o plugin Cordova, já vem com compilador próprio (na nuvem), entre outras coisas que facilitam o desenvolvimento. Vou baixar esse plugin por ele (também baixa plugins externos) e te dou um retorno
Answer: Fiz algo parecido, mas para ionic/angular como uma diretiva, como disse usei o plugin file.
Vou deixar o codigo mais como modelo de como fiz.
angular.module('imagefusion', ['ionic', 'ngCordova.plugins.file'])
.directive('imageFusion', function($compile, $timeout, $cordovaFile, $cordovaFileTransfer) {
    return {
        restrict: 'E',
        //replace: true,
        //template: '

',
        //transclude: true,
        scope: {
            config: '=',
        },
        link: function(scope, $image, attrs){
            var debug = true;
            var localPath = 'images/'+scope.config.name;
            var $spinner = null;
            var ghost = angular.element(new Image());

            function changeSource(src){
                ghost.attr('src', src);

                if($spinner){
                    $spinner.remove();
                }
            }

            function displayLoader(){
                $spinner = angular.element($compile('<ion-spinner></ion-spinner>')(scope));
                $image.append($spinner);

                var wrapperSize = {width:$image[0].offsetWidth, height:$image[0].offsetHeight};
                //var spinnerSize = {width:$spinner[0].offsetHeight, height:$spinner[0].offsetHeight};
                var spinnerSize = {width:28, height:28};

                $spinner.css('position', 'absolute');
                $spinner.css('left', ((wrapperSize.width-spinnerSize.width)/2)+'px');
                $spinner.css('top', ((wrapperSize.height-spinnerSize.height)/2)+'px');
            }

            function formatSize(size){
                var s = null;
                if(size){
                    if( typeof size=='number' || (typeof size=='string' && size.indexOf('%')==-1) ){
                        s = size+'px';
                    }else{
                        s = size;
                    }
                }

                return s;
            }

            var size = null;
            if(scope.config.size){
                size = scope.config.size;
            }

            // naturalHeight
            // console.log(cordova.file.applicationStorageDirectory);
            // file:///data/data/br.com.nibler.doctorphotosolution/
            if(size){
                var w = formatSize(size.width);
                $image.css('width', w);
                $image.css('height', w);
            }

            ghost.on('load', function(event){
                var target = event.target;

                if(!size.height){
                    var height;
                    var image = $image[0];

                    if(attrs.original!==undefined){
                        // (original height / original width) x new width = new height
                        var originalWidth   = ghost[0].naturalWidth;
                        var originalHeight  = ghost[0].naturalHeight;
                        var currentWidth    = image.clientWidth;
                        //var currentHeight     = image.clientHeight;

                        height = (originalHeight/originalWidth)*currentWidth;
                    }else{
                        height = image.clientWidth;
                    }

                    $image.css('height', formatSize(height));
                }
                $image.css('background-image', 'url('+target.src+')');
            });

            $image.on('error', function(){
                if(debug){
                    console.log('Error');
                }
            });

            $image.css('background-position', 'center center');
            $image.css('background-repeat', 'no-repeat');
            $image.css('background-size', 'cover');
            $image.css('display', 'inline-block');

            if(attrs.relative!==undefined)
                $image.css('position', 'relative');

            $timeout(function(){
                displayLoader();
                //console.log(localPath);
                //console.log(cordova.file);
                cordova.file;
                //debugger;

                var storageDir = null;

                if(ionic.Platform.isIOS()){
                    storageDir = cordova.file.documentsDirectory;
                }else{
                    storageDir = cordova.file.applicationStorageDirectory;
                }
                var fullLocalPath = storageDir+localPath;

                if(!scope.config.name || scope.config.url.indexOf('http')==-1){
                    changeSource(scope.config.placeholder);
                }else{
                    $cordovaFile.checkFile(storageDir, localPath).then(
                        function(success){
                            changeSource(fullLocalPath);
                            if(debug){
                                console.log('['+scope.config.name+'] Fetched from Disk');
                            }
                        },
                        function(err){
                            if(debug){
                                console.log('['+scope.config.name+'] Not exists, downloading....');
                            }

                            $cordovaFileTransfer.download(scope.config.url, fullLocalPath).then(
                                function(resp){
                                    changeSource(fullLocalPath);
                                    if(debug){
                                        console.log('['+scope.config.name+'] Downloaded');
                                    }
                                },
                                function(err){
                                    if(debug){
                                        console.log('['+scope.config.name+'] Download error');
                                        console.log(err);
                                    }
                                }
                            );
                        }

                    );
                }
            });
        }
    };
});

Comment: Ajudou bastante, valeu!


Turn non-invertable matrix into nilpotent

Question: $A$ is a non-invertable $n$ by $n$ matrix over a field $K$. Show that there are invertable matrices $S,T$ such that $SAT$ is nilpotent.
Comment: **Hint:** In general, there exist invertible matrices $S,T$ such that $B=SAT$ if and only if $A$ and $B$ have the same rank.
Comment: @JendrikStelzner I know that there must be an invertable matrix $S$ such that $SA = E$, where $E$ is in row-echelon form, and because $A$ is not invertable $E$ should have a zero row. But $E$ is not necessarily nilpotent (I have a counterexample) and what about $T$ then. So I am stuck.
Answer: Suppose $A$ is a $n \times n$ matrix. It is a basic result that we can find invertible $n \times n$ matrices $S'$ and $T'$ such that
$$
 S' A T' =
 \begin{pmatrix}
  1      & 0      & \cdots &      0 & 0      & \cdots & 0 \\
  0      & 1      & \cdots &      0 & 0      & \cdots & 0 \\
  \vdots & \vdots & \ddots &      0 & 0      & \cdots & 0 \\
  0      & 0      & \cdots &      1 & 0      & \cdots & 0 \\
  0      & 0      & \cdots &      0 & 0      & \cdots & 0 \\
  \vdots & \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\
  0      & 0      & \cdots &      0 & 0      & \cdots & 0
 \end{pmatrix}.
$$
(To see this take a basis $(b_1, \dotsc, b_k)$ of $\ker(A)$ and extend this to a basis $\mathcal{B} = (b_1, \dotsc, b_k, b_{k+1}, \dotsc, b_n)$ of $K^n$. Then $\{Ab_{k+1}, \dotsc Ab_n\}$ generates $\mathrm{im}(A)$, so we can choose a basis of $\mathrm{im}(A)$ of the form $(Ab_{i_1}, \dotsc, Ab_{i_r})$ for $r = \mathrm{rang}(A)$ and $k+1 \leq i_1 < \dotsb < i_r \leq n$. Extend this to a basis $\mathcal{C} = (Ab_{i_1}, \dotsc, Ab_{i_r},c_{r+1},\dotsc,c_n)$ of $K^n$. If we rearrange $\mathcal{B}$ and $\mathcal{C}$, and take $\mathcal{B}$ as a basis of the domain of the linear map $f \colon K^n \to K^n$, $x \mapsto Ax$ and $\mathcal{C}$ as a basis of its codomain, then with respect to these bases $f$ is represented by the above matrix.)
It sufficies to show the statement for $S' A T'$, so can assume w.l.o.g. that $A$ is of the above form. Then for $r = \mathrm{rang}(A)$ we have $A e_i = e_i$ for every $1 \leq i \leq r$ and $A e_i = 0$ for $r < i \leq n$ (that $r < n$ corresponds to the fact that $A$ is not inverible).
Consider the $n \times n$ permutation matrix $S$ with $Se_i = e_{i+1}$ for every $1 \leq i < n$ and $Se_n = e_1$ and let $T$ be the identity matrix. Then $SAT e_i = e_{i+1}$ for all $1 \leq i \leq r$ and $SAT e_i = 0$ for all $r < i \leq n$, so $SAT$ is nilpotent.


Android Bitmap Linear Interpolation Blending

Question: I need to be able to blend two bitmaps together using a linear interpolation (or average). This is a fairly simple operation, but even using native code to manually apply it to each pixel is too slow.
How can I accomplish this? Is there any way to accomplish this using shaders without swapping my entire engine to openGL?
Thanks.
Answer: You can probably use Porter-Duff filtering with a Paint object to get the performance you want, even without using ndk. It tends to be pretty fast.
Show us your code and someone can probably provide a more specific answer.
Comment: I have looked through the standard PorterDuff modes have yet to find a way to combine them to achieve what I want. Any code is really just going to be standard bitmap rendering(canvas), there isn't anything special about the rest.


How to handle the 3 hard Keys in Android

Question: There are the 3 basic keys in an Android device.
 1. Home button (middle button)
 2. Menu button (left most button)
 3. Back Button (right most button)
I'm trying to create a code the use will press the Back button and a AlertDialog will appear before return to the previous activity.
How can I handle the back button and do I have to insert it on the onCreate on the Java File of an Activity?
Thank You!
Comment: It's not completely true. Some devices have 4 phisical buttons. And the tendency on some devices is to eliminate the menu button.
Comment: Oh! and I forgot to mention that you can manage the Volume physical keys and (not pretty sure about) the power button as well.
Comment: "There are the 3 basic keys in an Android device" -- no, there are not. *Some* devices have *some* keys. "I'm trying to create a code the use will press the Back button and a AlertDialog will appear before return to the previous activity." -- this is a UI anti-pattern. Please do not interrupt the user when they press BACK. Moreover, this does not handle any other way that the user might navigate away from your app, such as HOME or the recent-tasks list.
Answer: All (4) buttons are handled differently.
The home button and running apps buttons are completely outside your control.
To get the BackButton press, override this function.
@Override
public void onBackPressed(){
    //Do Stuff
}

To get the Menu button key press, use the following
@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
    switch(keycode) {
        case KeyEvent.KEYCODE_MENU:
            doSomething();
            return true;
    }

    return super.onKeyDown(keycode, e);
}

After you show the user your alert dialog, you can either send a real BackPress to the system using super.onBackPressed(), or you can manually finish() your activity.
Comment: Huh...and I've never used onBackPressed.  I wonder if there are any compelling technical reasons to use one or the other to detected the Back button.  You've given me something to Google!
Comment: I typically use onKeyDown for both Menu and Back.  Is there a reason to use onBackPressed instead of using onKeyDown for both buttons?
Comment: @RobertNekic, that is actually just the way I have always done `onBackPressed`, because I try to never use the Menu key.
Answer: @Override
public void onBackPressed(){

    AlertDialog.Builder build=new AlertDialog.Builder(currentactivity.this);
    build.setMessage("Are you sure you want to return?");
    build.setCancelable(false);
            build.setTitle("Note");
    build.setPositiveButton("yes", new DialogInterface.OnClickListener() {

        @Override
    public void onClick(DialogInterface dialog, int arg1) {
        Intent i =new Intent(currentactivity.this,anotheractivity.class);
    startActivity(i);
            //or just type finish();
               }
    });
    build.setNegativeButton("no", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int arg1) {

            dialog.cancel();
        }
    });
    AlertDialog alert=build.create();
    alert.show();

}


Run XP Application from Windows 7/8/10

Question: I have a small network (windows Server 2012r2 Domain) and need to run on 10 workstations one application wich runs (well) only on Windows XP.
I was thinking of running a windows xp VM and connect to it from the workstations, wich are running windows 7-8-10.
What are the options?
Already tried

Thinstuff XP/VS, not working on Windows 8
Rdp RemoteAPP, cant find KB961742-v3
Comment: Window XP Mode virtual PC.  Compatibility mode checkboxes on application properties...
Comment: Update the application.
Comment: Does XP-Mode work on Windows 8 and 10?
Comment: If only this would be possible!
Answer: You may try Oracle VirtualBox. I use it quite a lot. For server use (e.g. headless mode) see section 1.16 in this doc.
Comment: Thank you but I was looking for something simpler, like Thinstuff, it would have been perfect if it was compatible.

Run XP Application from Windows 7/8/10


Mule 4 : Design : How to process data[files/ database records] in Mule 4 without getting "out-of-memory" error?

Question: Scenario :
I have a database which contains 100k records which have a 10 GB size in memory.
My objective is to

fetch these records,
segregate the data based on certain conditions
then generate csv files for each group of data
write these CSV files to a NAS (storage drive accessible over the same network)

To achieve this, I am thinking of the design as follows:

Use a Scheduler component that triggers the flow daily at 9 am for example)
Use a database select operation to fetch the records
Use a batch processing scope
In batch step use reduce function in Transform message and segregate the data in aggregator in the format like :

<code>{
   "group_1" : [...],
   "group_2" : [...]

}

</code>

In the on complete step of batch processing use a file component to write the data in files in the NAS drive

Questions/Concerns :
Case 1 : When reading from database select it loads all the 100k records in memory.
Question : How to optimize this step so that I can still get 100k records to process but not have a spike in memory usage?
Case 2 : When segregating the data I am storing the isolated data in the aggregator object in reduce operator and then the object stays in memory till i write it into files.
Question : Is there a way I can segregate the data and directly write the data in files in the batch aggregator step and quickly clean the memory from the aggregator object space?
Please treat it as a design question for Mule 4 flows and help me. Thanking the community for your help ad support.
Answer:
Don't load 100K records in memory. Loading high volumes of data in memory will probably cause an out of memory error. You are not providing details in the configurations but the database connector 'streams' pages of records by default so that's taking care. Use the fetchSize attribute to tune the number of records per page that are read. The default is 10. The batch scope uses disk space to buffer data, to avoid using RAM memory. It also has some parameters to help tune the numbers of records processed per step, for example batch block size and batch aggregator size. Using default values would not be anywhere near 100K records. Also be sure to control concurrency to limit resource usage.

Note that even if reducing all configurations it doesn't mean there will be no spike when processing. Any processing consumes resources. The idea is to have a predictable, controlled spike, instead of an uncontrolled one that can exhaust available resources.

This question is not clear. You can't control the aggregator memory other than the aggregator size, but it looks like it only keeps the more recent aggregated records, not all the records. Are you having any problems with that or is this a theoretical question?
Comment: thanks for your answer. I am just looking for optimizing my solution. it does not give any error at the moment.


Run meteor on Raspberry pi (ARM6)

Question: I tried to install meteorJS on my raspberry pi  and I get this error during the installation :
"Unable to install on unsupported architecture Meteor: armv6l
 Installation failed. ".

There is a solution by modifying the file "admin/generate-dev-bundle.sh" on the meteor core to regenerate the bundle, but what should we put in this file?
Do you have another solution?
Thank you
Comment: You need to rebuild node from source on your raspberry - https://gist.github.com/stolsma/3301813, Be warned it does take a fair amount of time, then just run `npm install meteor` hopefully it should pull through
Comment: Have a look at http://stackoverflow.com/questions/10936675/meteor-on-armv6l-raspberry-pi
Comment: @Akshat Thanks but i want the content of the "admin/generate-dev-bundle.sh" file !
Comment: @Baltox could you please change the accepted answer because the fork from IG is outdated and still some old 0.x version of meteor. Thanks, Tom
Answer: FYI, I've put together a fork of meteor that supports the Raspberry Pi, along with full installation instructions. You can find it here: https://github.com/IGx89/meteor
Comment: @IGgx86 I'm currently running your fork of meteor and have successfully compiled mongodb on the pi (took forever!). Any chance you could update to meteor 1.x?
Comment: Thanks! Thank you for keeping this SO Question current :)
Answer: I created some update to meteor dev bundler so that you can generate runtimes for yet unsupported architectures. [Update] I will support the meteor realease tags in future as long as they will supprt ARM by themself. Checkout branches on my GitHub repo [Update]. [Update2] Added infos from tumblr site[Update2]
https://github.com/4commerce-technologies-AG/meteor
http://meteor-universal.tumblr.com/
Comment: I created a small internet tumblr site around meteor on ARM. There are many hints about how to install meteor and nodejs on UDOO, Rasberry Pi, Beaglebone and others. Have a look at: http://meteor-universal.tumblr.com/
Comment: Tom also made a great install script for 1.0 here https://github.com/4commerce-technologies-AG/meteor
Answer: Quote by Nick Martin in verbatim from Issue #442 in the Meteor github repository:
No immediate plans to add official ARM support. In theory, all the dependencies
should build on ARM, so you could try building the dev bundle on your platform.
See https://github.com/meteor/meteor#slow-start-for-developers

All required files to build this (yes, even admin/generate-dev-bundle.sh) is available in the repository above. Akshat references another SO question that does mention how to modify it. Quoting this in verbatim:

Essentially, remove all the instructions regarding building node.js, and all references to a tempdir, so you end up just installing node packages. I will post mine as a gist once it's all figured out...

Just give it a spin. It's even possible you can arrive to a solution faster. You never know until you try.

Run meteor on Raspberry pi (ARM6)


Does my SSL cert have anything to do with or say about the symmetric session key?

Question: The answer found on this server fault thread is my jumping off point for this general topic: https://serverfault.com/a/313558
... and this question can be thought of as a follow-up to that answer.
Does my SSL cert have anything to do with or say about the symmetric session key? (I know that the browser and web server both have a role there, but what about the cert itself?)
If YES: Where is it specified in the cert?
If NO: Why do CAs all boast about "128-bit to 256-bit encryption" which is implicitly referring to the session key?
Comment: The answers are NO, and because all marketing people should be shot, respectively.
Comment: Maybe the marketing guys talk about the symmetric session key while submitting the CSR, from the client's browser to their own servers...
Answer: No. The strength and type of the symmetric encryption used is negotiated by your browser and webserver (and thus based on their configuration). The certificate simply allows the key agreement to happen in a secure (authenticated) fashion.
Concerning your follow-up question: It's mostly a marketing gag. The certificate they sell enables you to use 256-bit encryption during the session. Which is, of course, also true for absolutely any standard compliant X.509 certificate.


Internet Explorer 9 doesn't align text in div

Question: I have a problem concerning IE9 and CSS.
I have a HTML5 form where I want to align the button on the right of te page. But only in IE9, it right aligns to a div where it seems not to have any connection to.
In Chrome and Firefox it looks like this:

That is the desired outcome.
But in IE9, it looks like this:

When I play around with the F12 Developer tools settings, it works whe I choose "Document Mode: IE7 standards" and any Browser mode.
HTML looks like this and is HTML5 validated on http://html5.validator.nu/:

As you can see this div is not related to the other divs.
The style window looks like this (all css files are css3 valid):

I have already tried to place a span like suggested here:
Align Text in List in Div with CSS in Internet Explorer 9
Any other suggestions are welcome, or work-arounds that will do the job.
Answer: I have finally figured it out. Adding the following line before each dubhead div did the trick:

References:
- What is the use of style="clear:both"?


The letters A, E, I, P, Q, and R are arranged in a circle. Find the probability that at least 2 vowels are next to one another.

Question: I've had trouble for his one for a while now. All help would be greatly appreciated.
My attempt:
Alright, since one letter is fixed, that leaves us with 5 letters to arrange. I'm going to fix the consonant in this case, since it is particularly easier for me :P. The remaining spots (5 left) can be arranged 3!*2! (remaining vowels and consonants respectively). I'm lost here though, so any help on what to do/correct me would help. Thanks! :D
Answer: There are $6$ chairs around a table. The chairs are labelled $1$ to $6$, in counterclockwise order.
The letter $P$  sits down somewhere, it doesn't matter where, say on the chair labelled $1$. Then the other letters sit down at random. We will find the probability that the vowels are all separated.
If the vowels are to be all separated, they must occupy chairs $2$, $4$, and $6$, and the remaining two consonants must occupy $3$ and $5$.
There are $\dbinom{5}{2}$ ways of selecting two chairs for the consonants, from the remaining five. There is exactly $1$ selection that consists of chairs $3$ and $5$.
I expect you can now complete things.
Answer: A few broad hints:

Since the letters are arranged in a circle, you can choose to 'start' the circle anywhere you wish, so you can just set the 'A' at twelve O'clock for reference purposes; that leaves one less symmetry that needs consideration.
Ignore the specific consonants and vowels for a minute and imagine that you have V, V, V, C, C, and C.  How many distinct ways can you arrange those letters (with a 'V' at 12 o'clock, remember!) so that none of the Vs are next to each other?
Now that you know all the possible configurations of V's and C's, can you go back for each of those configurations and figure out how many possible assignments of vowels into the Vs (remember, your A is still fixed!) and how many possible assignments of consonants into the Cs there are?  (Keep in mind that for each possible C-and-V set, the arrangement of individual vowels into the Vs and individual consonants into the Cs are independent; this means that you can just multiply the number of vowel arrangements by the number of consonant arrangements to get the total number of arrangements for a given configuration.)
Once you've done this for each configuration of Vs and Cs, you can just add up the total number of arrangements per configuration to get the total number of 'good' arrangements.  Can you figure out how to get the total number of arrangements?  (Keep in mind that we're keeping the 'A' fixed at the top, still!)  Once you have the two numbers, you should be able to just divide them out to get a probability...
Comment: Hey, if it doesn't bother, would you mind giving me the answer, so I can see whether I did it correctly?
Comment: @missiledragon To be honest, I'd rather see your attempt (and answer) edited into the question!
Comment: I placed my attempt, however, I'm still pretty stuck :(
Comment: @missiledragon You skipped into step 3 without doing step 2 at all; I really recommend doing step 2 first.  After that, try doing step 4 (in particular, for the second half of step 4 you can _ignore_ the vowel-consonant distinctions...)
Comment: I think I arrived at the answer: 1-(3!*2!/5!)


how to start aplication or bring to front when user clicks on a notification click on android

Question: I'm working whit push notifications.
When a user clicks on a notification I want to start the application in case it is not started, or bring it to front in case it is started.
Thanks
Answer: implement pending intent.
Code
Intent pi = new Intent();
pi.setClass(getApplicationContext(), youactivity.class);
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,pi, PendingIntent.FLAG_UPDATE_CURRENT);
String msgText = mMessage;
// construct the Notification object.
Notification notif = new Notification(R.drawable.icon, msgText,System.currentTimeMillis());

manifest
<activity android:name="com.InfoActivity" android:noHistory="false android:excludeFromRecents="false"></activity>

Answer: this is the complite code I found the answer here Bring application to front after user clicks on home button
    Intent intent = new Intent(ctx, SplashScreen.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
                    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
                    PendingIntent.FLAG_CANCEL_CURRENT);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                    ctx).setContentTitle(extras.getString("title"))
                    .setContentText(extras.getString("message"))
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentIntent(contentIntent);
           Notification noti = mBuilder.build();
           noti.flags = Notification.DEFAULT_LIGHTS
                | Notification.FLAG_AUTO_CANCEL;
           mNotificationManager.notify(NOTIFICATION_ID, noti);

The important things are the flags on the Intent, this will open the app or bring it to front if is opened, or do nothing if you click on the notification while you are browsing the app
Answer: Just set the intent for the notification, this is covered in details in the official API guide.
Answer: You do that by creating a PendingIntent.
For example, this will launch a MainActivity when notification is clicked.
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

Notification noti = new Notification.Builder(this)
        .setContentTitle("Notication title")
        .setContentText("Content text")
        .setContentIntent(pendingIntent).build();

Comment: sorry but this is not working, it makes new instance from the activity
Comment: Then you may just change PendingIntent.getActivity() to PendingIntent.getBroadcast(), and make your IntentReceiver to receive this intent, and do whatever you want.
Answer: I don't know whether you're talking about Google Cloud Messaging or not. But if it is a normal Notification then while creating your notification you've to provide Pending Intent. Just put your desired class in Pending intent so that when user clicks on that notification you'll be driven to your so called Application. A snippet :
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
        "Your application activity".class), PendingIntent."Flag you want");

After this use this intent while creating notification. It's method is setContentIntent("above intent") and fire your notification with NotificationManager!
Comment: the folowing flagns need to be added intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER); to the launcher intent in order to start the aplication, and


CheckBox in table

Question: This question is regarding aem 6.3
I have an assignment that requires me to use a checkbox in the table. But I notice that when I do that, I am unable to create a new row through the workflow. May I know is there a workaround over it?
In my console logs, I am getting this error
<code>TypeError: Cannot read property 'id' of undefined at child.handleAccessibility...
</code>
Am I suppose to create an id first? If so how do I do that?
Thanks
Norman
Answer: It appears to be that aem currently has a bug where the title of the checkbox cannot be hidden if not it will face the aforementioned error. So the solution is not hide the title but let it be blank.
This is more of an issue of that the id cannot be recognised, instead of unable to create a new row through the workflow, that resulted in the latter issue.

CheckBox in table


Report to Multiple Google Analytics Property IDs?

Question: Is it possible to have Google Analytics report traffic to a given page to more than one Profile ID? If so, are there any special considerations or recommendations for doing such? I can't seem to find anything about doing this in the Analytics documentation.
Can I just call <code>_gaq.push(['_setAccount', 'UA-xxxxxxx-x']);</code> multiple times? Or would the nth call just override the previous one?
Thanks!
Answer: As long as the UA-xxxxx id is different I can't see how it would cause any problems.  I've chained three GA trackers on one site and had no issues at all.
For more info see here: http://www.google.com/support/forum/p/Google+Analytics/thread?tid=4513592e18b05514&hl=en
Comment: Thanks for the info, nageeb! Did you include the complete tracking script three times, or just the `_gaq.push(['_setAccount', 'UA-xxxxxxx-x']);` line I mentioned above?
Comment: At the time I wasn't sure, so I believe I added the entire script, but that wasn't necessary.  See the link I just posted in the answer for more info.


What is heard when a tuning fork is struck?

Question: When a tuning fork is struck I hear two tones. From a distance I can hear a high octave frequency of the pitch of the tuning fork. Though, if I listen to it closely (closer to my ears), I also hear a lower octave frequency of the pitch of the tuning fork. I want to clarify that what I'm hearing is correct.
Also, is there something about "pure tones" that produces this effect, and if so what are the harmonics of a pure tone/tuning fork? Just from brief reading on the topic, I've seen it said that tuning forks' overtone(s) (I'm assuming there is only one overtone) ring out quickly. Then why am I hearing a high octave version of the fork's pitch and a low octave version of the forks pitch until it rings out?
Comment: *Tiiiiiiinnnnnngggggggggggggg*
Answer: Although tuning forks produce very pure tones compared to other instruments, they do not produce actual pure tones.  One reason that you can hear the overtones easily, despite how quiet they are, because human ears are very sensitive in the frequency range that they exist in (2-5kHz).  The frequency separation between the overtones and fundamental also prevent the fundamental from masking the overtones effectively.
The reason these overtones exist at all is because the tuning fork has several modes of vibration- different ways in which the metal can bend and produce periodic oscillations.  Each mode sounds a different frequency.  You suspect that there is only one overtone, but that is not exactly right- there are many overtones, but one (the "clang mode") tends to ring longer and louder than the rest.  This clang mode isn't necessarily a harmonic of the fundamental, and it is totally unrelated to the fork's use as a musical tool.
A similar question has been asked on physics stackexchange, and there is some more technical detail on the overtones produced here.  If you want to find the overtones of your particular tuning fork, you can record it and analyze the recording with a software spectrogram/spectrograph/spectrum analyzer.
Comment: @phoog -- you really do **NOT** want to know.     https://www.frequencyheals.com/product/221-23-hz-frequency-of-venus/
Comment: The relationship of the clang mode to the fundamental mode can vary between tuning fork designs.  You can't rely on it being a fifth.
Comment: @Lecifer what is the purpose of a 221.23 Hz tuning fork?
Comment: @phoog uh oh Sweetwater set me up! (Jk)… But honestly I assumed it wasn't a huge deal as I never perfectly tune my guitar strings. Maybe I should pay more attention to that. I'm gonna get a 440hz fork soon as well.
Comment: Yes, it's most likely that the high tone you hear is the clang mode.  The lower tone is the fundamental mode.
Comment: @CarlWitthoft OMG you're right!  Lecifer: I asked because that frequency does not particularly correspond to any frequency that would be in common musical use -- it's rather sharp of the standard A at 220 Hz (by about 10 cents).  You'd be better off buying a tuning fork from a music shop.
Comment: Firstly, thank you for the detailed response! I am going to look into some of your suggestions but I had one immediate observation. I have two 221,23 hz forks and I hit them together. Is the high tone I'm hearing the "clang mode"? The only thing is, that is the tone I'm saying rings out earlier than the lower quieter tone.
Comment: Also I see that the clang mode would actually be a perfect fifth, not an octave.
Comment: @phoog Well according to meinl (the brand) it encourages intuition and opens your third eye lol. But I only bought it to use for tuning without needing electricity. Why do you ask though?
Comment: @Lecifer Yeesh, anything to sell a product I guess.  It's unusual to get a tuning fork that doesn't correspond to a common tuning standard, but it's close enough to a standard A that it will work, as long as you demand that everyone tunes to you or you don't play music with anyone else.
Answer: The tone the tuning fork is tuned to is generated by transversal waves in the tips of the metal fork. It needs amplification by a resonance body (or as you did: close listening). This is the low tone.
Depending on how you hit the tuning fork (eg with a hard object, rather on the top than sideways), also longitudinal waves can be generated. These are not the swing of the fork tips, but they travel along the fork with the speed of sound in the metal. This is the high tone.
Comment: Longitude modes are unlikely in a traditional tuning fork.
Answer: I'm guessing that the higher tone is an overtone the first of which is the same note an octave higher (the first overtone of an A is an A for example). However, I don't what's causing the lower note. It's possible that the lower note is fundamental pitch note or that something else entirely is happening.
I would recommend you ask the Physics stack exchange, this seems like more an interesting physics question than a music one.
Comment: Ideophones such as tuning forks do not have harmonic overtones, so the overtone is unlikely to be found in the harmonic series.
Comment: @Lecifer it is evident from the definition of idiophone and the nature of tuning forks that a tuning fork is an idiophone.  Also see [Warren Burt - Music For Tuning Forks (1987) (Full Album)](https://m.youtube.com/watch?v=LK0WdW1HDzQ) on YouTube.
Comment: I actually posted it on there first, but I thought maybe I was posting it in the wrong place lol! I'll repost it on there again. And what you said is my speculation. If the fork is closer to your ear, you hear the Low A and the high A. If it is further away, you only hear the high A (the low A is still ringing but only perceivable up close which I'm assuming has to do with size of the fork). The high A also rings out earlier than the Low A.
Comment: @phoog I guess the tuning fork not being classified as an instrument (idiophone), is because it hasn't really been used as one because I don't see it anywhere https://en.wikipedia.org/wiki/Hornbostel%E2%80%93Sachs
Comment: @phoog Thanks I checked it out, amazing! Very interesting composition. & I found a couple of books (through Wikipedia sources & references), that actually do list the tuning fork as an Idiophone.   https://www.amazon.com/gp/aw/d/1884365086/ref=ya_aw_od_pi?ie=UTF8&psc=1


Append strings to pandas dataframe column with conditional

Question: I'm trying to achieve the following: check if each key value in the dictionary is in the string from column layers. If it meets the conditional, to append the value from the dictionary to the pandas dataframe.
For example, if BR and EWKS is contained within the layer, then in the new column there will be BRIDGE-EARTHWORKS.
Dataframe
mapping = {'IDs': [1244, 35673, 37863, 76373, 234298],
 'Layers': ['D-BR-PILECAPS-OUTLINE 2',
  'D-BR-STEEL-OUTLINE 2D-TERR-BOUNDARY',
  'D-SUBG-OTHER',
  'D-COMP-PAVE-CONC2',
  'D-EWKS-HINGE']}

df = pd.DataFrame(mapping)

Dictionary
d1 = {"BR": "Bridge", "EWKS": "Earthworks", "KERB": "Kerb", "TERR": "Terrain"}

My code thus far is:
for i in df.Layers
  for x in d1.keys():
    first_key = list(d1)[0]
    first_val = list(d1.values())[0]
    print(first_key,first_val)
    if first_key in i:
      df1 = df1.append(first_val, ignore_index = True)
      # df.apply(first_val)

Note I'm thinking it may be easier to do the comprehension at the mapping step prior to creating the dataframe.. I'm rather new to python still so any tips are appreciated.
Thanks!
Comment: can i see desired output of `df` to be precise?
Answer: Use Series.str.extractall for all matched keys, then mapping by dictionary with Series.map and last aggregate join:
pat = r'({})'.format('|'.join(d1.keys()))
df['new'] = df['Layers'].str.extractall(pat)[0].map(d1).groupby(level=0).agg('-'.join)
print (df)
      IDs                               Layers             new
0    1244              D-BR-PILECAPS-OUTLINE 2          Bridge
1   35673  D-BR-STEEL-OUTLINE 2D-TERR-BOUNDARY  Bridge-Terrain
2   37863                         D-SUBG-OTHER             NaN
3   76373                    D-COMP-PAVE-CONC2             NaN
4  234298                         D-EWKS-HINGE      Earthworks


How to search jobs that I've added through Google Cloud Talent Solution API

Question: I'm using Google Talent Solution API to create jobs under some companyName and these seem to be getting added when I'm listing through API yet they nowhere seem to appear on Google search results or Google Job search page.
The location of company & jobs are same to my current location. Is there any visibility issue (though I've added jobs with SHARED_WITH_PUBLIC visibility) or is there any other way to add jobs? Please let me know.
Answer: You can serve HTML pages to Google to have your jobs added to their index.
Here are docs on what data to add to a standard HTML page for job ads:
https://developers.google.com/search/docs/data-types/job-posting


Connect PC and headphones to digital piano

Question: It has become my hobby to write my own piano arrangements for songs I like, but due to my furniture arrangement, I couldn't connect my digital piano to my PC - until now.
Now I'd like to have just one pair of headphones to listen to the original song (from PC) and my own playing (from piano), sometimes simultaneously. My first thought was to connect the piano's line-out to the line-in of my PC, but there is a huge delay (feels like 500ms) that makes it impossible to play. Tinkering with the settings and installing ASIO4ALL and JACK didn't help enough because there still was a small delay - much better compared to the delay without ASIO, but it still made me uncomfortable to play.
So I bought an external audio interface (Behringer UCA222) which has a line-in for my piano, a monitor output for my headphones and a USB connection to my PC.
I don't think this is common, but my piano (Kawai CN-3) has a line-out which is not only controlled by the piano's master volume control, the line-out is also muted when I connect headphones. So I have to connect the interface's line-in to the piano's headphones output if I don't want to disturb my sleeping son because I can't mute the piano without also muting the line-out.
And now I have another problem, and I don't know whether it's the piano, the headphones, the audio interface, or the fact that I had to use the headphones output. When I play a bit louder, especially when I play many notes at once (e.g. glissando or series of 4-note chords with pedal), there is a scratch sound in my headphones which sounds like an overdriven/clipped audio signal. First I thought it must be the interface because I never had problems when the headphones were directly connected to the piano. But when I use Adobe Audition to record what I'm playing there is no clipping at all (all input levels set to 100%). Even if I turn down the piano's and the monitor's volume, there is sometimes a scratch while Audition shows a maximum level of -15 dB.
Unfortunately, I don't have another piano or even other headphones to try. Does anyone have an idea what I'm doing wrong?
Answer: First off; Behringer is garbage. Always has been, always will be. Your noise ("scratching") issue sounds like badly-written zero-latency monitoring drivers. Or, those phono inputs are almost certainly not grounded so they pickup stray voltage from (wherever).
Buy an m-audio (2 channels for about $100) or, if really squeezed for cash an ART ($60 or so). Definitely get 1/4 inch or xlr inputs and external psu (powerbrick) if possible. At that range, harder to get independent ground (3-pin power cable) but better than usb power for sure.
Comment: Hm, I just want to listen to my PC and my piano at the same time, without delay and scratches - no recordings. Do I really have to spend like $150 for equipment? Maybe there is a completely different solution?
Comment: Who said $150? $60-$100.

This is basic electronics. Audio-frequency sinusoidal signals don't do well in small boxes.

You could buy some small line mixer, but probably it would not be cheaper.
Comment: I meant $100 plus cables, external PSU. ART is hard to find in Germany and also around €100 (or I just didn't find the one you had in mind). Anyway, it was just an estimate. But it seems like there's no other way...
Comment: Yea I didn't realize you were overseas, sorry.  Anything that needs an external psu will include one. Cables are separate, though. External psu units are generally pricier - the m=audio 2x2 doesn't have one.
Comment: I know, audiophile persons and professionals are gonna stone me to death for this question, but can I use a gaming headset like the [Sennheiser GSP 300](http://en-de.sennheiser.com/gaming-headset-gsp-300) with the M-Audio 2x2 so I can use the headset for gaming and voice chat and the headphones part for my piano, too, without having to replug anything?
Comment: You can do whatever you want - its your money. You will need some small cheap adapters for the headphones and mic to connect to m-audio box. Real problem is that you will have to make it the default audio device in windows, and it may not use whatever processing is included by default in the consumer audio already in your computer. This may make games and movies sound different from what you are used to.

If you found my answer helpful please accept and/or upvote.
Comment: I already used the Behringer box as default device while it was connected. It was working perfectly and sounded as expected (or at least not surprisingly different). I guess the M-Audio won't be different for that matter. Thanks for all the info.


Using getUSerMedia AND webkitSpeechRecognition allow access x 2

Question: I am creating a site that uses two types of audio input... getUserMedia and webkitSpeechRecognition. Both functions are working fine but Chrome is popping up it's access security pop-up twice - which makes sense. Does anyone know how to have one access permission  handle both functions?
Cheers SO!

navigator.getUserMedia({audio:true}, gotStream, function(e) {
    alert('Error getting audio');
    console.log(e);
});

and...
var recognition = new webkitSpeechRecognition();

Answer: The only way to avoid asking for permissions multiple times is to make sure that your web page is using the https url. Then Chrome will remember your permissions and not show the pop-up again.
Answer: On Chrome 36 (and possibly earlier ones) I'm getting just one popup bar for both.


How to combine @Entity and @XmlRootElement in one class

Question: I am facing a situation that a REST service takes XML request and need to store the data in the request into database. The request XML basically gives values of a class that needs to be persisted.
For example, suppose I need to persist a class as follows:
@Entity
public class Person {
    @Id @GeneratedValue
    private Long id;
    private String firstName;
    private String lastName;
}

The request XML may look like this:
<?xml version="1.0" encoding="UTF-8"?>
<PersonInputs>
    <Input type="String" name="firstName">Foo</Input>
    <Input type="String" name="lastName">Bar</Input>
</PersonInputs>

Is it possible that I can use JAXB annotations to create a Person object and bind data from the request XML in a simple way? I am not familiar with JAXB for the moment, so I hope I can get some informed suggestions. Nevertheless, any input is greatly appreciated.
Comment: do you have the exact format of the xml?
Comment: @DebojitSaikia: If you are referring to a XSD, we don't have one. We probably should, but we have never gotten to it so far.
Answer: You can use this solution with additional class Input
@XmlAccessorType(XmlAccessType.FIELD)
public class Input
{
   @XmlAttribute
   private String type;
   @XmlAttribute
   private String name;
   @XmlValue
   private String value;

   public Input() {}

   public Input(String type, String name, String value)
   {
      this.type = type;
      this.name = name;
      this.value = value;
   }
}

and additional getters in entity
Variant 1
@XmlRootElement(name= "PersonInputs")
@XmlAccessorType(XmlAccessType.NONE)
public class Person
{
    @Id @GeneratedValue
    private Long id;

    private String firstName = "foo";

    private String lastName = "bar";

    // getters/setters

    @XmlElement(name= "Input")
    Input getFirstNameXML()
    {
       return new Input(String.class.getSimpleName(), "firstName", firstName);
    }

    @XmlElement(name= "Input")
    Input getLastNameXML()
    {
       return new Input(String.class.getSimpleName(), "lastName", lastName);
    }
}

Variant 2
@XmlRootElement(name= "PersonInputs")
@XmlAccessorType(XmlAccessType.NONE)
public class Person
{
    private Long id;

    private String firstName = "foo";

    private String lastName = "bar";

    // getters/setters

    @XmlElement(name = "Input")
    List<Input> getList() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException
    {
       return getInputs(this, "firstName", "lastName"); // fields names
    }
}

Util method getInputs
static List<Input> getInputs(Object thisObj, String ... fields) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException
{
   final List<Input> retVal = new ArrayList<Input>();
   for (String field : fields)
   {
      Field f = thisObj.getClass().getDeclaredField(field);
      f.setAccessible(true);
      retVal.add(new Input(f.getType().getSimpleName(), field, (String )f.get(thisObj)));
   }
   return retVal;
}


Index (or signature) of a pseudo-riemannian metric on manifold

Question: Let $(M , g)$ a $n$-dimensional pseudo-riemannian manifold. As $g(p)$ is a bilinear mapping from $T_pM \times T_pM$ to $\mathbb{R}$, we can get a basis
$$
{\left\{{\left(\frac{\partial}{\partial x_i}\right)}_p\right\}}_{i = 1}^n
$$
on $T_pM$ such that
$$
g(p)\left({\left(\frac{\partial}{\partial x_i}\right)}_p , {\left(\frac{\partial}{\partial x_j}\right)}_p\right) = 0
$$
for each $i , j \in \{1 , \ldots , n\}$ such that $i \neq j$. It allows us to define the index (or signature) of $g(p)$ because it is independent of the choice of basis in $T_pM$, a fact known classically as Sylvester's law of inertia.
Well, many texts talk about index of $g$ strightly, and define for instance riemannian metrics as pseudo-riemannian metrics which index coincide with the dimension of the manifold (or signature ($n , 0$) in this case).
How can I show that it is independent of the point $p$ in $M$? As it can be observed, I have not used neither $g(p)$ is non-degenerate or symetric nor the fact $T_pM \cong {\mathbb{R}}^n \cong T_qM$, as isomorphism of vector spaces ($p , q \in M$), for defining signature of $g(p)$ (for $p \in M$ fixed). Must I use one of these statements to show that the index of $g(p)$ and $g(q)$ coincide for each $p , q \in M$?
Answer: Let $v_1, \dots, v_n$ be a basis for $T_pM$ such that $g(p)(v_i, v_i) > 0$ for $i = 1, \dots, k$, and $g(p)(v_i, v_i) < 0$ for $i = k + 1, \dots, n$. We can extend this basis to a basis of local smooth vector fields $V_1, \dots, V_n$ for $TM|_U$ where $U$ is an open neighbourhood of $p$.
Now consider the functions $f_i : U \to \mathbb{R}$ given by $f_i(q) = g(q)(V_i|_q, V_i|_q)$. Note that $f_i$ is smooth and $f_i(p) = g(p)(V_i|_p, V_i|_p) = g(p)(v_i, v_i)$ which has a sign. For $i = 1, \dots, k$, let $U_i = f_i^{-1}((0, \infty))$ and for $i = k + 1, \dots, n$ let $U_i = f_i^{-1}((-\infty, 0))$. Then on $U' = U_1\cap\dots\cap U_k\cap U_{k+1}\cap\dots\cap U_n$ each $f_i$ has a sign. For any $q \in U'$, $f_i(q) > 0$ for $i = 1, \dots, k$ and $f_i(q) < 0$ for $i = k + 1, \dots, n$, so $g(q)$ has the same index of $g(p)$. That is, the index of $g$ is a locally constant integer-valued function and is therefore constant on each connected component of $M$.


Elemento com margin-left -100% continua sendo renderizado?

Question: Elementos com margin-left -100% continuam sendo renderizados ou o navegador entende que eles estão fora da "área de visão" e param de usar recursos do computador?
E quando eles estão com opacity: 0 e/ou visibility: hidden, isso também ocorre?
Comment: Só `display: none` para de "renderizar" *relativamente*, no DOM ainda existe e afeta alguns comportamentos, o que acontece é que ele não ocupa espaço.
Comment: Possível duplicata de [Qual a diferença entre display:none e visibility:hidden?](https://pt.stackoverflow.com/q/44678/3635)
Comment: @GuilhermeNascimento não acho que seja duplicata e achei essa discussão muito interessante. Tentei pesquisar se há alguma maneira de identificar com JS se o elemento está presente no DOM e sendo renderizado ou não, mas ainda não achei nada.
Comment: @AndersonCarlosWoss Só `display: none` não ocupa espaço, o resto tudo é técnica para "maquiar", claro que cada motor pode ter um esquema próprio de "otimização" para melhorar a performance conforme **"puder"**. Mas se quiser dividir e discutir cada detalhe ou técnica talvez eu retire o voto, ainda sim tenho quase certeza que só `display` tem efeito (menos na "interface DOM"). ;)
Comment: @GuilhermeNascimento sim, só o `display` tem efeito sobre isso, mas tem alguma forma prática da se mostrar isso além de olhar no inspetor do navegador? Tentei ver com JS mas não achei um meio de descobrir se determinado elemento estava ou não sendo renderizado . Deve haver alguma forma...
Comment: @AndersonCarlosWoss penso eu que renderizar seja totalmente relativo, no geral para o DOM tudo existe, o `none` só não "ocupa espaço", e quanto a renderizar é algo que pode variar de motor para motor, visando otimização dele próprio e da máquina do usuário. Eu pessoalmente aonde usei `display:none` quando havia muito conteudo percebi uma ligeira melhora (nos motores populares), mas isso não é uma afirmativa para todos motores, só analisando o source dos motores, creio eu. A resposta que já é apresentada me soa (opinião minha) como um "baita chute" sem certeza de nada.
Comment: Por isso que eu comentei que seria uma discussão interessante, pois imaginei que com JS poderia haver uma maneira de descobrir isso e até para comparar diferentes motores.
Comment: Talvez eu esteja enganado, a questão de renderização ocorre na interface que esta no núcleo, JavaScript não tem como ter acesso a isto, a não ser que exista uma API que informe, ainda sim acho que se algo assim existir não seria algo *standard*, pois cada motor gerencia a sua forma o que vai usar recursos visuais e cada um tem uma estratégia própria, resumindo a nível da camada "cliente" não creio que exista nada que possa ser feito, a nivel de núcleo e interação com as interfaces talvez seja possivel deduzir algo. Mas se desejam discutir sobre o repaint e aceleradores vou retirar meu voto.
Answer: Sim, ele renderiza.
Prova - https://jsfiddle.net/y1h5cmtc/
Por CSS criei uma transição do margin-left: -100% para o margin-left: -150%, e ele conseguiu encontrar a diferença, que é escrita na tela por Javascript.
Portanto, existem 2 processamentos gráficos diferentes no navegador: o Renderint e o Painting.
O Painting é processado quando alguma imagem é alterada na tela, e o Rendering quando é necessário recalcular algum atributo de um elemento qualquer, seja a posição, a cor, o tamanho, etc.
Nesse caso, o Rendering recalcula a posição do elemento, mas o Painting não exibe na tela, fazendo com que seja processado apenas pelo Rendering.
Se você abrir a aba de "Performance" do DevTools do Chrome, vai perceber a diferença na execução do Painting se, na transição, substituir o margin-left: -150% por margin-left: 50%, fazendo com que exiba na tela a div
https://jsfiddle.net/y1h5cmtc/1/


Prove the inequality - inequality involving surds

Question: Prove that for $r$ greater than or equal to 1:
$\displaystyle 2(\sqrt{r+1} - \sqrt{r}) < \frac{1}{\sqrt{r}} < 2(\sqrt{r}-\sqrt{r-1})$
Any help on this would be much appreciated.
Answer: Hint: $\frac{1}{\sqrt{r}}=\frac{2}{\sqrt{r}+\sqrt{r}}$ and $r-1<r<r+1$.
Comment: **Subhint:** What are $\frac{1}{\sqrt{r}+\sqrt{r-1}}$ and $\frac{1}{\sqrt{r+1}+\sqrt{r}}$?
Comment: I'd be curious to see a full method that uses this hint.
Answer: Let $g(x) = \frac1{\sqrt x}$, and $g(x)$ is strictly decreasing. Then this inequality holds:
$$\int_{r-1}^rg(x)\ dx > 1\cdot g(r) > \int_{r}^{r+1}g(x)\ dx\\
\int_{r-1}^r\frac{dx}{\sqrt x} > \frac{1}{\sqrt r} > \int_{r}^{r+1}\frac{dx}{\sqrt x}\\
2(\sqrt r - \sqrt{r-1}) > \frac{1}{\sqrt r} > 2(\sqrt{r+1} - \sqrt r)$$
Comment: A very insightful solution! Thanks
Answer: Let $f(x) = \sqrt x$. By mean value theorem, there exist $q\in (r-1,r)$ and $s \in (r, r+1)$ that satisfy
$$f(r) - f(r-1) = f'(q),\quad f(r+1)-f(r) = f'(s).$$
By the concavity of $f$, since $q<r<s$,
$$\begin{array}{rcl}
f'(q) >& f'(r) &> f'(s)\\
f(r)-f(r-1) >& f'(r) &> f(r+1) - f(r)\\
\sqrt{r}-\sqrt{r-1} >& \dfrac1{2\sqrt r} &> \sqrt{r+1} - \sqrt{r}\\
2(\sqrt{r+1}-\sqrt{r}) <& \dfrac1{\sqrt r} &< 2(\sqrt{r} - \sqrt{r-1})
\end{array}$$