Changing and setting button background color and also comparing clicks on button pressed using switch and case

Question: I have been working on an examination app for a while now,
Please am stock with setting buttons background colors as well comparing values on every button pressed.
Below is my code, please where am I getting it wrong?
It gives me no error and don't satisfy the desired task.
<code>    switch (V.getId()) {
    case R.id.option1:
        Button s2 = (Button) findViewById(R.id.option2);
        actual = bOption1.getText().toString();
        s2.getBackground().setColorFilter(0xFF33FF33, PorterDuff.Mode.MULTIPLY);
        bOption2.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        bOption3.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        bOption4.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        aoption1 = 1;
        aoption2 = 0;
        aoption3 = 0;
        aoption4 = 0;
        break;
    case R.id.option2:
        actual = bOption2.getText().toString();
        bOption1.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        bOption2.getBackground().setColorFilter(0xFF33FF33, PorterDuff.Mode.MULTIPLY);
        bOption3.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        bOption4.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        aoption1 = 0;
        aoption2 = 1;
        aoption3 = 0;
        aoption4 = 0;
        break;
    case R.id.option3:
        actual = bOption3.getText().toString();
        bOption1.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        bOption2.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        bOption3.getBackground().setColorFilter(0xFF33FF33, PorterDuff.Mode.MULTIPLY);
        bOption4.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        aoption1 = 0;
        aoption2 = 0;
        aoption3 = 1;
        aoption4 = 0;
        break;
    case R.id.option4:
        actual = bOption4.getText().toString();
        bOption1.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        bOption2.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        bOption3.getBackground().setColorFilter(0x33FF33FF, PorterDuff.Mode.MULTIPLY);
        bOption4.getBackground().setColorFilter(0xFF33FF33, PorterDuff.Mode.MULTIPLY);
        aoption1 = 0;
        aoption2 = 0;
        aoption3 = 0;
        aoption4 = 1;
        break;
    case R.id.confirm:
        tvexplain.setText(explain);
        ahint.setVisibility(View.VISIBLE);
        proceed.setVisibility(View.VISIBLE);
        proceed.setText(continued);
        confirm.setVisibility(View.INVISIBLE);
        confirm.setLayoutParams(new LayoutParams(3, 1));
        if(actual.equals(null)){ }else{
            if(actual.equals(answer)){
                if(aoption1 == 1){
                    bOption1.getBackground().setColorFilter(0xFF66FF66, PorterDuff.Mode.MULTIPLY);
                }else if(aoption2 == 1){
                    bOption2.getBackground().setColorFilter(0xFF66FF66, PorterDuff.Mode.MULTIPLY);
                }else if(aoption3 == 1){
                    bOption3.getBackground().setColorFilter(0xFF66FF66, PorterDuff.Mode.MULTIPLY);
                }else if(aoption4 == 1){
                    bOption4.getBackground().setColorFilter(0xFF66FF66, PorterDuff.Mode.MULTIPLY);
                }
            }
        }
        break;
    }
</code>
Comment: As long as your views `R.id.option*` are contained in the currently active layout your switch should work fine. You can set a breakpoint or a log call somewhere in your switch cases to make sure they are getting hit. For setting your background, try just doing something like `bOption2.setBackgroundColor(Color.parseColor("#33FF33FF"));`
Comment: Prefer an [SSCCE](http://www.sscce.org) over a wall of code!
Comment: Sure, all buttons were initialised in my onCreate function and also when I tried setting button background color this way, it ends up destroying the look and feel of the button.
I will still try some other techniques and will update it here as well.
Thanks for the response all and more options will be highly appreciated.
Answer: Why don't you use Android Art Studio to create different colors for your buttons?


How to create database in Hibernate at runtime?

Question: I'm using Hibernate tenancy and every time user logs I'm changing database to his username (SQLite). Sadly sometimes the database does not exists and I need to create it.
The problem is that I don't know how to create all tables in database at runtime.
Normally Hibernete creates for me db with this:
<property name="hibernate.hbm2ddl.auto">update</property>

Comment: Create a new `SessionFactory` from scratch just like you create the initial one?
Comment: session = sessionFactory.withOptions().tenantIdentifier("tenancy_id").openSession(); <- but where I should add this?
Comment: I don't think the database update runs when you open a session. It runs when you create a `SessionFactory`. When switching databases, you'll have to get rid of the old factory, and create it anew. I have no idea *where* to do this because I have no idea where you're doing it *now*.
Comment: I hope it helps you. It works for me. http://stackoverflow.com/questions/21069687/hibernate-auto-create-database/26706954#26706954
Answer: Did you try the value create instead.

A value of create will create your tables at sessionFactory creation, and leave them intact.
A value of create-drop will create your tables, and then drop them when you close the sessionFactory.

That would be
<property name="hibernate.hbm2ddl.auto">create</property>

More infornation here and here
Or there could be a dialect problem
Comment: The problem is that database is created at runtime (I'm using tenance)
Answer: You can create database at run time by adding createDatabaseIfNotExist=true parameter in DB connection URL.
For more information check the SO Link !
Answer: You can use the SchemaExport for this to export the entities you want to create in your newly created database right after you created the database. the basic steps are below. How you get the properties for your config does not really matter.
    Configuration config = new Configuration();
    config.addAnnotatedClass(Class1.class);
    config.addAnnotatedClass(Class2.class);
    config.addAnnotatedClass(Class3.class);
    <set all hibernate properties/datasource here>
    SchemaExport schema = new SchemaExport(config);
    schema.create(true, true);

Javadocs are here: http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/tool/hbm2ddl/SchemaExport.html
For options of setting upt the configuration look here. http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/cfg/Configuration.html
Edit:
I guess a remark that has to be added is that it is considered bad practice to let hibernate handle DB/SCHEMA/TABLE creation in a production environment. Depending on the needs and the viability it might be better practice to save prepared SQL statements for this, or even do it manualy by a DB admin. But since we are all lazy I guess thats not often going to happen. ;D
Comment: Can I get my classes from hibernate.cfg.xml? Like config.loadAnnotatedClassFromXML()?
Comment: Yes. Just pick the method that suist you best from here: http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/cfg/Configuration.html. You probably want to look into addClass() or addFile().


How to specify directory where my reference git repos live

Question: Our company has reference git repositories available via NFS for some remote repositories I am cloning using ssh.
Is there a .gitconfig setting that will tell git to look here for a reference repo?
The git command I am executing is:
git clone ssh://remote-machinename/repos/repo.git --reference ~otheruser/references/repo.git

I'd like to automatically add --reference ~otheruser/references/repo.git when I type git clone ssh://remote-machinename/repos/repo.git, but make it flexible to match other repository names. Is this something I can do with insteadOf magic?
Answer: You would need to deplay a git wrapper script which would clone, adding the name of the repo to the reference part, using --reference-if-able:
git clone ssh://remote-machinename/repos/$1 --reference-if-able ~otheruser/references/$1

The idea being, as mentioned in git clone --reference:

When using the --reference-if-able, a non existing directory is skipped with a warning instead of aborting the clone.


Why should the last tag be fixed in CRF?

Question: In the tutorial, it is said that:

Let v range over the tags. Define U(k, v) to be the score of the best
  sequence of tags from 1 to k, where tag k is required to be v. This is
  a maximization over k −1 tags because tag number k is fixed to have
  value v

It is very confusing that why should the Kth tag be fixed?
Comment: v is the STOP tag, and the sequence needs to end with a STOP tag.
Answer: I learned from here that the first and last tokens are all fixed.


Cannot calculate Markov chain steady state

Question: currently I have a markov chain and need to calculate the steady state of the markov chain, but however the values does not converge.
I'm using python and numpy to calculate the transition state.
self.transition_state = np.array([[1/43, 2/43, 12/43, 0, 13/43, 5/43, 10/43],
                                [5/52, 8/52, 13/52, 0, 16/52, 8/52, 2/52],
                                [12/475, 16/475, 177/455, 2/475, 216/475, 40/475, 12/475],
                                [0, 0, 4/7, 0, 2/7, 1/7, 0],
                                [16/536, 13/536, 214/536, 5/536, 251/536, 26/536, 11/536],
                                [2/97, 5/97, 40/97, 0, 32/97, 12/97, 6/97],
                                [7/47, 8/47, 16/47, 0, 5/47, 5/47, 6/47]])

self.start_state = np.array([0, 0, 0, 0, 1, 0, 0])

for i in range(500):

    self.start_state = np.dot(self.start_state, self.transition_state)

Answer: The matrix that you used is not a valid stochastic matrix.
I believe you made a typo at $(3,3)$-entry where it should be $\frac{177}{4\color{red}75}$.
import numpy as np

class solution():
    def __init__(self):
        self.transition_state = np.array([[1/43, 2/43, 12/43, 0, 13/43, 5/43, 10/43],
                                        [5/52, 8/52, 13/52, 0, 16/52, 8/52, 2/52],
                                        [12/475, 16/475, 177/475, 2/475, 216/475, 40/475, 12/475],
                                        [0, 0, 4/7, 0, 2/7, 1/7, 0],
                                        [16/536, 13/536, 214/536, 5/536, 251/536, 26/536, 11/536],
                                        [2/97, 5/97, 40/97, 0, 32/97, 12/97, 6/97],
                                        [7/47, 8/47, 16/47, 0, 5/47, 5/47, 6/47]])
        self.start_state = np.array([0, 0, 0, 0, 1, 0, 0])
        for i in range(500):

            self.start_state = np.dot(self.start_state, self.transition_state)
            print(self.start_state)

solution()

and I obtain
[0.03420606 0.04137862 0.37865691 0.00556449 0.42559945 0.07719859
 0.03739588]

Comment: thanks. i was losing my mind over this


convergence in probability (MLE)

Question: Can someone please explain what the following phrase actually implies:
  $\mathbf{\hat{θ}}$ converges to $\mathbf{θ}$ in probability with order $\mathbf{\hat{θ}}−\mathbf{θ}=O_p (n^{-\frac{1}{2}})$  ?
 ($\mathbf{\hat{θ}}$ is the maximum likelihood estimator)
Comment: See the [wikipedia page](https://en.wikipedia.org/wiki/Big_O_in_probability_notation#Big_O:_stochastic_boundedness): for any $\epsilon>0$ there exists $M>0$ such that $P(\sqrt{n}|\hat{\theta}_n - \theta| > M) < \epsilon$ for all large $n$. (Thanks kimchi lover for the correction.)
Comment: @angryavian : There's still the matter of the meaning of $O_p(n^{-1/2}). \qquad$
Answer: For a sequence of random variables $X_n$ (such as your $\hat \theta_n-\theta$) to be $O_P(1)$ means it is tight: for each $\epsilon>0$ there is a compact  set $K$ such that $P(X_n\in K)>1-\epsilon)$ for all $n$.  To say $X_n=O_P(1/\sqrt n)$ is to say that $\sqrt n X_n = O_P(1)$.  One way this can happen is if $\sqrt n X_n$ converges in distribution (in a statistics context, probably to a gaussian limit) but it can happen that one subsequence of $\sqrt n X_n$ has one distributional limit and another subsequence has another.
Stochastically bounded or bounded in probability  are alternative terms for $O_P(1)$. The notation seems to be due to Mann and Wald in 1943; see this for more on this topic.

convergence in probability (MLE)


how to count how many lines each function has in a Python file?

Question: I'm doing research on software engineering.
I need to measure how many lines each function or class has in each file.
Another interesting metric would be the number of functions and the cyclomatic complexity of each one.
Comment: Does this answer your question? [Good way to count number of functions of a python file, given path](https://stackoverflow.com/questions/37514636/good-way-to-count-number-of-functions-of-a-python-file-given-path)
Answer: You can do something like this
<code>import inspect

def test(param1, param2):
    print(param1, param2)
    print(1+1)

inspect.getsource(test)
# 'def test(param1, param2):\n    print(param1, param2)\n    print(1+1)\n'

inspect.getsource(test).count("\n")
# 3
</code>


Reindexing rows by reversed column values

Question: I have this df, where inverted column values are far apart from each other, like so:
            Team     Adversary      Home
0   Internacional   Bahia           Home
1        Flamengo   Grêmio          Home
...
18         Grêmio   Flamengo        Away
19          Bahia   Internacional   Away

For every
tuple1 = ('Team', 'Adversary') and tuple2 = ('Adversary', 'Team')

where
tuple1[0] == tuple2[0] and tuple1[1] == tuple2[1]

how do I reorder the rows, ending up with:
            Team     Adversary      Home
0   Internacional    Bahia          Home
1          Bahia     Internacional  Away
2        Flamengo    Grêmio         Home
3          Grêmio    Flamengo       Away
...

Comment: Please explain better how do you want to reorder the rows
Comment: @gtomer is it clearer now?
Answer: Use np.sort to sort the values of Team and Adversary along axis=1, then using sort_values sort the dataframe based on this sorted columns x and y:
df['x'], df['y'] = np.sort(df[['Team', 'Adversary']], axis=1).T
df = df.sort_values(['x', 'y'], ignore_index=True).drop(['x', 'y'], 1)

Result:
print(df)

            Team      Adversary  Home
0  Internacional          Bahia  Home
1          Bahia  Internacional  Away
2       Flamengo         Grêmio  Home
3         Grêmio       Flamengo  Away

Comment: `KeyError: "None of [Index(['x', 'y'], dtype='object')] are in the [columns]"`
Comment: Which pandas version are you using?
Comment: `pandas   0.25.3`
Comment: Hmm..that;s why you are getting error because multiple column assignment is not supported in version `0.25`..let me edit the solution..
Comment: @8-BitBorges please check now.
Comment: `ValueError: too many values to unpack (expected 2)`, my dtaframe has many other columns...
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/220982/discussion-between-shubham-sharma-and-8-bit-borges).
Answer: You confused me there for a second by using the word 'grouping'.
The easiest way to do this is to use the fact that combining teams names from Team and Adversary column have the same set of letter.
df.combo=df.Team+df.Adversary
df.combo=["".join(sorted(list(i)) for i in df.combo]

what this does -for example- is make sure that the combination of "Internacional" and "Bahia" is always ['B', 'I', 'a', 'a', 'a', 'a', 'c', 'e', 'h', 'i', 'i', 'l', 'n', 'n', 'o', 'r', 't'] or 'BIaaaacehiilnnort' no matter which ones occurs first.
Essentially you are using the unique letters content of the sorted letters combination as a unique id.
Now sort using the combo column
df = df.sort_values(by="combo", ascending=True).reset_index(drop=True)

finally drop the combo column
df = df.drop(["combo"], axis=1)


"init_dgelsd failed init" When using import numpy as np

Question: I am trying to run this simple code
import numpy as np

my_first_array = np.array([1, 2, 3,4,5])

my_first_array([1, 2, 3, 4, 5])

I believe I am using python 3.9 as i just bought this computer and downloaded the newest version.
But keep getting the error code:
Traceback (most recent call last):
  File "/Users/oledy/Documents/Skole/Dat200/test.py", line 1, in <module>
    import numpy as np
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/numpy/__init__.py", line 286, in <module>
    raise RuntimeError(msg)
RuntimeError: Polyfit sanity test emitted a warning, most likely due to using a buggy Accelerate backend. If you compiled yourself, see site.cfg.example for information. Otherwise report this to the vendor that provided NumPy.
RankWarning: Polyfit may be poorly conditioned

Answer: If you care to read up on the issue here is where I found the solution below.
rm -v ~/Library/Caches/pip/wheels/*/*/*/*/*numpy* # clear the pip wheel cache of any built numpy wheels
brew install openblas # make sure OpenBLAS is installed
# activate your virtualenv
OPENBLAS="$(brew --prefix openblas)" pip install numpy # let numpy's setup.py know where OpenBLAS is installed


Is SVM RBF applied to both classes?

Question: Lets say i have following 1D data (position on x), color is target class and I need a classifier which classifies green from red:

I decided to use SVM. Data is clearly not linearly separable, so i need to map it to higher dimensional space.
The question is should the transformation be applied to both green and red classes, or should i apply it just to one class? Look at the following image where i applied transformation only to red points. The problem is, when i apply it just to one class as on following image (and use gaussian radial basis function, then set the hyperplane), it is very similar to KNN, and it looks like that I misunderstood RBF concept.

 But if i modified all the data that way, then it would be just shifted to y = 1 position and still would not be linearly separable. So what is the correct way of transformation to higher dimensional space?
Answer: You've just plotted RBF similarity measures for each point, not the transformations. RBF kernel maps the data into infinite dimensional space, so you won't be able to actually visualize it. Kernel defines a similarity matrix that you can build your SVM onto. SVM doesn't need the explicit mapping in its optimization procedure, i.e. in its Lagrangian formulation. This is known as kernel trick. Here is an example mapping for RBF kernel.

Is SVM RBF applied to both classes?


Induction: If $a+1/a$ is an integer, then so is $a^t+1/a^t$ for $t\in\mathbb N$

Question:
$a$ is in $\mathbb{R}$ but not equal to $0$, and $a+\dfrac{1}{a}$ is integer, $a^t+\dfrac{1}{a^t}$ is also an integer for all $t\in\mathbb N$.

If $\displaystyle a+\frac1a$ is an integer then $\displaystyle \left(a+\frac1a\right)^2,\left(a+\frac1a\right)^3, \ldots $ are integers.
Maybe induction on $$a^{t+1} + \frac1{a^{t+1}} = \left(a^t+\frac1{a^t}\right)\left(a+\frac1a\right) - \left(a^{t-1}+\frac1{a^{t-1}}\right)$$
I'm having a problem doing the induction for this problem, any help will be appreciated.
Comment: You're basically done already. The right-hand side is a difference of two integers (by inductive hypothesis), so it's an integer.
Comment: By induction hypothesis
Comment: @PatrickStevens Ah, but how do we know that $\left(a^t+\frac1{a^t}\right)$ is an integer?
Comment: HINT: If $a+1/a= b$ then $a^2+1/a^2=b^2-2$ and $a^3+1/a^3=b^3-3b.$
Comment: Possible duplicate of [Proving that $\frac{\phi^{400}+1}{\phi^{200}}$ is an integer.](http://math.stackexchange.com/questions/936479/proving-that-frac-phi4001-phi200-is-an-integer)
Comment: @GCab Set it equal to whatever integer you want and you get a quadratic equation in $k$ with real roots if $k\geq 2$.
Comment: @GCab in the proof question, a is an element of Real numbers.
Comment: @Monkleys: actually $t$ can be in $\mathbf Z$
Answer: Your method is correct. The inductive hypothesis is "$(a^i+a^{-i})$ is an integer for all $i \leq t$". You will use this three times in each induction step: for $i=t$, for $i=1$, and for $i=t-1$.


Help rearranging algebraic expression?!

Question: In the following relationship x and $\delta_S$ are unknowns:
$$\delta_f = \delta_S-(\delta_S-\delta_o)\exp\left[-(1+mx)\frac{It}{V}\right]$$
I need to solve for x and have the following relationship for $\delta_S$:
$$\delta_S =\frac{\delta_{in}+mx\delta^*}{1+mx}$$
Therefore: $$\delta_f = \bigg(\frac{(\delta_{in}+mx\delta^*)}{(1+mx)}\bigg)-\bigg(\frac{(\delta_{in}+mx\delta^*)}{(1+mx)}-\delta_i\bigg)\exp\bigg[-(1+mx)\frac{It}{V}\bigg]$$
Honestly I have no idea where to begin isolating x once I start taking the natural log...
Answer: You cannot isolate $x$ and you will need some numerical method.
If I had to do it, I would define $y=(1+mx)$ to make
$$\delta_f = \delta_S-(\delta_S-\delta_o)\exp\left[-y\frac{It}{V}\right]$$
$$\delta_S =\frac{\delta_{in}+mx\delta^*}{1+mx}=\frac{\delta_{in}-\delta^*+y\delta^*}{y}=\delta^*+\frac{\delta_{in}-\delta^*}y$$ Use Newton method.
In fact, I suppose that there could be an "explicit" solution in terms of the generalized Lambert function (have a look at equation $(4)$ in the paper).

Help rearranging algebraic expression?!


How to play same note with left and right hand

Question:
This is a piano sheet. The second line is in bass clef. The blue one and the green one are same. How should I play this two?
Should I  pick up my left hand and play the blue one?
Comment: O.k., so what's the key signature?
Comment: @LoveIsHere This "lets say" is quite pointless here. I would give an answer to that case (as this scenario is very common in organ music actually), but I don't want to answer so unclear question, and I doubt that E and Fb appear simultaneously.
Comment: @LoveIsHere - the way I see it is that when a question is asked, as much relevant information as is needed should be provided by the poser. Here, it's insufficient.
Comment: What do you mean "the blue one and the green one are [the] same"?
Comment: But lets say its in c major key - if the note in the trebble is Fb and in the bass cleff is E how would you play it? I also seen scores like that with same notes it is not clear how would you play similar note that apear in both cleffs simultanesly
Comment: @LoveIsHere - it's certainly not in C, and there's no point in surmising. If the OP needs an answer, the question needs to provide relevant information - which is lacking right now.
Comment: @Tim I thought you could address that. It was definitely not surmising it was raising a very relevant question. maybe I will address this in a new question.
Comment: @LoveIsHere - 'let's say it's in C  major key *is* surmising! It's most likely in Db, but why guess. It's up to the OP to help out here.
Comment: You could just have said to put it in a new question. and write it more kindly.
Answer: Without the key signature, it's not a total certainly, but it appears that the treble clef note is Fb, which is in fact the white key to the left of F,a.k.a. 'E', while the bass clef note is either E or Eb. If it's Eb, then it's a different note, and will be held on. If it's E, then I can't think why the r.h. note would need to be written as anything but E, certainly not Fb. It rather depends on the key signature though...
Comment: The signature almost certainly has flats, since otherwise it wouldn't make sense to notate both a B and a C flat for the right hand.
Answer: I also notice the C-flat later on in the bar, which is enharmonically equivalent to a B natural. Since it is preceded immediately by a B, it is almost certain that there is at least a B-flat in the key signature. But as the response above says, it would be awkward if the E in the left hand was not a flat, because it would otherwise not be technically playable. So I am pretty certain that there should be an E-flat in the key signature as well. Also accounting for the double bar which indicates this bar is the beginning of a section or theme, I think the key would be either B-flat major or E-flat major, but it could also be a modulation to D-flat minor (which has a F-flat), but as before, I cannot guarantee a firm response until you tell or show us what the key signature is.
Answer: I suspect it's in 5 flats.  Then it all makes perfect sense.
Comment: Because the last four notes in RH spell a natural E-flat minor scale - which has six flats including C-flat, but not F-flat; the F-flat there is merely an enharmonic respelling of E-natural to avoid clashing with the E-flat in LH.


Could it be an Nginx bug when using regex?

Question: I'm cleaning up our configuration so I thought of using regex since I'll be able to remove tons of lines. I'm wondering why the new rule is not working properly or works differently.
The rule below is currently in our dev, stage and prod. It works pretty well. We have many rules that looks like this but the second path is what varies.
location /app/sss/cifs/ {
  proxy_pass http://int-svr/sss/s3/dev/app/sss/cifs/;
}

I added a new rule(shown below) and I commented out the above
location ~ ^/app/(...)/cifs(.*) {
  proxy_pass http://int-svr/$1/s3/dev/app/$1/cifs$2;
}

When using the original rule, and my http call is http://localhost/app/sss/cifs, I am able to see the page. However, if I use the new rule which uses regex, the url that I typed on my browser will change after visiting the page and I'll get a 404. The url will become http://localhost/sss/s3/dev/app/sss/cifs. It's weird that the value on the proxy_pass is disclosed.
Btw, if I'm using the regex rule and my call is http://localhost/app/sss/cifs/, it will work. The difference is that this link has a trailing slash. In old rule, both http requests with or without trailing slash, it works.
Any ideas?
Basically, I want the behavior of my original rule but using regex.
Comment: what about `location ~ ^/app/(.)/cifs(.*)` ?
Comment: why only a single dot? I mean, the character there will always be 3 characters
Comment: yep, test it ;)
Comment: I actually use this, return 200 "http://int-svr/$1/s3/dev/app/$1/cifs$2" and the output is correct but it becomes weird when proxy_pass is used
Comment: ok, I'll test your regex
Comment: It didn't work. I got a 404 Check this out - http://imgur.com/a/zVFWN
Comment: on access.log, this is what it logged - 172.20.49.163 - - [22/Jul/2016:02:16:20 +0000] X-Forward-Scheme:http   X-Forward-For:192.168.203.83, 172.20.49.163   request: GET /app/sss/cifs HTTP/1.1   cookies: -   status-code: 404
Comment: What is the exact url you are typing, and what is the exact url you are trying to proxy ?
Comment: It's above on my post. Those are the exact links but internal to our network
Comment: I can access the other server using curl and I am able to get a file
Comment: `location ~ ^/app/(...)/cifs(.*)` then `proxy_pass http://int-svr/$1/s3/dev/app/$1/cifs$2/` ?
Comment: I restored my old rule and captured the traffic. I put the new rule then captured the traffic. The nginx response for on /sss/s3/dev/app/sss/cifs using GOOD rule, I get a 200 OK. But the response when using the regex rule on that kind of path, I get a 404
Comment: So I guess the problem is that this rule `location ~ ^/app/(...)/cifs(.*) {` or this `location ~ ^/app/(.*)/cifs(.*) {` is not used when request is `/sss/s3/dev/app/sss/cifs` I think that's the culprit. It's because `dev` string is not in my rule. However, using the original rule, the proxy_rule works well and I don't have a rule that has `dev` in location
Comment: I give up. I'll just use the original rule. The confusing thing is that why is Nginx giving my browser the path that is in proxy_pass. I think that's a bug
Comment: I finally figured it out. The caret was the culprit. The backend server responded with a different path that didn't start with /app. So that rule got ignored. Removing the caret, the rule was used again.
Comment: please write an answer yourself and add the solution, so anybody having the same problem gets a clear answer.
Answer: There are two potential issues in your question.
The prefix location (your first rule) and the regex location (your second rule) have different evaluation orders. So it is easy to replace a prefix location with a regex location and find that its precedence order within the configuration file has changed. See this document for details.
The second problem is that your regex rule accepts URIs that finish after the .../cifs sequence (i.e. without a trailing /), whereas the original rule prevents it.
So,
In the case of the first rule, when presented with /app/sss/cifs, nginx will issue a redirect and add a trailing / (either explicitly or implicitly).
In the case of the second rule, this URI gets passed upstream, which also redirects, but with the wrong result.
You could try protecting the upstream by modifying your regex and adding a trailing / to cifs:
location ~ ^/app/(...)/cifs(/.*) { ... }

I have placed in inside the capture so that the rewrite statement is the same.
If this breaks the /app/sss/cifs URI, you could explicitly add a trailing /, bu adding a new rule to take care of that specific case:
location ~ ^(/app/.../cifs)$ { return 302 $1/; }

Comment: I got it working last night. I mentioned it above. The problem was the caret. I had to remove it. It was the S3 bucket web server that was prepending the path to the original path I submitted.


Conditional facet specification with ggplot2

Question: I am making several plots, which for flexibility I am planning to wrap in functions, and as part of that I would like to specify faceting for those plots according to some condition.
Specifically, I have a list of grouping_vars (per-specified elsewhere) that I use to perform several other manipulations on the data. I'd like to have my plotting functions be able to automatically use a facet_wrap if there's only one grouping_var, or if there are two or more variables specified in grouping_var, use the first two for facet_grid.
So for instance, if the basic plot is something like
mtcars %>% ggplot() + geom_point(aes(x = hp, y = mpg))

If I specify grouping_vars <- c("cyl"), I'd like to get, in effect,
mtcars %>% ggplot() +
    geom_point(aes(x = hp, y = mpg)) +
    facet_wrap(~cyl)

Whereas if I specify grouping_vars <- c("cyl", "carb") I'd like to get
mtcars %>% ggplot() +
    geom_point(aes(x = hp, y = mpg)) +
    facet_grid(vars(cyl), vars(carb))

Based on some other answers I've tried doing this:
mtcars %>% ggplot() +
    geom_point(aes(x = hp, y = mpg)) +
    {if(length(grouping_vars==1)) facet_wrap(grouping_vars[[1]])} +
    {if(length(grouping_vars>=2)) facet_grid(vars(grouping_vars[[1]]), vars(grouping_vars[[2]]))}

but it doesn't seem to work. Among other things, if there's only one element in grouping_vars, it gives me Error in grouping_vars[[2]] : subscript out of bounds.
Is there a way to conditionally specify faceting like this?
Answer: Following the advice in the vignette here, we should be able to use vars() with the .data pronoun as follows:
library(ggplot2)

plot_mtcars <- function(grouping_vars = NULL) {
  p <- ggplot(mtcars) +
    geom_point(aes(x = hp, y = mpg))

  if (length(grouping_vars) == 1) {

    p <- p + facet_wrap(vars(.data[[grouping_vars]]))

  } else if (length(grouping_vars) == 2) {

    p <- p + facet_grid(vars(.data[[grouping_vars[1]]]),
                        vars(.data[[grouping_vars[2]]]))

  }
  p
}

plot_mtcars("cyl")

plot_mtcars(c("cyl", "vs"))

Created on 2023-03-14 by the reprex package (v2.0.0)
Answer: We can create a custom function, which uses get to pass the variables to ggplot.
conditional_facet <- function(data, x, y, grp) {
  require(ggplot2)
  require(dplyr)
  data %>%
    ggplot() +
    geom_point(aes({{x}}, {{y}})) -> gp

  if(length(grp) == 1) {
    gp + facet_wrap(~get(grp)) -> gp_out
  } else if (length(grp) == 2) {
    gp + facet_grid(vars(get(grp[1])), vars(get(grp[2]))) -> gp_out
  } else {
    gp -> gp_out
  }
  return(gp_out)
}

grouping_vars <- c("cyl")
conditional_facet(mtcars, hp, mpg, grouping_vars)

grouping_vars <- c("cyl", "carb")
conditional_facet(mtcars, hp, mpg, grouping_vars)

Created on 2023-03-14 by the reprex package (v2.0.1)


Every element is radical in a field extension.

Question: Let $L/K$ be an algebraic field extension. Suppose for each $x\in L$, there exists an integer $n>0$ such that $x^n\in K$, where $n$ may depend on $x$. If the characteristic of $K$ is zero, does it follow that $L=K$?
Thanks.
Comment: @Arturo Magidin, thank you.
Comment: To prove it false, it suffices to consider $K$ to be an algebraic extension of $\mathbb{Q}$, and $L$ finite over $K$. I think we can even reduce it to $L$ being a cyclic extension of prime order.
Comment: (I retract my hypothesis we can reduce it to being cyclic: the argument I had in mind doesn't work)
Answer: Here is a very incomplete idea. Perhaps someone can finish it, or point out why it won't work.
Let $a\in L\setminus K$, and let $n>1$ be the smallest number such that $a^n\in K$. Then the minimal polynomial for $a$ over $K$ divides $x^n-a^n$. Then $(x-1)^n-a^n$ is a polynomial having $a+1$ as a root, so that the minimal polynomial for $a+1$ must divide $(x-1)^n-a^n$.
But we also know that $a+1$ is the root of some polynomial of the form $x^m-(a+1)^m$, so the minimal polynomial for $a+1$ must also divide $x^m-(a+1)^m$. The roots of $(x-1)^n-a^n$ are
$$1+\zeta_n^ka,\quad 0\leq k<n$$
and the roots of $x^m-(a+1)^m$ are
$$\zeta_m^\ell(a+1),\quad 0\leq \ell<m.$$
If
$$(1+\zeta_n^ka)=\zeta_m^\ell(a+1)$$
then
$$a=\frac{1-\zeta_m^\ell}{\zeta_m^\ell-\zeta_n^k}.$$
If we can show that there must always be at least one $a\in L\setminus K$ that can't be expressed this way, for any algebraic extension $L/K$ of characteristic zero fields, then we're done; I suppose it seems plausible, but I don't see any way of proving such a thing.
Comment: That does show that $L\setminus K$ must be algebraic over $\mathbb{Q}$. As we can reduce to the case where $L$ is generated by a single element, it reduces to the case where $K,L$ are finite extensions of $\mathbb{Q}$. Then, as $L$ (and its normal closure) is a finite extension of $\mathbb{Q}$, it contains only finitely many roots of unity. So your expression for $a$ can only take finitely many values. So $L\setminus K$ is finite and, as $K$ is infinite, this means that $L=K$. QED.
Comment: @George: That looks like it does it! I can incorporate that into my answer, but I really think you deserve some upvotes - maybe post that comment as a separate answer, and people can vote both of us up?
Comment: Ok, I will. Maybe tomorrow morning as its getting late now.
Answer: Yes, it does follow that $L=K$.
Let's start by supposing that $L\not=K$ so that we can choose some $a\in L\setminus K$. We can express $a$ in terms of roots of unity (as in Zev Chonoles' answer). The minimal polynomial over $K$ of $a$ is of degree greater than 1 so, as we are assuming nonzero characteristic, it must have at least two roots. Let $\tilde a\not=a$ be any other root, which will lie in the normal closure of $L/K$. As $a^n\in K$ for some $n > 0$, the minimal polynomial of $a$ divides $X^n-a^n$ and, hence, $\tilde a^n=a^n$. So, $\tilde a=\zeta a$ for an $n$th root of unity $\zeta$. Similarly, $(a+1)^m\in K$ for some $m$ so $\tilde a+1=\eta(a+1)$ for an $m$th root of unity $\eta\not=1$. Rearranging $\tilde a=\zeta a=\eta(a+1)-1$ gives
$$
\begin{align}
a=\frac{\eta-1}{\zeta-\eta}&&{\rm(1)}
\end{align}
$$
for roots of unity $\zeta\not=\eta\not=1$ in the normal closure of $L/K$.
As $K$ has characteristic zero, it contains the rationals and (1) shows that $a$ is algebraic over $\mathbb{Q}$. We can reduce to algebraic extensions of the rationals by setting $\tilde L=\mathbb{Q}(a)$ and $\tilde K=\mathbb{Q}(a)\cap K$. Every element of $\tilde L$ is a radical of an element of $\tilde K$, and $\tilde L,\tilde K$ (and their normal closures) are finite extensions of $\mathbb{Q}$.
Using the same argument as above, every element $b\in\tilde L\setminus \tilde K$ can be expressed as in (1) for roots of unity $\zeta,\eta$ in the normal closure of $\tilde L$. However, being a finite extension of $\mathbb{Q}$, the normal closure of $\tilde L$ only contains finitely many roots of unity, so (1) shows that $\tilde L\setminus\tilde K$ is finite. This is impossible for $\tilde L\not=\tilde K$. For example, $a+\mathbb{Z}$ is an infinite subset of $\tilde L\setminus \tilde K$, contradicting the initial choice of $a\in L\setminus K$.
Answer: We can suppose that $K \subset L$ is a finite extension (because any subextension still satisfies the property).
Let $L'$ be the Galois closure of $L$ and let $n=[L':K]$.
Euler's $\varphi(x)$ function diverges to $+\infty$ as $x \to \infty$, so we can pick an integer $p$ such that $\varphi(x)\le n \Rightarrow x \le p$.
Pick any $\sigma \in Aut_K(L')$.
For all $x \in L$, by assumption, there is an integer $m$ so that $x^m \in K$. Since $x$ can have at most $n$ distinct conjugates in $L'$, we can pick $m \le p$.  Then $x^\sigma = \zeta_x x$ where $\zeta_x$ is an $m$-th root of unity,. In particular, $\zeta_x$ is also an $p!$-th root of unity.
For any $x,y \in L^*$ and $t \in K$, write $\zeta_{x+ty}(x+ty) = (x+ty)^\sigma = x^\sigma+ty^\sigma = \zeta_x x+t\zeta_y y$.
If we find a $p!$-th root of unity $\zeta$ such that $\zeta_{x+ty} = \zeta $ for more than one values of $t$, then we have just found that the polynomial $\zeta (x + Ty) - x^\sigma - Ty^\sigma$ is a degree $1$ polynomial that has more than one root in $K$, so it has to be $0$, which implies that $\zeta = \zeta_x = \zeta_y$.
But there are finitely many $p!$-th roots of unity, while $K$ is infinite. so this always happen, and forall $x \in L^*$, $\zeta_x = \zeta_1 = 1$, and so $\sigma|_L = id_L$. So $L$ is Galois and there is no nontrivial automorphism : $K = L = L'$.
Comment: I don't follow why it can be assumed to be Galois.
Comment: @ George : I think I was under the very mistaken assumption that any element of the Galois closure is a conjugate of an element of $L$.
Comment: Ok, next, why can you write $x^\sigma$ as a power of $\zeta$ multiplied by $x$? This would imply that $x^n\in K$.
Comment: @ George : thanks, I realize it is more complex than I thought.
Comment: Yes, showing that $k(x)$ is uniformly bounded seems like the tricky bit. But, I think Zev's answer + my comments achieve this.
Comment: I see you've updated this answer, but now I'm struggling to understand why we can take $m \le p$. Could you give a bit more detail here?


How to identify that BIND is running under chroot

Question: I am trying to run BIND under chroot on Ubuntu and CentOS. Installing it on CentOS is pretty straight forward with just installing the packages - bind and bind-chroot, while Ubuntu is a little more involved.
I've been following the below links to get it running on Ubuntu,
https://help.ubuntu.com/community/BIND9ServerHowto
http://www.tokiwinter.com/installing-chrooted-bind-ubuntu-12-04-server/
I can get it up and running but I am unable to figure out if BIND is running in chroot.
From what I can see it isn't running in chroot since there is no pid file inside the chroot directory but instead there is still a pid file in the /var/run/named directory.
Also trying to see where the process directory is mapped using the below
[root@centos-test etc]# ls -ld /proc/2839/root
lrwxrwxrwx. 1 named named 0 Feb 11 04:01 /proc/2839/root -> /
[root@centos-test etc]#

But from what i read at various places the above command is supposed to point to the chroot'ed directory if it is running inside a jail.
How can i accurately identify that I am inside a chroot jail or not?
Answer: It's simple: if named is running with -t <directory> flag, then it's chrooted. Otherwise - it's not.


Cron - Does not execute command every 10 mins

Question: I don't understand why cron is not really executing the command every 10 minutes.
in crontab -e I have added:
*/10 * * * * /var/www/myproject/recording/batch.pl

I could see in the cron log it is running every 10 mins:
Mar 17 10:50:01 host crond[26335]: (root) CMD (/var/www/myproject/recording/batch.pl)
Mar 17 11:00:01 host crond[26357]: (root) CMD (/var/www/myproject/recording/batch.pl)
Mar 17 11:10:01 host crond[26418]: (root) CMD (/var/www/myproject/recording/batch.pl)
Mar 17 11:20:01 host crond[26657]: (root) CMD (/var/www/myproject/recording/batch.pl)

but it is not really executing the command.
When I execute that command manually in the Linux console it is working fine.
Comment: Did you check your email?
Comment: @MichaelHampton No? Where do I check that on Linux
Comment: try putting /path/to/perl in front of your command
Answer: CRON doesn't inherit all your environments variables. Some software must be manually called (ie: calling ifconfigor /sbin/ifconfig is not equal if you don't have a valid $PATH environment variable).
Also make sure it is executable and that your shebang is correctly defined (otherwise you'll have to prepend your command with the interpreter).
Answer: As CloudWeavers said, it most be about a missing environmental variable, to check what exactly is missing you can edit the cronjob to log all it's standard output/error to a log file, so that you can review it to get what's stopping it:
*/10 * * * * /var/www/myproject/recording/batch.pl &> output.log

Answer: how about setup your crontab like this
*/10 * * * * /usr/bin/perl /var/www/myproject/recording/batch.pl 2>&1 | tee -a /var/log/myproject-recording-batch.log

then you can tail the log file  /var/log/myproject-recording-batch.log to trace the running


Eigen Vector more than one for one eigen value

Question: I have a matrix, $S$,
$$ S =  \begin{bmatrix} 1.15 & 5.76 \\ 5.76 & 29.54 \end{bmatrix}.$$
I want to find eigen value and eigen vector of $S$, $$ (S -\lambda I)a = 0. $$ Calculating the Eigen value is easy since $S$ is a matrix $2\times 2$, hence I got
$$\lambda_1 = 30.66; \\
\lambda_2= 0.03. $$
Supposed that the eigenvector of $S$, $a$, has properties $a^Ta = 1$, hence I have a relation
$$ a^Ta = \begin{bmatrix} a_{11} & a_{12} \end{bmatrix}\begin{bmatrix} a_{11} \\ a_{12} \end{bmatrix} \\ a_{11}^2 + a^2_{12} = 1. $$
Since both $a_{11}$ and $a_{12}$ are in quadratic terms, it must have two values for each $a_{11}$ and $a_{12}$.
So then, for eigenvalue $\lambda_1 = 30.66$, I will get more than one eigenvector for one eigenvalue. It is confusing me which eigenvector should I use in my calculation, I need a suggestion or solution for this problem. Thank you in advance.
Comment: What are the eigen values and eigen vectors for the identity matrix?
Comment: What is the definition of characteristic subspace? For it is a subspace, if $\textbf{v}$ is in the subspace, what about $-\textbf{v}$?
Comment: I am sorry. I am new to linear algebra, so I don't really understand what eigen value and eigenvectors  for identity matrix.
Comment: @Jarjit You can always go back to the definition of eigenvalue and eigenvector. For any vector $\textbf{x} \in \mathbb{R}^n$, what is $\textbf{I}\textbf{x}$ then?
Comment: Since $\det(S)>0$ the eigenvalues must have the same sign.
Answer: When $a$ is an eigenvector for eigenvalue $\lambda$, any non-null vector proportional to $a$ is also an eigenvector for $\lambda$.
The equation $a^Ta=1$ is only useful if you want an eigenvector with norm 1. So you don't have to worry about that immediately. First determine $a_i$ such that $Sa_i=\lambda_i a_i$, for $i=1$ and $2$. This will give you solutions $a_i=\gamma_i b_i$, where $\gamma_i \in \mathbb{R}$ can take any non-null value.
Then, if you want $a_i$ with norm $1$, compute the norm of $b_i$ and adjust $\gamma_i$ accordingly. You'll get two solutions, which will give two opposite vectors.


Remover parte sem tamanho fixo de um xml

Question: Galera,
Tenho esse pedaço de um XML e necessito retirar o valor (357122.40) que está entre as tags < vMerc>xxxxxx< /vMerc>. Só que esse valor não tem tamanho fixo.
...<infCTeNorm><infCarga><vMerc>357122.40</vMerc><proPred>...

Tentei fazendo esse SQL:
SUBSTRING((CONVERT(VARCHAR(MAX), xml_conhecimento)), (PATINDEX('%<infCTeNorm><infCarga><vMerc>%', CONVERT(VARCHAR(MAX), xml_conhecimento)) + 30), (((PATINDEX('%</vMerc><proPred>%', CONVERT(VARCHAR(MAX), xml_conhecimento))) - (PATINDEX('%<infCTeNorm><infCarga><vMerc>%', CONVERT(VARCHAR(MAX), xml_conhecimento))))-30))

Mas não funciona em tabela com muitos registros. Aparecendo o seguinte erro:
Mensagem 537, Nível 16, Estado 3, Linha 56
Parâmetro de comprimento inválido passado para a função LEFT ou SUBSTRING.
Comment: 2 perguntas: Você poderia disponibilizar o XML inteiro? Saberia nos dizer em qual XML o seu SQL falha?
Comment: Segue link de um xml e não sei onde falha:
https://www.webdanfe.com.br/danfe/exemplos/CTe_assinado.html
Answer: Esse erro significa que a função SUBSTRING está a receber um valor negativo no parametro start ou no parametro length.
Se o valor pretendido aparece aparece sempre entre as tags <vMerc></vMerc> , está aqui uma solução que funciona sempre. Retorna NULL caso não encontre nenhum valor.
Usei variáveis apenas para que fosse mais fácil ler e testar o código, substituir de acordo.
declare @xml        nvarchar(max)
declare @tagAbrir   nvarchar(200)
declare @tagFechar  nvarchar(200)
declare @pattern    nvarchar(max)
declare @inicio     int
declare @fim        int
declare @compriNum  int

set @xml        = '<infCTeNorm><infCarga><vMerc>357122.40</vMerc><proPred>'
set @tagAbrir   = '<vMerc>'
set @tagFechar  = '</vMerc>'
set @pattern    = '%'+ @tagAbrir + '%' + @tagFechar + '%'

set @inicio     = CASE WHEN PATINDEX(@pattern, @xml)>0
                  THEN PATINDEX(@pattern, @xml) + LEN(@tagAbrir)
                  ELSE NULL END
set @fim        = CHARINDEX(@tagFechar,@xml,@inicio)
set @compriNum  = @fim + LEN(@tagFechar) - @inicio - LEN(@tagAbrir)

select SUBSTRING(@xml,@inicio,@compriNum-1) AS Valor


Find a measurable function $g:\mathbb{R}\to\mathbb{R}$ s.t. $\mathbb{E}(g(\mathcal{N}(0,1)))=2$

Question: Let $X\sim\mathcal{N}(0,1)$ a random variable. Find a measurable function $g:\mathbb{R}\to\mathbb{R}$ such that $\mathbb{E}(g(X))=2$.
Comment: Hint: What is E(X^2)? Simpler: What is E(X)? Even simpler: What is E(1)?
Answer: We know that the density function of $X$ is
$f_X(s)={1\over\sqrt{2\pi}}e^{-s^2\over 2}$. Let $g:\mathbb{R}\to\mathbb{R}$ a function defined by
$$
\\ g(s)=\sqrt{2\pi}e^{s^2\over 2}\cdot\textbf{1}_{\{0\leq s\leq 2\}}\ \
$$
$s\mapsto \textbf{1}_{\{0\leq s \leq 2\} }$ is a measurable function because it's a linear combination of indicators of borel sets, $s\mapsto\sqrt{2\pi}e^{s^2\over 2}$ is a measurable function because it's continuous, and $g$ is a measurable function because it's a composition of measurable functions. Thus,
$$
\\ \mathbb{E}(g(X))=\int_{-\infty}^\infty g(s)f_X(s)ds=\int_0^2ds=2  \
$$
Comment: This is fine and dandy but far too complicated, maybe?  What if $g(x) = x+2$ for all $x\in \mathbb R$? Is $g(x)$ measurable? What is $E[g(X)] = E[X+2]$?


Backing up data of android app in phone directory

Question: I actually created an android app, now I want to add an backup and restore option in that app. If I click on backup option all the data for that particular user including video, media etc need to be backup in .zip format and need to be saved in phone directory.
My question is whether I need to use BackupAgentHelper provided by Android API or is there some other way I can do it? if anyone can help it will be very useful..
Comment: You can use and do what you want. There are no obligations.
Comment: @greenapps So, I can use BackupAgentHelper to perform this operation. As I read the document on that and they only mentioned of backing up data to cloud. So, I am confused with this.
Answer: You can use Auto Backup or Key/Value Backup (by extending BackupAgentHelper). Or you can implement your own custom backup solution.
If you want to target Android versions 4,5 or API level 22 or below you need to use Key/Value Backup. If you target Android 6 and above you can use Auto Backup.
Differences between Auto Backup and Key/Value Backup:
https://developer.android.com/guide/topics/data/backup.html
Auto backup:
https://developer.android.com/guide/topics/data/autobackup.html
Key/value backup:
https://developer.android.com/guide/topics/data/keyvaluebackup.html


Exibir modal de confirmação após enviar email

Question: Tenho o seguinte código
<?php

require_once('PHPMailer-master/PHPMailerAutoload.php');

PHP_OS == "Linux" ? $quebra_linha = "\n" : $quebra_linha = "\r\n";

//$emp = $_POST["empresa"];
$nome = trim($_POST["nome"]);
$tel = $_POST["telefone"];
$cid = $_POST["cidade"];
//$ass = $_POST["assunto"];
//$msg = $_POST["mensagem"];

switch ($cid) {
    case "ipatinga":
        $destino = "email@example.com";
        break;
    case "fabriciano":
        $destino = "email@example.com";
        break;
    case "timoteo":
        $destino = "email@example.com";
        break;
}

$email = "
NOME: ".$nome."
TELEFONE: ".$tel."
CIDADE: ".$cid."";

$mail = new PHPMailer();

$mail->IsMail();
//$mail->SetFrom('email@example.com', 'Thiago Londe');
$mail->SetFrom($eml, $nom);
$mail->Subject    = "Agendamento de visita";
$mail->MsgHTML($email);
//$mail->AddAddress($destino, "Thiago Londe");
$mail->AddAddress($destino, utf8_decode('Unimed'));

if (!$mail->send()) {
    $msgerro = "Não foi possível enviar sua mensagem de contato. Tente novamente dentro de alguns instantes.";
} else {
    $msgerro = "Sua mensagem de contato foi enviada com sucesso!";
}

if($mail->send()) { ?>

Gostaria de saber alguma forma de exibir um modal de confirmação de envio assim que o usuário submeter o form.
Alguma sugestão?
Answer: Ao meu ver, a maneira mais simples de se construir qualquer front-end, incluindo modais, é utilizando boostrap. Neste caso, você poderia fazer da seguinte forma:
<?php

function error($data) {
    foreach($data as $key => $val)
        if(empty($val))
            return "Campo $key vazio, preencha todos os campos para fazer o envio";
    return false;
}

require_once('PHPMailer-master/PHPMailerAutoload.php');

PHP_OS == "Linux" ? $quebra_linha = "\n" : $quebra_linha = "\r\n";

//$data["empresa"] = $_POST["empresa"];
$data["nome"] = trim($_POST["nome"]);
$data["telefone"] = $_POST["telefone"];
$data["cidade"] = $_POST["cidade"];
//$data["assunto"] = $_POST["assunto"];
//$data["mensagem"] = $_POST["mensagem"];
try {
    $error = error($data);
    if($error)
        throw new Exception($error);

    switch ($cid) {
        case "ipatinga":
            $destino = "firstname.lastname@example.com";
            break;
        case "fabriciano":
            $destino = "email@example.com";
            break;
        case "timoteo":
            $destino = "email@example.com";
            break;
    }

    $email = "
NOME: ".$nome."
TELEFONE: ".$tel."
        CIDADE: ".$cid."";

    $mail = new PHPMailer();

    $mail->IsMail();
    //$mail->SetFrom('email@example.com', 'Thiago Londe');
    $mail->SetFrom($eml, $nom);
    $mail->Subject    = "Agendamento de visita";
    $mail->MsgHTML($email);
    //$mail->AddAddress($destino, "Thiago Londe");
    $mail->AddAddress($destino, utf8_decode('Unimed'));

    if (!$mail->send())
         throw new Exception("Não foi possível enviar sua mensagem de contato. Tente novamente dentro de alguns instantes.");

    $msgerro = "Sua mensagem de contato foi enviada com sucesso!";
} catch (Exception $e) {
    $msgerro = $e->getMessage();
}

?>
<!DOCTYPE html>

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

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Envio de email

<?=$msgerro?>

            <button type="button" class="btn btn-default" data-dismiss="modal">Ok</button>

Comment: Obrigado Kenny Rafael.

Mas como posso fazer isso dentro do php?

Tenho isso:

if (!$mail->send()) {
    $msgerro = "Não foi possível enviar sua mensagem de contato. Tente novamente dentro de alguns instantes.";
} else {
    $msgerro = "Sua mensagem de contato foi enviada com sucesso!";
}

Gostaria de quando o email for corretamente enviado, invés de exibir uma janela confirmando, exibir o modal de confirmação.
Comment: Vou editar para ficar mais claro!
Comment: Você já está setando a mensagem, independente de erro ou não, neste caso, basta dar o echo dentro do modal como no exemplo, o que alterei na verdade foi só inserir o seu código de envio antes de exibir o conteúdo.
Comment: Consegui Kenny Rafael. Agora me surgiu uma outra dúvida. Meu formulário está validando para verificar se os campos foram todos preenchidos. O meu modal está aparecendo mesmo se os campos não forem preenchidos. Como fazer com que ele apareça somente se todos os campos estiverem preenchidos?

Deixei assim:

$('form button[type="submit"]').on('click', function () {
            $('#modal-mail').modal('show');
        });
Comment: O ideal é que seu modal abra sempre com as informações do que aconteceu, neste caso, dei um upgrade no código, dá uma olhada!


Trigonometry word problem involving wheel?

Question: A wheel 5 feet in diameter rolls up with an incline of 18 degrees 20 minutes. What is the height of the center of the wheel above the base of the incline when the wheel has rolled 5 ft up the incline?
Comment: Draw a picture.  Do you see a right triangle that might give you some clues.
Comment: I drew a picture with 5 being hypotnouse 18 degrees 20 being an angle and I got 1.57. When i did sin 18 degrees 20= x/5.
Comment: Hmm I am not sure how to proceed.
Comment: @Bishop did you figure it out?
Comment: No I cant seem to figure it out.
Comment: By the way welcome to Math Stackexchange :)
Comment: Bishop, it does seem that you are able to write what you've already tried for solving a problem. Please write those out as part of your question the next time you ask one...
Answer: Does this diagram help? It is not drawn to scale but it can help in visualizing the problem.

So note that $|BD|=5ft$, $|CD|=2.5ft$, $\angle BDC=90^\circ$. Having settled that $$|CM|=\dfrac{2.5}{\sin 72}=2.628655561\ldots$$ we now need to find $$|MD|=\dfrac{2.5}{\tan 72}=.812229924\ldots$$ Since $|BD|=|BM|+|MD|$, then $$|BM|=5-|MD|=4.187700759\ldots$$ Calculating now $$|ME|=|BM|\sin 18=1.294070702\ldots$$ Finally, $$|CE|=|CM|+|ME|.$$
Comment: Similar trangles galore!
Comment: Yes I did something similar and I got BE is 4.74 when I did 5 cos 18 degrees 20 minutes the thing is my final answer is 3.75 ft and I am not sure how to get there. I mean I know from E to right below the circle is 1.57.
Comment: Maybe I add 1.57 plus the radius which is 2.5 feet.
Comment: @azetina Good Drawing!
Comment: @ncmathsadist thanks. I did it with GeoGebra. Very nice program indeed.
Comment: @Bishop If my answer responds to the question, do hit the check mark to accept as an answer. :)
Comment: I think it's not quite clear from the problem description which position the wheel _starts from_ before it moves the 5 feet along the incline. If the wheel starts being tangent to the incline at your point $B$, then it would initially protrudes _below the floor_. It might be a more realistic assumption that the wheel is initially tangent to _both_ the floor and the incline, in which case the answer would be simply $2\frac 12 + 5\sin 18^\circ 20'$.
Comment: @HenningMakholm I understand that clearly but what I suggested would give an idea on how to solve the matter at hand.
Answer: Place an additional label where the segment joining $C$ to $E$ and the segment joining $B$ to $D$ intersect.  Let's agree to call that point $M$.  The length of $\overline{EM}$ is $|\overline{BM}|\sin(18^\circ)$.  The angle $\angle CMD$ is $72^\circ$.  Can you figure the rest?
Now use the fact that
$$\sin(72^\circ) = {2.5\over |\overline{CM}|}.$$
so $$|\overline{CM}| = {2.5\over \sin(72^\circ)} = 2.629. $$
Also we have $|\overline{BM}| = 5 - | \overline{MD}|$.  Can you find the length of $\overline
{ MD}$?
Comment: I know the lenght of EM is about 1.57 but no I am not sure about figuring out the rest. Am I to use 72 degrees to find a certain length?
Comment: @ncmathsadist I disagree with you since EM is in $\triangle BEM$ and therefore its hyp0tenuse is not 5 ft.
Comment: I will say the final answer is 3.95 I know BE is 4.74 the question is how to reach the final answer?
Comment: would MD be .81240 I did 2.629 cos 72
Answer: Rotation of axes. Plug in
$$ x = 5^{'}, y =2.5 ^{'}, \alpha = 18 \frac 13^{0}$$
into
$$ y_2 = x  \sin \alpha + y  \cos \alpha. $$
Answer: You'll just have to imagine that the radius (Half of the diameter which is 2.5 feet) is aligned with the height of the triangle. So You just have to get the height of the triangle. To get it's height. Simply...
Sin 18.33 = height / 5 feet
Sin 18.33 x 5 feet = height
(0.3145)(5 feet) = height
1.5725 = Height
So, to get the height of the center of the circle to the ground. Simply...
Height of the center of the circle  w/respect to the base = 1.5725 + 2.5
The answer would be...
4.0725 feet


dump command is showing empty brackets in pig

Question: When I used the following command in the grunt shell:
B = FOREACH A GENERATE(category);
dump B;

The output was:
()
()
()
()
()
()
()

and so on.
Category is the string(char array) which I want to display using dump.
Answer: Add a "DESCRIBE B" to the end of the script.
The output appears to be 7 nulls, instead of an expected chararray or string.  The DESCRIBE command will either verify that category is actually a string equal to "() () () () () () ()" or is using an unexpected schema.


GRE math prep question

Question: How can I solve $\int_{0}^{x}(1-e^{-t})\, f(t)\, dt = xe^{2x}$ for $f(x)$. Problem from here.
I tried solving $(1-e^{-t})\, f(t) \left\rvert \right._{t=x}= \frac{d}{dx} x e^{2x}$, but it didn't work. Any help would be appreciated!
Comment: Why didn't it work?
Answer: Applying the Fundamental theorem of Calculus should work.
Just take the derivative with respect to $x$ on both sides and apply the first part of the Theorem.
Solving for $f(x)$ gives you $f(x)=\dfrac{e^{2x}(2x+1)}{1-e^{-x}}$.
Notice that you can treat the case $x=0$ first on which the identity becomes trivial.

GRE math prep question


Difference of harmonic series

Question: Proving convergence:
$$\sum_{n=1}^\infty (-1)^{n-1}\frac1n$$
Just wanted to confirm if the reason they converge is due to the fact that for n= 1, 3, 5, ... we have a positive harmonic series and for n= 2, 4, 6, ... we have a negative harmonic series? therefore the two cancel giving a convergent sum.
Does the above proof make mathematical sense?
Is it possible for the difference of two particular (not the same) harmonic series to be divergent?
Answer: The two do not cancel at all. Perhaps you want to read about Leibniz Alternating Series
About your last question: for any $\,k,m\in\Bbb R\,$ , the series
$$\sum_{n=1}^\infty\left(\frac{1}{kn}-\frac{1}{mn}\right)=\frac{m-k}{mk}\sum_{n=1}^\infty\frac{1}{n}\,\,\,\text{diverges}$$
Answer: Here I'm speaking about the series $$\sum_{n=1}^{\infty}(-1)^n\frac1n$$
(I assume this is what you intended, because $\displaystyle \sum_{n=1}^{\infty}\frac{(-1)^n}{\frac1n}=\sum_{n=1}^{\infty}(-1)^nn$ manifestly can't converge.)
Well, yes, the fact that for $n=1,3,5,\dots$ ($n=2,4,6,\dots$) you have a positive (negative) contribution to the series is the reason why it converges, but that's just an observation and definitely not a proof.
A demonstration easily follows from Leibniz criterion for alternating series, since the sequence $(a_n=\frac1n)$ is monotone decreasing and $\displaystyle \lim_{n\rightarrow\infty}a_n=0$.
Comment: yes, I edited the original question. Currently reading up the alternating series test.
Answer: Second question:
The difference of two complete harmonic series converges to $log(\frac{p}{q})$, where $p$ positive terms and $q$ negative terms are taken every $p+q$ terms.
$$
\log\left(\frac{p}{q}\right)=\sum_{i=0}^\infty \left(\sum_{j=pi+1}^{p(i+1)}\frac{1}{j}-\sum_{k=qi+1}^{q(i+1)}\frac{1}{k}\right)
$$
See this message for some examples https://math.stackexchange.com/a/1602987/134791
We can think those pairs as the same series in the sense that they have the same terms but also as different series because their relative speed or rate is not the same. One may be interpreted to run faster than the other, because has more terms than the other per term in the difference.

Difference of harmonic series


Is ID column always required in SQL?

Question: to be more specific, I've created a news module with a tag system. As each tag is unique (you are not allowed, as an admin, to create 2 identical tags), is the id column still useful? I guess no, but I was wondering about the performances.
id | mews_title | date ... <-------------> news_id | tag_id <----------> id | tag_name
VS
id | mews_title | date ... <-------------> news_id | tag_tag_name <----------> tag_name
Thanks a lot!
Comment: ID could be anything. A tag doesn't say much about what that may look like. It may or may not have serious effect on performance.
Comment: Presumably, a "tag" is a word or a short phrase, often a noun or adjective.
Answer: The performance difference is insignificant.
Advantages to using a numeric id for the tags in your example would be:

to make the intersection table somewhat smaller because integers are smaller on average than a string
to allow changing the spelling of a tag name by updating one row instead of many rows

These may not be important considerations for your case. So no, it's not required to use a numeric id.
I also wrote about this in a chapter titled "ID Required" in my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.
Comment: Nice, I've got your book on a shelf somewhere :-))
Comment: The second point is not that much of an advantage in a tagging system.  You are more likely to split a tag into two tags than to fix the spelling of one tag universally.  Anyway, since the tag lives only in this table, a simple multi-row Update is not that bad.  The `id` arguments are useful in _other_ cases.
Comment: Thanks a lot, I have not thought about your second point!
Answer: Numeric IDs are not required (You could have a table without a primary key), but they are useful:

Without and ID column, if you want to change a tag_name in the future (because for example it is misspelled), you will have to update all the tables that have this foreign key (tag_tag_name). If you have and ID column you only will have to change the tag_name in one place.
They could be auto generated (Autoincremental).
It could take up less space. For example when the natural primary key is composite and is the foreign key in another table, and id (one integer column) primary key take up less space.
It's easier make joins with other tables (If the primary key has only a column than if it has more than one).
if all yours table's primary key is the ID field, you don't have to remember others field names when you make joins, your data schema syntax will be consistent.

You can specify the tag_name as unique, so two tag_name equals couldn't be inserted.
Comment: Less space -- Maybe not.  The `id` is showing up in at least 2 tables.  If you blindly use `INT`, that's 8 bytes (plus overhead).  In many tagging systems, the average tag length might be less than 8.
Comment: Thanks, the first and fourth points are good arguments.
Answer: You don't even need a table of tags.  Just a table with
news_id | tag_name

This is a many-to-many mapping between news_ids and tags.  Since there is no tag table, the issue of duplicates vanishes.  The same tag (tag_name) can be associated with many news articles, but that is what you want.
INSERT INTO Tags (news_id, tag_name) -- change this to INSERT IGNORE INTO Tags (news_id, tag_name) so you don't have to worry about getting the same news article tagged the same way twice.  And have
PRIMARY KEY(news_id, tag_name), -- uniqueness and lookup tags for one article
INDEX(tag_name, news_id)  -- For finding all articles for one tag

Is ID column always required in SQL?


How to make sql server database setup

Question: I have an application that uses SQL Server Express.  How to make setup that will install the application on client's computer?
I searched a lot on google but nothing found helpful.
Also tried this link http://www.codeproject.com/KB/database/Deploy_your_database.aspx
but got stuck on step 3.  Please help.
Thanks
Comment: need to know the exact problem you're having on step 3.  Are you looking for the setup in Visual Studio or Sql Server Management Studio?  Are you getting an error message?
Comment: I donot know how to add installer class and overide it (as mentioned in the article)  Also how to add the code given in vb.net
Answer: Try this article :
http://msdn.microsoft.com/en-us/library/bb264562(v=sql.90).aspx#emsqlexcustapp_topic3

How to make sql server database setup


C harmonica: How to play high tabs without producing "noise"

Question: I'm going to give 2 examples so you understand the point

If you want to play She's Gone, how you do so? when he screams "Hey Lady...". I tried to play all the time on 8 - 9 holes doesn't sound right, 8' and 9' are worse. i played 4 - 8 and it sounds better, but It's not the real notes.

It's not just about that song, it's about all the songs that has electric guitar, I've never been able to match an electric guitar, especially those songs which has high tabs, the harp seems to make noise when you play long high tabs.
But if you play other songs on acoustic guitar or piano, like "When I was your man", even if you play high tabs for a long time, it doesn't sound that bad. Maybe because you can play lowest tabs?
Is it just about electrical guitar or not? How to play long high notes? they don't bend.
Answer: I'm not sure whether you're trying to play the vocal line from She's Gone on harmonica, or whether you're trying to play the lead guitar part on harmonica.
Either way, the principle is the same: different instruments have different capabilities. It sounds as if you're trying to play long sustained notes at the top end of your harmonica's range.
It's pretty common for the top end of a harmonica to sound "reedy" - a bit of a hiss alongside the tone. You may be able to improve this by looking around for a better harmonica, or by experimenting with breath control to find the perfect blow pressure for that note.
However, more generally, understand that while some people's voices, and many electric guitars are designed for that range, your harmonica probably isn't. You don't hear those notes sustained on many recordings, and there's a reason for that -- it doesn't sound very nice.
You would have the same problem, for example, adapting violin solos.
Copy actual harmonica parts, or when writing your own parts or adapting parts for other instruments, bring the arrangement into the natural range of the instrument. Perhaps you need to find a sneaky place to drop by an octave.
Answer: Heres a good how to on playing singles notes http://www.harmonica.com/single-notes-harmonica-4947.html ...once I got that down, playing songs a lot easier, even 8 and 9.
Comment: This answer would be more useful if it included some detail, even an excerpt of the site linked to , but a link only answer is not useful here.


How can i simulate a "click" on a website, without clicking? To read the response message before to real click

Question: is there any way to send a "fake" request to a server, via a website, to analyze the response and then make the real request?
I'll give you an example: if on a website i click on a button, the site shows me a message. I need to simulate the button click because im trying to know in advance what the response message would be to the click, but without actually clicking on the button. Thank you. Have a good day!
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Two things:

You could try and read the JS scripts on the page and deduct what would clicking that element do, but usually the scripts are mangled, so it would be hard to read. You could try searching them via class or id of the element of interest.
You could try playing with blocking network traffic, so you could still do the action, without sending the request. It might prove fruitless as the result might be dependent on getting a valid response from the server, but still it could be worth a shot.
Comment: thanks for the reply, i don't know how the communication between client and server works but i was thinking, if i send a request and the server replies, does my client need to give confirmation of receipt? in this case it would be possible not to send my confirmation of receipt, but in the meantime read the message from the server?


How to pull what endpoints are still using old DNS?

Question: I have a Windows Server 2008 R2 box that served as our DNS server for some time. I built a new one awhile back and we've been haphazardly switching over to the new one. Is there a way to see what endpoints might still be requesting resolutions from the old DNS server? I'd like to turn that box off.
Thanks
Answer: Start a packet capture on the old box with wireshark with a filter like:
<code>dns and ip.dst==ip_of_your_server or dns and ip.src==ip_of_your_server
</code>
Comment: I figured I might have to go down that road, I just thought there might be a log or something that would tell me that info.
Comment: @SquishemQuick You can install a audit tool, from MS (https://technet.microsoft.com/en-us/library/dn800669%28v=ws.11%29.aspx?f=255&MSPPError=-2147217396) but in my opinion it's simplier to run a wireshark portable edition
Answer: Lots of direct logging in Windows DNS:
https://technet.microsoft.com/en-us/library/cc776361(v=ws.10).aspx
https://technet.microsoft.com/en-us/library/cc759581(v=ws.10).aspx


Integral $\int_1^2 x^{-2}\,dx$ with Darboux sums.

Question: I'm trying to calculate $\int_1^2\frac{1}{x^2}\,dx$, with the partition $2^{\frac{i}{n}}$ , $0\leq i\leq n$. ( Darboux sums)
I tried to solve it for hours but I'm getting strange results.
thanks for help!
Answer: The function is continuous and strictly decreasing, so $$U_n=\sum_{k=0}^{n-1}\frac{2^{(k+1)/n}-2^{k/n}}{2^{2k/n}}\\ L_n=\sum_{h=0}^{n-1}\frac{2^{(h+1)/n}-2^{h/n}}{2^{2(h+1)/n}}$$
Thus $$U_n=\sum_{k=0}^{n-1}\frac{2^{1/n}-1}{2^{k/n}}=(2^{1/n}-1)\cdot\frac{2^{-n/n}-1}{2^{-1/n}-1}=(2^{1/n}-1)\frac{-\frac12}{2^{-1/n}(1-2^{1/n})}=2^{(1-n)/n}$$ And, to cut it short, $L_n=2^{-2/n}U_n$
Comment: thanks ! but can you explain how did you get rid of the SUM symbol? i dont understand this step.
Comment: The $2^{1/n}-1$ is constant in $k$, so it can be taken out of the sum. Then, it's the sum of a geometric sequence, because $\frac{1}{2^{k/n}}=(2^{-1/n})^k$.
Comment: now i understand , thanks alot!
little question :when i tried to solve this at the  beggining i used  the infinity geometric sequence formula and it didnt gave me any result. this is not an inifinity geometric sequence?
Comment: @Gyyyy It would give a finite, but incorrect, result. Specifically, roughly twice the correct one, because you'd be adding to what I wrote the sum of all the terms $2^{-k/n}$ for $k\ge n$. Or, in the grand scheme of things, you'd be calculating something fairly close to the definition of $\int_1^\infty x^{-2}\,dx$. The fact that you are summing up to "the same $n$ that appears in $a_1,\cdots, a_n$" is crucial.
Comment: thanks alot for your help!
Comment: We have $n+1$ nodes so $n$ subintervals. But why did you take the summation to $n-1$ instead of $n$?
Comment: And another question please. Did you take the term $2^\frac{i}{n}$ in $U(f,P)$ instead of $2^\frac{i-1}{n}$ for simplicity?
Comment: @nour 1) Because my summation starts at $k=0$ and ends at $k=n-1$. So it has $(n-1)-0+1$ terms. 2) Because the Darboux upper sum forces me to choose $\sup\{ f(x)\,:\, x\in [a_k,a_{k+1}]\}$.
Comment: But in the question $0 \leq i \leq n$ and not $n-1$. Sorry but I'm not catching the idea.
Comment: $0\le i\le n$. In particular, for $i=n$ you have the last point of the interval ($2$). Obviously, $[2,2^{1+\frac1n}]$ is not a subinterval of $[1,2]$.
Comment: Regarding my second question: I meant why didn't you consider $sup{f(x) : x\in [a_{k-1}, a_k]$. I know this is the same. But when I tried to solve it with these terms $2^\frac{i-1}{n}$ made it a little more difficult. That's why I asked you if you use this for more simplicity.
Comment: @Nour Not really. It's the first that came to mind. For yours you should get a general term $$\frac{2^{k/n}-2^{(k-1)/n}}{2^{2(k-1)/n}}=\frac{2^{1/n}-1}{2^{(k-1)/n}}$$ and do basically the same steps (this time summing from $1$ to $n$).
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/58996/discussion-between-nour-and-g-sassatelli).


Geometric meaning of a vector space

Question: Let $Q = \{(x,y) \in \mathbb{R}^2: x,y > 0 \}$ be a vector space over the real numbers with the operations
$$+:Q\times Q \rightarrow Q$$
$$(x_1,y_1)+(x_2,y_2)=(x_1x_2,y_1y_2)$$
and
$$\cdot : \mathbb{R} \times Q \rightarrow Q$$
$$c\cdot(x,y)=(x^c,y^c)$$
It's easy to show that this structure is a vector space, but what about the geometrical meaning of these operations? Is there any?
Comment: what do you mean $x^c$
Comment: $\prod_{k=1}^{c} x$
Answer: Consider $\tilde x = \ln x$ and $\tilde y = \ln y$. Then $(\tilde x, \tilde y)$ is just the standard $\mathbb R^2$. Therefore your vector space is just the standard $\mathbb R^2$ using logarithmic coordinates instead of Cartesian coordinates.
Answer: Let $\mathbb R_{> 0} = \{x \in \mathbb R \mid x > 0 \}$.
Note that $\log\colon (\mathbb R_{>0},\cdot) \to \mathbb (\mathbb R,+)$ is an isomorphism of abelian groups.
This induces an isomorphism $Q=\mathbb R_{>0}^2 \to \mathbb R^2, (x,y) \mapsto (\log x, \log y)$.
Now note that under this isomorphism, your scalar multiplication becomes the usual one on $\mathbb R^2$ since $\log(x^c) = c\log(x)$.
So $Q$ is isomorphic to $\mathbb R^2$ with the usual $\mathbb R$-vector space structure.

Geometric meaning of a vector space


cloud-init does not run when creating azure vm

Question: I am running the below sample. For some reason, it is not executing cloud-init-web-server.txt when creating the VM. Is there any other step messing?
I have looked at this azure VM tutorial.
az vm create \
    --resource-group tkestvalkey \
    --name myVM \
    --image UbuntuLTS \
    --admin-username azureuser \
    --admin-password password \
    --custom-data cloud-init-web-server.txt \
    --secrets "$vm_secret"

Answer: I just went over the steps, it works just fine.  Make sure you are not getting any error on the commands.
I notice you password is password, it might fail validation. Try it with a stronger password or the SSH key like the tutorial.
Comment: no sure what happened it worked this time. thanks for check it out


What equational properties of a group only need to be checked on a generating set?

Question: Let $G$ be a group and $S\subset G$ a generating set. Let $P$ (short for $P(x_1,\dots,x_n) = 1$) be an equational property that may or may not be satisfied by all $n$-tuples of elements of $G$. My question is:

What $P$ are such that $P$ being satisfied on $S$ implies that it is satisfied on all of $G$?

Is there a simple characterization? (If so, do you know a proof?) Is this a hard question with a developed theory? (If so, can you point me to relevant sources?)
Examples of $P$'s:
(1) If $P$ is $[x_1,x_2]= x_1x_2x_1^{-1}x_2^{-1}=1$, then $P$ being satisfied on $S$ implies that it is satisfied on $G$. Indeed if pairs of generators commute, then words on those generators clearly commute since the generators can "slip past each other."
(2) On the other hand, if $P$ is $x_1^2=1$, then $P$ being satisfied on $S$ says nothing about $G$. For an extremely hands-on example, $S_3$ is generated by two elements of order $2$, but not all its elements are order $2$.
Motivating example:
What got me interested in this in the first place was that I was wondering if free metabelian groups (on a finite number of generators) are finitely presented. Does the relation $[[x_1,x_2],[x_3,x_4]] = 1$ that defines metabelianness carry over from a generating set to the whole group? A few google searches seems to have revealed that it does not, so now I'm wondering what the other relations might be that do carry over.
Thanks in advance.
Answer: This is more of an extended comment:
If your group has two generators, like the free group on two generators, then these metabelian relations hold for the generators, since $[[x,y],[x,y]]=1,[[x,y],[y,x]]=1,[[x,y],[x,x]]=1$ (this is just asking if $[x,y]$ commutes with itself, with its inverse, and with the identity).
You should look into verbal subgroups and reduced free groups, I know that Combinatorial Group Theory by Karrass, Magnus, Solitar has some stuff on them. It is known that reduced free groups all have presentations $\langle a_1,...,a_n \mid X_1^d, P_1,....,P_i,...\rangle$ where the $X_1,P_i$ are all the words that satisfy the equation they specify (so $P=X_1X_2X_1^{-1}X_2^{-1}$ is the commutator subgroup and $X_1^d$ is the group generated by all $d$-powers), and $P_i$  are in the commutator subgroup (this is Cor 2.3.1 in Combinatorial Group Theory). You can find by looking directly at any original presentation and transforming the presentation in a fairly simple manner (although I am not sure if "defining relation on generators is enough"-property is preserved, but it seems plausible).
I wouldn't be surprised if the commutator equation is the only one where you can get away with generator only relations, and feel like there should be a way to finagle an answer using that corollary.
Update 1: The equation for the equation $[X,Y]X^p=1$ it is enough to define on generators (where $X,Y$ vary over the group.) This is because if you have generators $x_1,...,x_n$, you can look at $[x_i,x_i]x_i^p=1=x_i^p$, so your generators are torsion, and $[x_i,x_j]x_i^p=1=[x_i,x_j]$ (since $x_i^p=1$) so your group is commutative. So your group is $\langle x_1,...,x_n \mid x_i^p, [x_j,x_k]; 1\leq i,j,k \leq n \rangle $ which is exactly the free reduced group version (ranging over all elements rather than just the generators).
Note that if you change this to something like $[X,Y]W(X,Y)=1$ ,where $W(X,Y)$ is a word in $X,Y$ you still get that $x_i$ are torsion provided $W(X,X)$ is not in the commutator subgroup, by the same argument, but you don't know, a priori, that $W(x_i,x_j)$ will be trivial, so you won't be able to conclude $[x_i,x_j]=1$, which is important to the argument. The reduced free group version of this group will be torsion( provided $W(X,X)$ is not in the commutator group) using the techniques in the proof of corollay 2.3.1. It feels very unlikely if you got a group which ranged over just the generators you would end up with a torsion group for most choices of $W(X,Y)$.
Comment: @BenBlum-Smith Yes. I didn't really think much about it whether or not it would work for higher. For example for $n=2$ we have the relations $[x,y]=x$ and $[y,x]=y$, so $x=y^{-1}$ since $[x,y]^{-1}=[y,x]$, so $[x,y]=[x,x^{-1}]=x=1$ etc. I guess the same argument works for $n>2$ too since you can do that to every pair of generators. (The reason I said for $n=1,2,3$ is that I know for $3$ it ends up being a quotient of a group I happened to know is tivial, a variation of the Higman group, $\langle x,y,z \mid [x,y]=y, [y,z]=z, [z,x]=x\rangle=1$ )
Comment: @BenBlum-Smith See my update to the answer. Short answer, yes it does.
Comment: Maybe I should hedge my bets on that last statement to things closely related to the commutator equation, like $[x,y]x^{-1}$ for 1,2,3 generators produces the trivial group.
Comment: Just so I can make sure I've parsed what you're asserting, is it that $\langle x_1,\dots,x_n\mid \{[x_i,x_j]x_i^{-1}\}_{i\neq j}\rangle$ is trivial for $n=1,2,3$?
Comment: Aside: +1 already for the elegant proof that the metabelian relation does not extend to the whole group. (Since $F_2$ is obviously not metabelian, and neither, e.g., is $S_n$ for $n>3$...)
Comment: I think messing around with the generator relations $[x_i,x_j]x_i^{-p}$  would be a good place to start since when looking verbal groups (not just the generator versions) this corresponds to the verbal group $\langle X_1^p, [X_1,X_2]\rangle$ ($X_i$ range over all of the group), in the proof of corollary 2.3.1, so end up being somewhat related to the case we already know, for commutators it is enough to define on generating set. At the moment, I don't really have time to investigate further, but that is where I would start.
Comment: (notation notes: The $X_1's$ that appear in different words are independent from each other, it is just the notation used in Combinatorial Group Theory)
Comment: Again just so I can make sure I understand you: you're suggesting that the relations $[x_i,x_j]x_i^{-p}$ might carry from generators to the whole group?


Isn't $V^n$ a $\Bbb K$-vector space?

Question: Suppose $V$ is a $\Bbb K$-vector space. Let $n \in \Bbb N.$ Can't we say that $V^n$ is also a $\Bbb K$-vector with respect to component wise addition and component wise scalar multiplication? If so what can we say about $\dim (V^n)$ in terms of $\dim (V)$?
Answer: Yes, this is indeed a vector space. Also, if $V$ is finite dimensional and $\{e_1,...,e_n\}$ is a basis then it is easy to prove that the set:
$\{(e_1,0),(e_2,0),...,(e_n,0),(0,e_1),(0,e_2),...,(0,e_n)\}$
is a basis of $V^2$, and hence $\dim(V^2)=2\dim(V)$. It follows by induction that $\dim(V^n)=n\dim(V)$.
Comment: Yeah. You are absolutely right. Thanks for your help.

Isn't $V^n$ a $\Bbb K$-vector space?


Difference between Rjct-T and Mask-T in electronic drum trigger settings — Millenium MPS 600

Question: I have the Millenium MPS600 drum module. The manual is a bit poor in terms of detailed information about the trigger settings. From experimentation and looking at manuals  ( ie it's own as well as manuals for similar Roland and Yamaha gear ) I have figured out what most of them do, but to me 'Mask Time' ( Mask-T) and Reject time (Rjct-T) ... at least I assume it's Reject Time ... seem to be the same or very similar ... or at least I don't know what Rjct-T is.
all the manual says is ..

Rjct-T This parameter affects the suppression time, i.e. the response time of the trigger after playing it.
Answer: I'll agree totally that the manual is not very informative, but my best guess (without the oppertunity to try it out on the device) is that it as to do with the messy world of trigger signals. The device simply needs to have some heuristics about what is a real stick hit, and what is just noise that comes from a particular stick's rebound, the vibrations and shock reflections from the mounting and stand and all kinds of unwanted signals.
This means that one setting of these parameters might work for you at home in a rehearsal situation, but other setting is needed on stage with a full band and PA. Also, one type of stick might need one setting, another stick need a different setting..
My best guess about the difference between 'mask' and 'reject' is that 'mask' is the initial time from the very first trigger signal (when the signal goes from 'low' to 'high'), and ignoring the very first repercussions of the initial hit, before considering another hit. This might be the most important setting by far.
I would then guess the 'reject' time is that when the signal went 'low' again (after minimum 'mask' time), it will reject further triggers ('high' signals) for the duration of 'reject' time. This could come in handy if your stick or mounting or stand or stage or stage dancers (!) are particularly bouncy.
If I am correct, you should experience that the two time settings sum up, fx if you set them both to the max value, I would expect a total of 3 seconds from the first hit and until the next hit will trigger a sound. This might behave differently depending whether you play a roll or just a repeated hit.
In practice, just set both settings as low as possible so you can play as fast as you like/need while avoiding unwanted double triggers, but beware that your surroundings might impact the settings.


If $\gcd(m,n) = 1$, show that $m^{φ(n)} + n^{φ(m)} ≡ 1 \mod{mn}$

Question:
If $\gcd(m,n) = 1$, show that $m^{φ(n)} + n^{φ(m)} ≡ 1 \mod {mn}$

The only similar problem I found to this in my notes was "Find all positive integers $n$ such that $φ(n) = 12$." Unfortunately this was no help and I'm really lost, any help is really appreciated.
Answer: Since $\gcd(m,n)=1$, you know from Euler-Fermat that
$$
m^{\varphi(n)}\equiv 1\pmod{n}
$$
and, similarly,
$$
n^{\varphi(m)}\equiv 1\pmod{m}
$$
Since $n^{\varphi(m)}\equiv 0\pmod{n}$, we also have
$$
m^{\varphi(n)}+n^{\varphi(m)}\equiv 1+0\pmod{n}
$$
and, similarly,
$$
m^{\varphi(n)}+n^{\varphi(m)}\equiv 1+0\pmod{m}
$$
Now use the Chinese Remainder Theorem.
Comment: Or use the following property (and the definition of mod): $$a,b\mid n\iff \text{lcm}(a,b)=\frac{ab}{\gcd(a,b)}\mid n$$


Retorno de verificação é enviada três vezes

Question: Ao clicar no botão, executa esse código a baixo
Ele era gerar apenas uma posição do array. No caso é gerado 3 posições, como se houvesse acontecido 3 testes
<code>$(document).on('click','#btnSegundaEtapa',function () {

    var arrayObjCat1 = [];

    $(".form-group").find('*').each(function(){
        var id = $(this).attr("id");

        if($(this).is(':checked')){
            if ( $("input[type='radio'][name='Licenciamentodeusuários']").is(':checked') ) {
                className = $("#"+id).data('class-name');
                vlrUnitario = $("."+className).text();

                vlrUnitario = vlrUnitario.replace("$","");
                vlrUnitario = parseFloat(vlrUnitario.replace(',','.'));
                arrayObjCat1.push({part_number:$('#'+id).data('part-number'), nome_item:$('#'+id).data('nome-item'),qtde:$('#'+id).val(),preco_unitario:vlrUnitario});
                console.log(arrayObjCat1);
            }

         }
     })

});
</code>
E acontece esse retorno
Comment: Você está executando `console.log` dentro da função `each`, isso quer dizer que irá imprimir no console cada vez que passar pelo loop. Experimente colocar o console fora do loop que irá imprimir apenas uma vez.
Comment: Considere explicar melhos seu problema
Comment: apertei para publicar sem querer, olha se ficou mais claro
Comment: Gabriel, qual é a pergunta ou o que não está a funcionar como queres?
Comment: Eu quero que esse dado só seja executado 1 vez e não as 3 vezes
Comment: Tens `$(".form-group").find('*').each(` isso vai fazer o código correr várias vezes...
Comment: Mas ele gera um array de 3 posições, isso que não quero
Answer: <code>$(document).on('click','#btnSegundaEtapa',function () {

    var arrayObjCat1 = [];

    $(".form-group").find('*').each(function(){
        var id = $(this).attr("id");

        if($(this).is(':checked')){
            if ( $("input[type='radio'][name='"+id+"']").is(':checked') ) {
                className = $("#"+id).data('class-name');
                vlrUnitario = $("."+className).text();

                vlrUnitario = vlrUnitario.replace("$","");
                vlrUnitario = parseFloat(vlrUnitario.replace(',','.'));
                arrayObjCat1.push({part_number:$('#'+id).data('part-number'), nome_item:$('#'+id).data('nome-item'),qtde:$('#'+id).val(),preco_unitario:vlrUnitario});
                console.log(arrayObjCat1);
            }

         }
     })

});
</code>
o codigo acima solucionou meu problema


Normality test with large data set

Question: I think I am dealing with this issue
http://www.r-bloggers.com/normality-tests-don%E2%80%99t-do-what-you-think-they-do/
I have large data set(10k data points) that slightly diverges from normal, and I get p-value of 0. I am interested in having perhaps a more crude test that tells me if data is extremely divergent from normal, versus looking somewhat normally distributed. I am currently trying Kolmogorov-Smirnoff, and in both cases I just get p-value of 0. Any alternatives?
I also looked at this:
Is normality testing 'essentially useless'?
So, taking all this into consideration, is there any kind of test I can perform that distinguishes between data that's roughly normal, and not normally distributed at all?
I am using scipy.
Comment: One of the very best ways is to look closely at the probability plot, because it will show you precisely *how* the data "diverge" from normal.
Comment: The p-value is not the test statistic.  Any distribution test, such as the Kolmogorov-Smirnov, will provide you a statistic that measures how far the data depart from a random sample of a Normal distribution.  It seems that you're asking us to propose a bad test, but you haven't provided any information about exactly how bad it needs to be.  That's going to be difficult to interpret and answer.
Comment: I'd always support use of probability plots here; and also the view that **the probability plot itself is a test statistic**. But it's better to measure non-normality, as that sounds like a better goal for your tastes, than to focus on P-values. (BTW, the P-value may be reported as 0, but it's just very small, not 0.) Classical measures are skewness and kurtosis; better measures in many ways are their L-moments equivalents. Many threads on this forum on both.
Comment: Because you have already applied some kind of test, what's the matter with reporting *its* test statistic?
Comment: Sure, but I want to output some sort of summary statistic as well(this is part of an automatized process that should not involve human intervention),
Comment: Because it is always 0, even when the data is approximately normal. Please see the links I have provided. I want the test to actually make a difference, and not be 0 all the time.
Comment: Thanks for your input. Is there any kind of test for 'approximate normality' (that you probably call bad test) you would recommend?
Comment: A normal probability plot will show that. Also a kernel density plot with reference normal superimposed. The best test statistics need not be single scalars; nor can a scalar catch everything that might be interesting or important about a distribution. (An outlier is usually an individual data point, not an odd distribution.)
Answer:
a more crude test that tells me if data is extremely divergent from normal

You very likely don't want hypothesis tests at all, since they don't answer that question.
You're trying to answer a question related to "effect size" ("how far from normal is it?" is an effect-size type question) but hypothesis tests don't answer that question.
Some goodness of fit statistics (as whuber suggested in comments) do give a measure of "how far from normal"..., as does looking at say a Q-Q plot, like Nick Cox mentioned, but I bet you have a more specific question than would not necessarily be well answered by using some measure essentially at random.
For example, you might perhaps have an underlying question nearer to "How badly could this particular kind of inference I wish to use be affected by the kind of (and degree of) non-normality of the distribution from which my data were drawn?"
[The answer to that depends on what you're trying to do! Different forms of inference have may be sensitive to different aspects of the distribution, and to differing degrees. More detail would be necessary before useful advice could be given for a question like that.]
You may have some other kind of question of course, but how to measure impact on whatever you're trying to do will again depend on what you're trying to achieve.
Comment: I am dealing with measuring Pearson's correlation, for the purpose of evaluating feature quality. This is basically an OLS on 1 variable, Sometimes I get reasonably high correlation(10%), but when I look at the plot, it is completely bogus. After some thought, I realized that those scenarios violate most of the OLS assumptions. So, I want to catch these cases automatically, so I can know that the obtained correlation is not valuable.
Comment: The "bogus-ness" of what you're trying to do probably relates more to other things than normality. What were you actually testing for normality? (Alternatively, what is it you think needs to be normal in OLS?)
Comment: I am looking at the errors. If I am to correctly evaluate a signal(feature), and try the correlation I obtain, I also want the errors to be normal, when doing the OLS of the target on that feature. Is this right?
Comment: You need something more or less near normality if you are performing inference that relies on it (like hypothesis tests or confidence intervals based on normal assumptions)

Normality test with large data set


Executar stored procedure no banco oracle em PHP

Question: Tenho a procedure "exemplo1" a qual recebe 3 parâmetros de entrada e nenhum de saída, como faço para executar a mesma em PHP.
No caso seria assim.
EXEC "exemplo1"('para1','para1','para3');

Como fica o codigo em PHP testei assim e não deu certo
$sql = 'EXECUTE "PORTAL_importaXml"'. "(?,?,?)";
$stmt = Conecta::prepareOrc($sql);
$stmt->bindParam(1, $p1);
$stmt->bindParam(2, $p2);
$stmt->bindParam(3, $p3);
return $stmt->execute();`

Desde já agradeço.
Comment: Qual biblioteca de conexão você está usando? OCI8 ou PDO? Aparentemente é PDO.
Comment: Estou usando PDO, algum problema em relação ao uso dela? Se só funcionar na OCI8 tem algum exemplo para conexão.
Comment: O exemplo 5 é o que você precisa. Esta é a documentação oficial http://php.net/manual/en/pdo.prepared-statements.php
Answer: Não precisa pôr aspas no nome da procedure:
$sql = 'EXECUTE PORTAL_importaXml (?,?,?)';

Comment: Desta maneira também não funcionou, utilizo para conectar o banco o PDO.