how to add common variable for laravel and pass this data to all view all views

Question: I want to create a global variable and pass this into all view, so I can get this variable into all blade template
basically, my need is to pass my general setting controller value into my common blade view like header.blade.php
Thanks in advance
Answer: For that you will need to add some code in the App->Providers->AppServiceProvider.php like this:
public function boot()
    {
        view()->composer('*',function($view){

            $settings = Settings::firstOrNew(['id' => '1']);
            $view->with('settings', $settings );

        });
    }

Comment: May be its help you to store data in common variable because boot Run first and store data in variable and after that you just have to pass the data in to your views like above @pixlogix show the code if this is not work post comments I will help you but I think Ik no it's work fine because this is correct way to do this
Answer: According to Laravel documentation you can use view composer:
https://laravel.com/docs/5.8/views#view-composers
for using this feature in app > AppServiceProvider and in boot method you can use this approach for passing parameter to specific view If you have data that you want to be bound to a view each time that view is rendered. this approach meet your need perfectly. for example you want to pass a parameter named userName to header.
View()->composer('header', function ($view){
    $userName= "username"
    $view->with(['userName'=>$userName]);
});


How do I set the default umask in apache?

Question: I need to set the default umask in apache on fedora so that my uploaded files have permissions 644 which are set to 600 by default in spite of doing chmod( $uploaded_file , 0644 ); in php script.
Can someone provide some direction...?
Answer: On Fedora, I believe it's in /etc/sysconfig/httpd and you change the umask there -- umask xxx.


Erro de cors acessar Api

Question: Pessoal estou tentando acessar um serviço da wikipedia com JQ, mas esta em retornando erro de cors, alguém poderia me ajudar com um código para acessar esse serviço corretamente.
Url: https://pt.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=google
erro
Requisição cross-origin bloqueada: A política de mesma origem (Same Origin Policy) impede a leitura do recurso remoto em https://pt.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=google. (Motivo: o cabeçalho CORS 'Access-Control-Allow-Origin' não está presente).
Comment: insere o erro para facilitar a ajuda.
Comment: coloquei mas é este Requisição cross-origin bloqueada: A política de mesma origem (Same Origin Policy) impede a leitura do recurso remoto em https://pt.wikipedia.org/w/api.php?action=query&format=json∝=extracts&titles=google. (Motivo: o cabeçalho CORS 'Access-Control-Allow-Origin' não está presente).
Answer: Essa é uma proteção que os navegadores possuem, evitando que um cliente em outro endereço faça uma requisição direto em algum site, salvo o caso em que ele autorize o tráfego externo. Nessas situações, vale a pena tentar usar o JSONP. Em uma requisição AJAX com Jquery fica assim:

var request = $.ajax({
  url: "https://pt.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=google",
  method: "GET",
  dataType: "jsonp"
});

request.done(function( msg ) {
  console.log(msg)
});

request.fail(function( jqXHR, textStatus ) {
  console.log(jqXHR, textStatus)
});

Comment: Tirei um tempinho para ver a API da Wikipedia, e consegui puxar no client. Basta usar `jsonp`. Você está fazendo a requisição com ajax do jquery? Se estiver, coloque `dataType: 'jsonp'`. Aqui funcionou normalmente
Comment: Não que eu conheça. Você teria que realmente construir uma API... Uma saída que eu utilizo nos meus projetos é usar as Cloud Functions do Firebase.
Comment: @JoãoPedroHenrique Eu estava testando justamente isso agora, pode colocar como resposta porque funciona mesmo.
Comment: Caramba que coisa :( existe algum tipo de serviço API para fazer isso ? eu usava um mas parou de funcionar.
Comment: entendi, muito obrigado.
Comment: Feito, Leandro. Valeu pelo toque ;)
Comment: Nossa muito obrigado amigo :D top

Erro de cors acessar Api


Symfony webpack encore twig functions not working

Question: I am generating static html pages using twig in a Symfony 4 project. Am trying to generate multiple pages at the same time with a simple loop and the Twig render function. Code looks like this:
foreach ($pages as $page) {
  $html = $this->twig->render('template', $page);
  $fileSystem->dumpFile('fileName', $html);
}

In the template am using, I load assets via webpack encore twig functions encore_entry_script_tags and encore_entry_link_tags.
The problem I face is that the assets are loaded for the first generated page but not the others ! The generated html content does not contain script and style tags.
I thought about possible Twig cache problem so I set the cache to false but that didn't solve the problem. Also, the problem is gone when I use the standard twig function {{ asset() }} instead of webpack enore twig functions.
Any ideas ?!
Answer: Problem found and solved. Check this link out for details. It's kinda a 'bug', the team still working on at the time I write this. A workaround is presented on the link.
Comment: Thanks for answering yourself. That info could be useful for others


How to set drawableRIGHTon Android button?(IMAGE DINAMICALLY)

Question: Drawable drawable = res.getDrawable(R.drawable.image);
 button.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);

This work but i would all dinamically.
Drawable drawable = res.getDrawable(R.drawable.path);
 button.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);

where path is a string that contains a name of image..
thanks to all!
Answer: If I got you right, you are trying to get drawable by the image name. right?
If so,
int imageResource = res.getIdentifier(path, "drawable", getContext().getPackageName());
Drawable drawable = res.getDrawable(imageResource);

then assign the button drawable...
Comment: OK, than i set this image in the right of botton..it`s correct?  Buttò.setCompound...(.,..,imageResourse,..). I simplify the code on the top
Comment: no, the code doesn't work, i have this error: No package identifier when getting value for resource number 0x00000000
Comment: i would an image in the right of button, the image is in the variable path


What are the benefits of using no beams in simple vocal melody?

Question: I've noticed some of my favorite musicians went out of their way to use no beams while writing vocal melodies. Why would they choose to exclude beams?
There are beams in the music but not the vocal melody.
Here are two examples: "Ridin' Down the Canyon", by Gene Autry and Smiley Burnett; and "When It's Springtime in the Rockies", by  Mary Hale Woolsey and Robert Sauer.
Answer: This is an old-fashioned vocal notation practice. From the looks of it, the music in the question seems old enough to have been written in the traditional style.
Current musical notation standard practice uses beaming to indicate groupings of subdivisions of the beat; in a 4/4 time signature, eighth notes get beamed together in those groupings to visually demonstrate the location of the four quarter note beats in the measure.
This older style of notation for singers has beaming conventions as well. Traditionally, only notes sung on the same syllable would be beamed together. This ostensibly makes it easier to organize the syllables and notes together at sight. In the two examples in question, it happens that no two consecutive eighth notes are sung on the same syllable. This gives it the appearance that no beams are in use, when in fact beaming rules are being applied albeit to no effect.
Other differences from contemporary music notation include the doubling of note values (I would guess it to be sung at a jaunty tempo?): assuming the song is sung around the same speed I'm imagining it to be, I would expect modern notation to write those quarter notes as eighth notes. It seems a bit out-of-touch to have quarter note values represent that kind of vocal melody in the modern style, especially marked "Moderato". In the style this sheet music embodies, it is correct, but this seems dated to me.

As for why this was done? Some shallow research declares that "Ridin' Down the Canyon (When the Desert Sun Goes Down)" was published in 1941, and "When It's Springtime in the Rockies" was first released in the late 1920s (Autry's version out in 1937). These songs are 80 years old by now, and it would not surprise me if the older style of vocal notation was still in some prevalence at the time of writing. Especially so given the genre - country/western music tends to thematically embrace older times, so even if the old style was no longer the most common, I could see a writer/publisher choosing this notation convention out of respect for the history of that kind of music.
Answer: It is a common standard in vocal music to notate every syllable independently and not to beam them.
Beams are reserved for singing multiple notes on the same syllable.
The advantage to the older system of no beams is that it makes clear syllabic versus melismatic singing. The advantage of the modern system of consistent beaming is that it makes the rhythm clear. Both systems are still in use and up to the composer or editor to choose.
Compare the two images below. In the first, there are no beams, because the syllable changes on every note. In the second image, there are beams when a syllable is sung over multiple notes (melisma) and no beams when a syllable is sung to a single note.
Comment: In current sheet music they beam every note no matter what. That's why I question the change in style.                                       https://s3.amazonaws.com/halleonard-pagepreviews/HL_DDS_119997731EH5LTWn6.png                     https://s3.amazonaws.com/halleonard-pagepreviews/HL_DDS_11400688k0Me55DCw.png     https://freshsheetmusic.com/media/catalog/product/j/i/jimmie_rodgers-t_for_texas-musicnotes_thumbnail.png
Comment: There's a load of music still in print that uses the old method.  But not many composers write that way now.
Answer: It's the old style.  OK, it shows where the syllables come, and where there's a melisma (more than one note to a syllable).  But it obscures the rhythmic patterns of the music.  It might have something to do with vocalist's legendary inability to count!  (And I don't altogether offer that in jest.)
The modern style is to beam to the rhythms as for other instruments, and to indicate melisma with a slur.
If there was any real advantage to the old style, it escapes me.


ASP - Page Not Loading until SendEmail function has ran

Question: I have an ASP page that receives data from the previous page through a form.
The ASP page:

Connects to Database
Updates Database
Loads HTML to say your form has been submitted
Email routine that sends a confirmation.

However, the page is not loading until the email routine has ran, even though it's the last routine to be called.
The call "SendEmail" routine, which is at the bottom of the page in a Sub, is called right after the HTML is loaded

<%

Call SendEmail

Sub SendEmail

End Sub
%>

Any help will be much appreciated.
Cheers
John
Comment: Of course it doesn't - ASP is server side, therefore all of your code will run on the server prior to sending its response to the client.
Answer: Classic ASP, like ASP.NET, PHP and so on, are all server side languages.  That means the the script that populates a page is executed prior to a response being sent to the client.  As an example:

This is a test

Some random Lorem Ipsum in a box.

        <%Response.Write("This is also a test
")%>

Some other gobbledegook.

        <%Response.Write("37 + 59 = " & (37+59))%>
        <%SendMail("Whatever message.")%>

<%Response.Write("Something else here.")%>

All this code will execute on the server side before returning something like:
This is a test
Some random Lorem Ipsum in a box.
This is also a test
Some other gobbledegook.
37 + 59 = 96
...(SendMail would execute here)...
Something else here.
If you want sections to run in unison then you'll have to consider invoking them with JavaScript, jQuery or some other similar JavaScript based plugin, or alternatively using (cough) a selection of iframes (gah! nasty!).
Answer:

<%
Response.Flush 'sends buffered HTML output immediately.
Call SendEmail

Sub SendEmail

End Sub
%>

Comment: I now think it's possibly more to do with the server than the code because the simple buffer/flush routine doesn't work either
Comment: Flushing the buffer will not solve this problem at all - it's all to do with the expectation of how a page executes.
Comment: I presumed there would be ASP within the body


How to develop a formula that shows x=0 from positive and negative

Question: In the formula
$\sin(x)/x $  when the limit is approaching $0$.
I have seen videos on how to prove this, but I don't know how to make an excel formula for it.
Answer: Use the Taylor expansion
$$\sin(x)=x-\frac{x^3}{6}+\frac{x^5}{120}-\frac{x^7}{5040}+\cdots$$
$$\frac{ \sin(x)}x=1-\frac{x^2}{6}+\frac{x^4}{120}-\frac{x^6}{5040}+\cdots$$


css, javascript: random image loader with array removes the first part of my variable how to fix this?

Question: I'm trying to set a random image background with css and javascript to a div, but when I load the random image on google chrome it does not work
I tried to do all image urls in variables but this does not work.
does anyone know why it is changing my code and why it is not working
code that loads the random image

where the image is printed

output when I do with google chrome inspect, edit as html

Answer: There are two problems with your code. First, you need to remove the " as you're using variables:
var imageURLs = [
  image1,
  image2,
  image3,
  image4
];

Second, you also need to remove the double-quotes around the url() that you manually inject. Your final function should look like this:

var image1 = "images/image1.png";
var image2 = "images/image2.png";
var image3 = "images/image3.png";
var image4 = "images/image4.png";

var imageURLs = [
  image1,
  image2,
  image3,
  image4
];

function getImageTag() {
  var img = '

';
  return img;
}

console.log(getImageTag()); // For StackOverflow output

Hope this helps! :)
Answer: Remove the " it's not a variable so!
var imageURLs = [
           image1
         , image2
         , image3
         , image4
      ];
Edit:
Function:
function getImageTag() {

  var randomIndex = Math.floor(Math.random() * imageURLs.length);
  var randomIndex = imageURLs[randomIndex];
  var img = '

';
  return img;
}

Comment: tnx but this does not change the output ``
Comment: Ok i hope it helps. I have made a little simpler


NFL betting odds during game

Question: I have a couple of basic questions about NFL betting.

Are betting odds set in stone before the game begins, or do they evolve with the progression of the game?

What are "closing odds?"  Are closing odds made during the game, or before it?
Comment: If a bookmaker offers live betting (i.e., if it possible to place a bet during the game), then odds are of course often changed during the game. (As you can check by having a look some bookmakers page and checking the odds on some in the section for live betting.) The odds also often change before the game starts (even if live betting for the particular fixture is not offered). See, for example, [this answer](http://stats.stackexchange.com/questions/26413/how-do-bookmakers-select-their-opening-odds/69756#69756).
Comment: I should mention that my comment above is based on my experience from betting on other sports. But I do not see a reason why betting on NFL should be different.
Comment: They evolve with the progression of the game of course, since bookmakers make money by splitting bets between two different outcomes and taking a cut (known as juice/vigorish) for themselves (this is why both teams with a handicap bet will have odds of either 10/11 or -110 rather than 1/1 or +100) so if a line opens at +3.5 for team A, and everyone is putting their money on team A, then they will lower the handicap until people start betting on team B)
Answer: 1)
It depends on the bookmaker.
Traditionally, things like the total, money line, and spread will be set before the game starts.  During the game it is possible to choose these same bets for halves of the game and sometimes even quarters of the game.
The odds will change for say the second half bets as the first half plays out.
Some bookmakers may even offer a live/ever changing odds.  You would be able to bet on the winner of the game or total during the game as it evolves.  The only difference is that the odds will change with the result of each play.  This is a very automated system.

2)
Closing odds refer to the last odds offered before the game starts.  When the odds are first chosen by the bookmaker, they are called the opening odds.  You may hear something like "the spread opened at -4.5 and closed at -3".  This means that during the time that the odds were made to the time they were last offered, the spread changed by 1.5 points.  This can be for a number of factors (injury, weather, suspensions, etc.), but usually is changed according to where bets are being placed leading up to the game.  See setting lines.
If you placed a bet at -4.5 then you will be locked in at that spread.
In the example of during the game betting the closing odds for say the second half total would be chosen before kick off of the second half.
Comment: @Jessica If you have specific teams or more information then this website will be helpful. [The Sports Network - Gaming Database](http://www.sportsnetwork.com/merge/tsnform.aspx?c=sportsnetwork&page=nfl/gaming/database.aspx)
Comment: Thanks for your very helpful answer!  Do you know where I might be able to find live odds statistics for old NFL games, like from 2002-2012?

NFL betting odds during game


Why does MCMCpack use normal priors when running Poisson regression?

Question: I thought that since the conjugate prior of Poisson distribution is gamma, we needed to use that when assigning prior distributions to the beta coefficient. MCMCpack and rstanarm both specify a multivariate normal distribution. Can someone explain the reasoning behind that?
Answer: If $Y_i \stackrel{ind}{\sim} Poisson(\lambda)$ and $\lambda \sim Gamma(a, b)$, then $$\lambda | Y_1, \ldots, Y_n \sim Gamma\left(\sum_{i = 1}^n y_i + a, n + b\right)$$ as you pointed out.
However, a Poisson regression is set up in a different way:
If $Y_i \stackrel{ind}{\sim} Poisson(\lambda)$, a regression model for $\lambda$ can defined as
$$
log(\lambda) = \beta_0 + \beta_1 X_{i,1} + \ldots + \beta_p X_{i,p}
$$
where $\mathbf{\beta} = [\beta_0, \beta_1, \ldots, \beta_p]$ is a vector of coefficients. There is no conjugate prior distribution for the $\beta$ in the Poisson regression.
You could define the gamma prior distribution for each $\beta_i$ as you proposed, but then we would state that each $\beta_i$ cannot be negative because the gamma distribution is only defined for positive values.
This could be a problem because you are not allowing that a covariable has a negative relationship with the average number of counts $\lambda$. For example, if
$Y_i$ is the number of children in country $i$ and $X_{i,1}$ is the wealth of country $i$, then $\beta_1$ could be negative indicating that people have fewer children as their countries get richer.
The only case that we have conjugate prior for $\beta$ is the normal linear regression, where the normal prior distribution for $\beta$ is conjugate with the normal distribution for the response variable.
I guess the normal prior distribution for $\beta$ in the Poisson regression just follows the normal linear regression. In addition, the hyperparameters of Normal prior distribution are easy to interpret, a less informative prior (i.e., high variance) is easily defined and the normal distribution is defined on the real line, which means that the coefficients $\beta_i$ can assume any real value.


3D representation of A4 that preserves the unit ball

Question: The subgroup of $\operatorname{GL}_3\left(\mathbb{R}\right)$ generated by the matrices $$\left(
\begin{array}{ccc}
 0 & 1 & 0 \\
 1 & 0 & 0 \\
 -1 & -1 & -1 \\
\end{array}
\right)\,,\hspace{10pt}\left(
\begin{array}{ccc}
 1 & 0 & 0 \\
 0 & 0 & 1 \\
 -1 & -1 & -1 \\
\end{array}
\right)\,, \hspace{5pt}\text{and}\hspace{5pt}\left(
\begin{array}{ccc}
 0 & 0 & 1 \\
 -1 & -1 & -1 \\
 1 & 0 & 0 \\
\end{array}
\right)$$
is isomorphic to $A_4$.
When acting on $\mathbb{R}^3$, this representation does not preserve the unit $3$-ball (i.e. map the unit $3$-ball into itself). Given a $\mathbf{v}=(x,y,z)$ such that $\left\lvert\left\lvert \mathbf{v} \right \rvert\right \rvert<1$, we either have $\left\lvert\left\lvert A\mathbf{v} \right \rvert\right \rvert=\left\lvert\left\lvert \mathbf{v} \right \rvert\right \rvert$ or, up to permutation of the coordinates, $$\left\lvert\left\lvert A\mathbf{v} \right \rvert\right \rvert=\sqrt{x^2+y^2+(x+y+z)^2}$$
which achieves a maximum of $\sqrt{2+\sqrt{3}}$ on the unit $3$-ball.
Is there another representation of $A_4$ in $\operatorname{GL}_3\left(\mathbb{R}\right)$ that does preserve the unit $3$-ball?
Answer: Take a regular tetrahedron inscribed in the unit ball. Work out the
coordinates of its vertices $P_1,\ldots,P_4$. Work out the matrix $R_i$
of a rotation with angle $2\pi/3$
about the axis $OP_i$ with $O$ the origin. Then the $R_i$
generate a copy of $A_4$ (you only need two of them) preserving the unit ball.
Answer: Lord Shark the Unknown gave a fine answer. I want to supplement it with the following generalization.
Assume that you have a finite group $G$ acting on $V=\Bbb{R}^n$ by linear transformations. Let $(\ ,\ )$ be the usual inner product on $\Bbb{R}^n$. Let us define another bilinear form $\langle\ ,\ \rangle$ on $V$ by taking the average:
$$
\langle x,y\rangle=\frac1{|G|}\sum_{g\in G}(gx,gy).
$$
The following are easy to see:

$\langle\ ,\ \rangle$ is bilinear and symmetric.
for all $x\in V$ we have $\langle x,x\rangle\ge0$ with equality only when $x=0_V$.
$\langle gx, gy\rangle=\langle x,y\rangle$ for all $g\in G$ and all $x,y\in V$.

Therefore the new metric given to $V$ by this averaged is invariant under the action of the group $G$. Call the resulting inner product space $V'$. All this immediately implies that balls in $V'$ are stable under $G$.
But, the space $V'$ is really the space $V$, we only changed the metric. You can easily find an orthonormal basis of $V'$. Rewriting the matrices of $G$ w.r.t. such a basis results in orthogonal matrices, i.e. $G$ acts by distance and angle preserving transformations.

You can turn any finite subgroup of $GL(n,\Bbb{R})$ into a distance preserving group (one that thus also preserves balls) by redefining "distance" in a suitable way.

Closing remarks:

This can be generalized to complex matrices and Hermitian inner products with the obvious modifications.
If a subspace $U$ of $V'$ is stable under $G$, then so is the orthogonal complement $U^\perp$ leading to Maschke's theorem.
Averaging arguments FTW.
Comment: Your emphasized statement is weaker than what you prove. It preserves not only a distance, but a distance arising from an invariant scalar product.
Comment: @JyrkiLahtonen Can I convert these into matrices that preserve the original distance? What would I do?
Comment: I tried computing $B=[\langle b_i, b_j \rangle]$ where $b_1=(1,0,0,0)^\intercal$, $b_2=(0,1,0,0)^\intercal$, and so on. Then I multiplied $BA$ for each generator $A$ given in question, but this does not come out right, nor does $B^{-1}A$ or $B^\intercal A B$ or any of that.
Comment: Also I try Grahm-Schmidt algorithm on the $b_i$ using that inner product but don't know what to do with the new vectors. Linear algebra was long ago.
Comment: @WQArielleCosette Unless I made a mistake the quadratic form preserved by the original group is $Q(x,y,z)=x^2+y^2+z^2+xy+yz+zx$. I, too, need to think it thru what to do with that :-)
Comment: @JyrkiLahtonen Well, I did find a unit ball preserving representation for the group in this question,but I now have similar problem with a representation of $C_5\rtimes C_4$ in $\operatorname{GL}_4(\mathbb{R})$. So, I am still want to figuring out how to do it


Appending to text file in android

Question: I am trying to append to a text file that starts off empty and every time the method addStudent() is called it would add a student.toString() line to the said file. I don't seem to get any exceptions but for some reason, after the method call, the file remains empty. Here is my code.
public void addStudent() {
        Student student = new Student();
        EditText fName = findViewById(R.id.first_name);
        EditText lName = findViewById(R.id.last_name);
        EditText studentGpa = findViewById(R.id.gpa);
        String firstName = String.valueOf(fName.getText());
        String lastName = String.valueOf(lName.getText());
        String gpa = String.valueOf(studentGpa.getText());

        if(firstName.matches("") || lastName.matches("") || gpa.matches("")) {
            Toast.makeText(this, "Please make sure none of the fields are empty", Toast.LENGTH_SHORT).show();
        } else {
            double gpaValue = Double.parseDouble(gpa);
            student.setFirstName(firstName);
            student.setLastName(lastName);
            student.setGpa(gpaValue);
            try {
                FileOutputStream fos = openFileOutput("students.txt",  MODE_APPEND);
                OutputStreamWriter osw = new OutputStreamWriter(fos);
                osw.write(student.toString());
                osw.flush();
                osw.close();
            } catch(FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

What might be the problem here? The file students.txt itself is located in assets folder
Answer: The problem may be with the fact that 'assets' directory doesnt exists on phone. So if I understand you correctly you may checking the wrong file.
Comment: Actually this file can be already created if this code works. You can try find it on the phone or read it from code.
Comment: Then should I create the file on the phone and append to that one?
Answer: What might be the problem here? The file students.txt itself is located in assets folder.
If it is in the assets folder then you should use AssetsManager top open an input stream to it. Files in the assets folder are readonly so trying to write to them does not make sense.
FileOutputStream fos = openFileOutput("students.txt",  MODE_APPEND);

That wil create a file in private internal memory of your app. The code looks ok. But it makes no sense trying to find the file on your phone with a file manager or other app as as said that is private internal memory of your app only.
You use a relative path with "studends.txt" and now you do not know where the file resides.
Well the file resides in the path indicated by getFilesDir().
You could as well have used a full path with
 File file = new File(getFilesDir(), "students.txt");

and then open a FileOutputStream with
FileOutputStream fos = new FileOutputStream(file);

Appending to text file in android


Orthogonal Complement of the Column Space

Question: I currently have this problem with this matrix.

Of this matrix i have to calculate the Orthogonal Complement of the Column Space. But nothing is given?
How can you do this?
Answer: The orthogonal complement of $\textrm{Col}(A)$ is $\textrm{Nul}(A^T)$.
The orthogonal complement of $\textrm{Col}(A)$ is the set of vectors $\vec{z}$ that are orthogonal to $\textit{each}$ vector in $\textrm{Col}(A)$, i.e. each vector given by $A\vec{x}$ for any $\vec{x} \in \mathbb{R}^n$. That means for each $\vec{x}$, we have $A\vec{x} \cdot \vec{z} = 0$. Using the definition of the dot product, $\vec{u} \cdot \vec{v} = \vec{u}^T \vec{v}$, this can be written as
$$(A\vec{x})^T \vec{z} = 0$$
Then using the fact that $(XY)^T = Y^TX^T$, we can rewrite this as
$$ \vec{x}^TA^T \vec{z} = 0$$
Since we need this to hold for $\textit{any}$ $\vec{x}$, we need $A^T\vec{z} = 0$ meaning any $\vec{z} \in \textrm{Nul}(A^T)$ is in the orthogonal complement of $\textrm{Col}(A)$
Answer: You want those vectors which are orthogonal to the columns of given matrix $A$. So you want a row vector $x$ such that
$$xA=0$$
Taking transpose
$$A^Tx^T=0$$
So essentially you want to solve for the solution of the homogeneous system with the matrix $A^T$.
note: this exercise is based on the fact that the null space is orthogonal to row space (same as column space of the transposed matrix).
Answer: Given a matrix $A$, you are looking for the space of all vectors $v$ that are orthogonal to the span of the columns. I would try to find an expression for that, using the fact that the being orthogonal to the column space is the same as being orthogonal to all the columns.
Comment: Would it be correct if you turn A into A^T and take the reduced echolvorm of A^T?

And then as last read the vectors out of that matrix
Comment: Yup, see Anurag A's response.


Media Querries Breakpoints estão colidindo

Question: Fala galera!
Eu fiz um site para meu portfólio e justamente nele eu tive o seguinte problema:
O site é feito em uma página só, então eu tive que ajustar o tamanhos das sections para o media querries.
Eu fiz tudo usando o "Responsive Layouts" do WebDev Tools do Google Chrome.
Para os celulares em posição retrato, eu mantive 100vh como a altura de cada section, mas para os celulares em posição landscape, eu tive que aumentar para 120vh ou 140vh, já que a altura do viewport fica muito pequena para suportar o conteúdo.
O problema é, o width do celular deitado colide com o width de alguns celulares de pé. Isto está fazendo com que, para certos aparelhos, eu tenha uma sobra enorme.
Eu tenho CERTEZA que eu to fazendo meleca com os breakpoints. Eu sou um dev novo e essa é uma parte que me quebra muito!
Alguém sabe me dar uns conselhos de como arrumar isso e de boas práticas pros breakpoints dos media querries não colidirem?
Código inteiro: https://github.com/lucasemg/porfolio
Página: https://lucasemg.github.io/porfolio/
@media screen and (max-width:400px) /*celulares retrato*/
@media (min-width:400px) and (max-width:498px) /*celulares landscape*/
@media (min-width:498px) and (max-width:630px) /*Tablets Pequenos Retrato*/
@media (min-width:630px) and (max-width:818px) /*Tablets Pequenos Landscape*/
@media (min-width:818px) and (max-width: 1200px) /*Tablets Grandes*/

insira o código aqui

Answer: Olha isso não é uma resposta absoluta, pq vc tem que analisar aplicando no seu documento, mas a forma que vc está fazendo os @media pode sim ser otimizada usando orientation: portrait ou orientation: landscape

The orientation CSS media feature can be used to test the orientation of the viewport (or the page box, for paged media).

Documentação da Mozilla sobre o orientação de tela: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/orientation
Aqui tem um exemplo básico para te ajudar a tratar esses media queries. Aqui tem um exemplo para orientação retrato
@media only screen
  and (min-width: 400px)
  and (max-width: 498px)
  and (orientation: portrait) {

  /*seu css aqui*/

}

Outro exemplo para orientação horizontal
@media only screen
  and (min-width: 498px)
  and (max-width: 630px)
  and (orientation: landscape) {

  /*seu css aqui*/

}

Isso significa que as 3 regras deve ser verdadeira para aplicar o CSS, o min-width, max-width e orientation devem corresponder ao @media para o CSS aplicar. Aqui vc pode ler mais sobre isso Usar @media, @media screen and ou @media only screen and Tem alguma diferença?

OBS: Esse recurso não corresponde à orientação do dispositivo. Abrir o teclado virtual em vários dispositivos na orientação retrato fará com que a janela de visualização fique mais larga do que alta, fazendo com que o navegador use estilos de paisagem em vez de retrato.
Comment: Putz Hugo, segunda vez que veio me salvar, meu caro! hahahahaha Enfim, muito obrigado, eu desconhecia a propriedade "orientation" pros @media. Eu vou tentar assim que chegar em casa, aí vamos ver se otimiza esse problema


Laravel beanstalk job id not matching

Question: I'm working on a project using laravel 4.2, and i'm sending jobs to a beanstalk queue. When the worker picks up the job to execute, I'm trying to capture the id of the job, and associate it back to the failed_jobs table in the event the job fails.
The problem is that the id returned from the Pheanstalk_Job->getId() method, never matches the id of the entry in the failed_jobs table.
I may be presumptuous in thinking that the two are correlated. If not, then hopefully someone can help with how I can achieve capturing the id of the failed_jobs record as it pertains to the job.
Comment: You would probably be better off inserting your own meta-information in the jobs that you create with a unique ID and checking against that. Any IDs that the beanstalkd returns are likely to be quite transient.
Answer: Ultimately, my solution to create a correlation between the exception that caused the job to fail, and the entry created in the failed_jobs table involved the following steps:

Created a migration that created an exception table that included the exception fields i.e. exception message, code, file, line, and also a field for the beanstalkd job id.
Created a migration that is exactly modeled after the failed_jobs schema provided by laravel with the addition of another field, the beanstalkd job id as well.
Created my own QueueServiceProvider and bound the 'queue.failer' and 'queue.worker' services with my own implementations. My 'failer' implementation extends the Illuminate\Queue\Failed\DatabaseFailedJobProvider and simply adds a method for doing an insert that includes the beanstalkd job id. My 'worker' implementation extends the Illuminate\Queue\Worker and overrides the logFailedJob method to call my own failed job insert method.
In app/config/queue.php I included, 'failed' => ['database' => 'mysql', 'table' => 'exception_failed_jobs'] to tell laravel to use my own failed jobs table called 'exception_failed_jobs'.
In my job handler code, the fire method wraps my business logic in a try/catch, and any exceptions raised, will result in the exception being stored in my exception table, including the beanstalkd job id.

Now all the exceptions raised have a correlation to the failed job record via the job id. The business can now determine the exception that caused the job to fail, and decide whether to correct the underlying issue and retry the failed job, or simply delete it off the queue. I've tested this solution and it works exactly as I need it to. Hopefully this helps anyone else out with the same requirement.
Can't wait to migrate this project off 4.2 and on to the latest version. I understand that the latest laravel has this functionality already baked in :)

Laravel beanstalk job id not matching


Replace/Avoid unicode characters in XML C# while sending XML data to SQL server

Question: Below is the code to create XML data so that I can send the same as a string to Sql server for bulk insert.

<code>private string SavePurchaseInvoiceProducts()
        {
            string xmldata = string.Empty;
            List<ProductDetail> ProductsList = new List<ProductDetail>();
            try
            {
                foreach (DataGridViewRow row in gvPurchaseInvoiceItems.Rows)
                {

                    if (dtBatchDetails.AsEnumerable().Count(i => i.Field<int>("ItemID").ToString().Equals(row.Cells["ItemID"].EditedFormattedValue.ToString())) > 0)
                    {
                        ProductsList.Add(new ProductDetail
                        {

                            ItemID = Convert.ToInt32(row.Cells["ItemID"].EditedFormattedValue.ToString()),
                            StockInHand = Convert.ToDecimal(row.Cells["StockinHand"].EditedFormattedValue),
                            ReceivedQTY = Convert.ToDecimal(row.Cells["Qty"].EditedFormattedValue),
                            NetPrice = Convert.ToDecimal(row.Cells["NetPrice"].EditedFormattedValue),
                            SellPrice1 = Convert.ToDecimal(row.Cells["StockWas"].EditedFormattedValue),
                            Tax_ID = Convert.ToInt32(row.Cells["Tax_ID"].EditedFormattedValue.ToString()),
                            ItemDescription = row.Cells["Description"].EditedFormattedValue.ToString()

                        });
                        row.Cells["StockWas"].Value = Convert.ToDecimal(row.Cells["StockinHand"].EditedFormattedValue);
                    }
                    else
                    {
                        MessageBox.Show("Please complete Batch qty entry for the product " + row.Cells["Description"].EditedFormattedValue.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return "Error";
                    }
                }

                var xmlPBDetails = new XElement("Root",
                                    from pbdetail in ProductsList
                                    select new XElement("InvoiceItemDetails",
                                                   new XElement("ItemID", pbdetail.ItemID),
                                                   new XElement("ItemDesc", pbdetail.ItemDescription),
                                                   new XElement("StockinHand", pbdetail.StockInHand),
                                                   new XElement("NetPrice", pbdetail.NetPrice),
                                                   new XElement("Stock_RecievedQty", pbdetail.ReceivedQTY),
                                                   new XElement("StockInHand_Was", pbdetail.SellPrice1),
                                                   new XElement("Tax_ID", pbdetail.Tax_ID),
                                                   new XElement("StockUpdateReason", "PurchaseInvoice"),
                                                   new XElement("EmpID", GlobalData.EmpID),
                                                   new XElement("Company_ID", GlobalData.CompanyID),
                                                   new XElement("Lastupdated", String.Format("{0:MM/dd/yyyy HH:mm:ss}", DTPInvoiceDate.Value)),
                                                   new XElement("IsDeleted", 0)
                                               ));

                xmldata = xmlPBDetails.ToString();
            }
            catch (Exception ex)
            {

            }
            return xmldata;
        }
</code>

The above code works fine but the only problem is with the line
new XElement("ItemDesc", pbdetail.ItemDescription) where ItemDescription is string
For example if the ItemDescription contains μ (Mu) then the sql server throws an error called ' XML Parsing error an invalid character'.Same is the case with all unicode characters. IF there any Regular expression to completely avoid these characters before sending to database or any other work around.I have tried few methods
http://weblogs.sqlteam.com/mladenp/archive/2008/10/21/Different-ways-how-to-escape-an-XML-string-in-C.aspx but all these only avoid few characters which we define.
Below is the StoredProcedure
<code> Create PROCEDURE [dbo].[inv_Save_InvoiceProductDetails]
    @InvoiceProductDetails as varchar(Max)
    as

    BEGIN
    declare @i int
    exec sp_xml_preparedocument @i output,@InvoiceProductDetails

    INSERT INTO  INV_ProductInvoiceDetails(ProductInvoiceID,ItemID,NetPrice,StockinHand,
    Company_ID,Lastupdated,EmpID,IsDeleted,Stock_RecievedQty,Tax_ID,ItemDesc)
    SELECT ProductInvoiceID,ItemID,NetPrice,StockinHand,Company_ID,getdate(),EmpID,IsDeleted,
    Stock_RecievedQty,Tax_ID,ItemDesc FROM OPENXML(@i,'Root/InvoiceItemDetails',2)
    WITH (
    ProductInvoiceID int,ItemID int,NetPrice numeric(18,2),StockinHand numeric(18,3),Company_ID int,
    Lastupdated datetime,EmpID int,IsDeleted bit,Stock_RecievedQty numeric(18,2),Tax_ID int,ItemDesc varchar(100))

    exec sp_xml_removedocument @i

    END
</code>
So please advice on escaping these characters or any other work around to insert in the database apart from the Encoding/Decoding idea.
Thanks.
Comment: Hm. As both .NET and SQL Server should be fully unicode enabled, I guess the error is somewhere in your code. Maybe you're not passing the right encoding in your XML header? Or you're converting the string to ASCII oder ANSI before passing it to the SQL server?
Comment: In the datalayer I get this error..so there must be some problem in the Storedprocedure.I am not using any encoding in XML header.How do we add that in the above code..please let me know
Answer: Found the solution.When I used XML datatype instead of varchar(max) its saving the details.So the problem is with the datatype of parameter.I have changed to nvarchar(max) and its works fine.
nvarchar(max) did the trick
Prathap


Why is my Views row template not loaded?

Question: I am using Views 3.
I have created my view and get these theme suggestions:

As you can see I created a --presse-page.tpl.php file bold marked in the second block. It works fine, but I need to style only the rows. So I created a views-view-fields--presse.tpl.php file, but if I rescan the theme, it does not appear.
Why not?
Answer: Your file should be called views-view-field--presse.tpl.php. field without an 's' not views-view-fields--presse.tpl.php file
Comment: no, stil not working :(
Answer: check which theme you selected and make sure that same theme is affecting the page.
And check filename present in the theme info and tempate filename are same
also clear cache then rescan it.
May be it helps.
Answer: You have to clear the cache when changing any template file


Default column value in ms access switch statement

Question: how to do this in ms access using switch statement?
Select CASE col1
          when '-' then 'Not Specified'
          else col1
       END

In my understanding it should be smth like this
SELECT
  switch(col1  = '-', 'Not Specified',
         true,  col1 )

or
SELECT
  switch(col1  = '-', 'Not Specified',
         col1  <> '-',  col1 )

However this does not seem to work.
maybe there is an alternative way to do this? What I am trying to achieve here is I would like to replace all '-' values in the data set with some custom text and leave other values unchanged.
I need to be using MS ACCESS SQL only and VBA is out of scope.
Answer: ok, figured out myself
SELECT
  switch(col1  = '-', 'Not Specified',
         false,  col1 )

this seems to do the job :)
Answer: You can try to use replace like this:
update tablename
set columnname = replace( columnName, instr('-',chr(42)), 'STRING_TO_REPLACE_WITH' )


How to address underdispersion in a GLMM

Question: I've read a few entries about underdispersion in count or binomial data, relating to poisson and binomial probability distributions. However, I haven't been able to find any information about gaussian distributions with underdispersed data.
I am currently analysing the average annual change in population size (λ). I have used other metrics of change in population size, but there are reasons I have decided to move forward using average-λ. Below is the distribution of average-λ values.

When I start building a GLMM, I typically start with a GLM and slowly increase the complexity until I get to the GLMM, just so I can see where the problems arise.
Thus, using the formula:
glm(formula = avg_lamda ~ Total_Threats, family = "gaussian", data = x5yr_data)
Output below:
Deviance Residuals:
      Min         1Q     Median         3Q        Max
-0.200553  -0.019402   0.001415   0.021470   0.205119

Coefficients:
                Estimate Std. Error t value Pr(>|t|)
(Intercept)     0.003944   0.002927   1.348 0.178310
Total_Threats1 -0.021170   0.005910  -3.582 0.000372 ***
Total_Threats2 -0.021339   0.005861  -3.641 0.000299 ***
Total_Threats3 -0.012737   0.006340  -2.009 0.045053 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for gaussian family taken to be 0.002372469)

Null deviance: 1.3082  on 533  degrees of freedom
Residual deviance: 1.2574  on 530  degrees of freedom
AIC: -1706

Number of Fisher Scoring iterations: 2

My question is how would I transform the data average-λ values so that my dispersion becomes more acceptable?
I will also be using this data in much more complex models testing threat interaction so I will need to fix this before I get to what I am suspecting will be much more complex models.
Thank you for your time.
Answer: I do not understand why you believe there is anything to fix. The dispersion of a Gaussian GLM is simply the sum of squares divided by the residual degrees of freedom (see help("summary.glm")). As long as it is not in a range hinting at numerical problems or a perfect fit, any value is acceptable. The dispersion is used by summary.glm to derive the standard errors.
Comment: Thank you. I guess I have some more reading to do. During my undergrad I was originally told that deviance should roughly equal degrees of freedom, and that was an indication of under- or over-dispersion should the deviance be lower or higher respectively.
Comment: @Miles https://en.wikipedia.org/wiki/Overdispersion#Normal_distribution


How to change Text in TextCompositionEventArgs

Question: C# WPF - I have a custom editable datagrid that uses my own custom columns that inherit from DataGridTextColumn. In my column class I override GenerateEditingElement so that I can automatically set things like MaxLength, CharacterCasing, etc.
The problem is that when the user highlights a cell, then types their first character, the datagrid auto enters editmode.  So my GenerateEditingElement fires and I'm able to setup the textbox.  Unfortuntately this is too late for charactercasing and the TextCompositionEventArgs already has a lower case char in it. Subsequent types characters are the correct case.
The column class PrepareCellForEdit is what fires next and this has the TextCompositionEventArgs. However, I can't seem to change the text.  I get compile errors that the setter is NOT available. (even though the intellisense help for the property does say get and set).
Is there anyway I can programmatically get my charactercasing into the textbox?
OR
How can I change that text in the TextCompositionEventArgs?
Answer: The main idea is subscribe to TextChanged event of TextBox.
But trick is that you could not update Text propery directly on this event handler.
You must use some small delay to do this.
Here is example which works OK:
<code>    public struct MyData
    {
        public string Name { set; get; }
    }

    public MainWindow()
    {
        InitializeComponent();
        ObservableCollection<MyData> oc = new ObservableCollection<MyData> { new MyData(), new MyData() };
        grid.ItemsSource = oc;
    }

    private void Grid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        var col = new DataGridTextColumn();
        Style myStyle = new Style(typeof(TextBox));
        // subsribe to TextChanged event
        myStyle.Setters.Add(new EventSetter(TextBoxBase.TextChangedEvent, new TextChangedEventHandler(OnTextChanged)));
        col.EditingElementStyle = myStyle;
        var binding = new Binding("Name") {Mode = BindingMode.TwoWay};
        col.Binding = binding;
        e.Column = col;
    }

    private static void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += Worker_DoWork;
        worker.RunWorkerAsync(textBox);
        worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
    }

    static void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        TextBox textBox = e.Result as TextBox;
        if (textBox != null)
        {
            textBox.Text = textBox.Text.ToUpper();
            textBox.CaretIndex = textBox.Text.Length;
        }
    }

    static void Worker_DoWork(object sender, DoWorkEventArgs e)
    {
        Thread.Sleep(1);// This is the trick :)
        e.Result = e.Argument;
    }
</code>


How to pass value from form to url parameter

Question: in my sidebar i have block with a form where users add name of restaurant and when they cick Submit they are supposed to be redirected to a page where my webform is.
I need url like this /add-your-restaurant?key=value-from-text-field but im not sure how to pass that value in url with my form.
I have already %get[key] as default value for my Name field in webform.
This is my html form:
<form name="addres" id="addres" method="post" action="">

<input type="text" name="addresfield" class="resfield" value="Enter your Restaurant name"/>

<input type="button" class="btn"/>
</form>

Comment: this is not Drupal question, its normal html question. change `method="post"` to `method="get"`
Comment: How are you building the form-in-the-lock?  Manual HTML or Forms API?
Answer: This is solution and working form as desired.
<form name="addres" id="addres" method="get" action="add-your-restaurant">
 <input type="text" name="addresfield" class="resfield"
 name="key" value="Enter your Restaurant name"/>
<input type="submit" class="btn"/>
</form>


Is it safe to add /usr/bin to open_basedir?

Question: A hacking incident a couple of months ago taught me the importance of using open_basedir on PHP sites. But now I need to get ImageMagick to work on a Drupal site and I get an error saying it can't access /usr/bin/convert because of open_basedir. /usr/bin and everything in it is writable only by root, but there are a lot of scripts in there, and giving the site access to all of them worries me.
Comment: Update your resume and run like hell.
Comment: Huh? The importance here is not of using `open_basedir` but of not running insecure code and of properly isolating PHP.
Comment: I agree with you completely but, my bosses are not going to give me time to update all the outdated code with known exploits running on our servers. This job is kind of a nightmare.
Comment: How many more "hacking incidents" will it take?
Comment: Good question. My bosses don't seem to understand that server administration is a full time job and I'm also their web developer/programmer/tech support guy.
Comment: LOL, if you'd put that comment in the form of an answer, I'd be tempted to mark it accepted.
Answer: No, it isn't safe to add /usr/bin to open_basedir. Once an attacker can execute arbitrary PHP code they will then be able to execute any command in /usr/bin.
To limit the attack surface area you could create a bin directory under open_basedir and make a link to convert in it. Make sure it isn't under your web root.
Comment: What if I were to create a single bin directory under /usr/local, with a symlink to convert in it? Then I could add that to the open_basedir of all the sites that needed it.
Comment: I would use something nonstandard so others do not accidentally put binaries in it, e.g., /usr/local/php_allowed_bin/
Answer: Obviously we don't know the details of the hack, but in order to exploit something which might have been prevented by setting open_basedir properly then there is a different vulnerability on your system. But that's beside the point.
There are lots of ways to solve the problem - allowing the PHP script limited access to the relevant binaries / setting up the permissions so you can allow access to the dir without exposing lots of other stuff (but unless your imagemagick is statically linked then you'll also need to open up the libs). The problem is that they rely on Byzantine permission models - which are likely to get trampled on by distro upgrades.
If it were me I'd run the conversion in a completely independent process group. How you go about that depends on whether your PHP script needs to know if the job completes successfully or not. If it doesn't need to know, then an asynchrnous message queue (rabbitMQ, SMTP linked to a procmail recipe, or just some records in a database) will process the jobs with manageable capacity. If it needs a confirmation, then run a forking daemon to exec the conversion.


Django Rest Framework - React - Unable to login immediately after logout

Question: This is very strange. I have a react front end and a django backend with djangorestframework and django-allauth for authentication. Everything works fine from Postman. But in the browser when I successfully sign in, successfully sign out, and then try to sign in again, I get a 401 unauthorized error. The correct user credentials are sent to the server just as the first successful time, yet a 401 error. However, after I refresh the browser then I am able to sign in normally again. I use jwt for authentication and I append the token to the authorization header before sign out. I even tried clearing out the authorization header after a successful sign out but to no avail. It is the same problem with my react native front end. I don't know if this is a react or a django problem. Please does anyone have any idea what the problem might be? Thanks.
Answer: The problem solved! I appended the Token to the authorization header like so:
request.headers['Authorization'] = Token ${token}
Except when signing out, every other request did not require the authorization header to be set as above. So after sign out, the authorization header becomes:
request.headers.Authorization = Token null
That null value of the token would make every request after sign out "Unauthorized". So to solve this, I had to set the Authorization header for every request when there is token and then delete the Authorization from the header object when there is no token like so:
delete request.headers.Authorization


Dynamically hiding / showing Field API fields in Drupal 7

Question: I've created an entity with an 'add new' form. The entity itself has a limited number of actual variables. I've added most of the extra data I need using custom Fields (i.e. the Field API).
What I need to do at this stage is be able to dynamically hide one field based on the value of another. i.e. if a drop-down field has it's value set to No, another field should be hidden, otherwise it should be shown.
From what I can see, it is somewhat easy to add this functionality to fields created using the Form API (i.e. via the AJAX property), however is there any way to achieve it using attached fields? I have no issues using custom Javascript if that is what is required to solve this.
Comment: I'm not sure if http://drupal.org/project/conditional_fields is ready to go for d7 yet, but it might be worth looking into
Answer: In Drupal 7, Drupal 8 you can use $form #states instead of custom jQuery script. Example:
  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

  // High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    // This #states rule says that this checkboxes array will be visible only
    // when $form['student_type'] is set to t('High School').
    // It uses the jQuery selector :input[name=student_type] to choose the
    // element which triggers the behavior, and then defines the "High School"
    // value as the one that triggers visibility.
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

Here is example if you want to use #states for multiple values condition:
 $form['student_type'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

  // High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'textfield',
    '#title' => t('What standardized tests did you take?'),
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type[high_school]"]' => array('checked' => TRUE),
        ':input[name="student_type[undergraduate]"]' => array('checked' => TRUE),
        ':input[name="student_type[graduate]"]' => array('checked' => FALSE),
      ),
    ),
  );

See the form_example/form_example_states.inc from examples module for more details and examples.
Comment: See my update above
Comment: Speaking of `#states`, I've never found a way to define more complex visibility conditions, such as: hide control A when control B value is in array(x,y,z). Do you happen to know a syntax for that?
Answer: jQuery works well for this:
(function($) {
  $(document).ready(function() {
    $('#select1').change(function() {
      switch ($(this).val()) {
        case '1':
          $('#field2').hide();
          break;
        default:
          $('#field2').show();
          break;
      }
    });
  });
}) (jQuery);

Comment: Yeah, I ended up using drupal_add_js on the form page and ended up doing it in jQuery. I was just wondering whether there was a more 'Drupal' way to do this.
Comment: I would mention that I'm not a big fan of the Drupal #states approach to visibility, which is why I didn't suggest it above.
Comment: @keithm Could you elaborate please on why you're not a fan of states (as of 2015, D7). I'm working on a project where we're trying to make the decision to use #states vs drupal_add_js. Why do you think one is a better choice over the other?
Comment: It's a matter of legitimate programmer preference in my opinion; my rationale may differ from yours. That said, in practice I rather dislike resorting to another syntax that duplicates functionality found in Javascript/jQuery. When I have tried #states, I also found the use cases for which it is apparently designed too limiting. When my problem extended outside these use cases, I had to rewrite the whole thing in straight Javascript anyway.
Answer: You should try Conditional Fields, I think this module is a must-have for this task. You can set dependencies between fields on a user-friendly admin interface. For example, you can set A field to be only visible if B field has value "1234", or you can set C textfield to be visible only when D field is checked, or set E field to invisible if F is focused etc.
On the upload form, these dependencies will be set client-side, on node display, these dependencies will be set on the server-side.
You can set these dependencies at admin/structure/types/manage/[YOURCONTENTTYPESMACHINENAME]/dependencies.

(Source of the image: the project's page)


Need to reload the web page partially with in the given time

Question: I am having three section in one web page with different data loaded, that data change with some time of interval,
I want to partially reload the web page with the current data loading with some given time limit.
Please help with the solution.
Answer: Add this JavaScript to your page:
It refreshs the page every 5 Seconds

Or if you like to click the button with jquery every 5 Seconds:
<button id="IdOfButton" >Click me </button>

Comment: Thank You Chris, This reload the page, but I want partially load the page with new data display on page.. like if we display watch and it continuously display the current time.


How to find determinant of 4d GPU array

Question: I'm new to using the GPU in MATLAB, I've got 4d array, let's call that A, where size(A) = [100, 200, 3, 3]. I want to do something like:
for i = 1:size(A, 1)
    for j = 1:size(A, 2)
        B(i, j) = det(squeeze(A(i,j,:,:)));
    end
end

If A is already a gpuArray, how can I implement this without the use of for loops? I've tried both pagefun and arrayfun, but they both don't seem to work.
Thanks!
Comment: You don't have a choice but to loop.  `det` works only on square 2D matrices.
Answer: Worked around it by explicitly defining the determinant function. That is
function DET = my3x3det(a11, a12, a13, a21, a22, a23, a31, a32, a33)
    DET = a11.*(a22.*a33 - a23.*a32) - ...
          a12.*(a21.*a33 - a23.*a31) + ...
          a13.*(a21.*a32 - a22.*a31);
end

Then instead of the for-loop, B can be obtained using arrayfun
B = arrayfun(@my3x3det, A(:,:,1,1), A(:,:,1,2), A(:,:,1,3), ...
                        A(:,:,2,1), A(:,:,2,2), A(:,:,2,3), ...
                        A(:,:,3,1), A(:,:,3,2), A(:,:,3,3));

Which works out to be faster than solving for the same thing in a for-loop. It's a little cumbersome, but it works for this case where specifically a 3x3 determinant is needed.

How to find determinant of 4d GPU array


EF code first return subset of columns

Question: I have a table with about 12 columns.  But there are time when I only need 2 or 3 columns.
I am using Entity Framework code first to query the database from my website.
What should I do so that I do not query all the columns but only a subset of columns?
Thanks,
Mike
Answer: You can use a projection to an anonymous type that contains the properties you want, i.e if your Foo entity has the properties A, B and C you could do:
var results = context.Foos.Select( x => new { x.A, x.B });

to retrieve only the properties A and B.

EF code first return subset of columns


Views PHP references

Question: I would like to use Views PHP module in my Drupal Site.
But I don't have any idea on how to use this and I can't find good tutorial for this module.
Anyone who can suggest any references or videos for Views PHP Tutorial?
Comment: This question appears to be off-topic because it is about document references or tutorials.
Answer: There exists good documentation in Project Page of Views PHP module and Documentation under Read Documentation link in project page..

How to Use Views PHP in views filter
How to Use Views PHP as Views Output Field..

Some existing answers and tutorials which can explain better you can find below..
How can I insert PHP code in Views?
http://eureka.ykyuen.info/2012/03/10/drupal-7-add-php-field-to-view/

Views PHP references


Start debugging with Visual Studio from a different folder

Question: I have a Visual Studio solution with set After-build commands. Those commands copy all files from the bin/Debug folder to the SOLUTION/Build/Debug folder.
Now I am trying to run debug from that SOLUTION/Build/Debug folder. Is that possible?
I have found in the Settings -> Debug -> Start External ... option, but this option won't accept a relative path to the executable (we need it relative as multiple developers are working on the project).
Answer: I have found a way how to do this.
First is needed to set in project properties Debug > Start External and Debug > Working directory to absolute paths. Then edit manually project file project.csproj.user and update it like this:
<code><StartAction>Program</StartAction>
<StartProgram>$(SolutionDir)Build\Debug\Prototype.exe</StartProgram>
<StartWorkingDirectory>$(SolutionDir)Build\Debug\</StartWorkingDirectory>
</code>
Then it is working as is needed.


Given an alphabet with 6 non-distinct integers, how many distinct 4-digit integers are there?

Question:
How many distinct four-digit integers can one make from the digits
  $1$, $3$, $3$, $7$, $7$ and $8$?

I can't really think how to get started with this, the only way I think might work would be to go through all the cases. For instance, two $3$'s and two $7$'s as one case, one $1$, two $3$'s and one $8$ as another. This seems a bit tedious though (especially for a larger alphabet) and so I'm here to ask if there's a better way.
Thanks.
Comment: I don't see any other simpler method.
Comment: Thanks for the answer, you simplified it a bit from what I was thinking by focusing on the 7s and the 3s. Cheers.
Answer: Distinct numbers with two $3$s and two $7$s: $\binom{4}{2}=6$.
Distinct numbers with two $3$s and one or fewer $7$s: $\binom{4}{2}3\cdot2=36$.
Distinct numbers with two $7$s and one or fewer $3$s: $\binom{4}{2}3\cdot2=36$.
Distinct numbers with one or fewer $7$s and one or fewer $3$s: $4\cdot3\cdot2\cdot1=24$.
Total: $6+36+36+24=102$

With larger alphabets,
Suppose there are $a$ numbers with 4 or more in the list, $b$ numbers with exactly 3 in the list, $c$ numbers with exactly 2 in the list, and $d$ numbers with exactly 1 in the list.
Distinct numbers with all 4 digits the same: $a$
Distinct numbers with 3 digits the same: $\binom{4}{3}(a+b)(a+b+c+d-1)$
Distinct numbers with 2 pairs of digits: $\binom{4}{2}\binom{a+b+c}{2}$
Distinct numbers with exactly 1 pair of digits: $\binom{4}{2}(a+b+c)\binom{a+b+c+d-1}{2}2!$
Distinct numbers with no pair of digits: $\binom{a+b+c+d}{4}4!$
Total: $a+4(a+b)(a+b+c+d-1)+6\binom{a+b+c}{2}+12(a+b+c)\binom{a+b+c+d-1}{2}+24\binom{a+b+c+d}{4}$
Apply to the previous case: $a=b=0$, $c=2$, and $d=2$:
$0+0+6\binom{2}{2}+12(2)\binom{3}{2}+24\binom{4}{4}=102$


Digest authentication not working on IE8, Firefox and Chrome are fine

Question: I have a website with digest authentication required and when I browse it with IE8, it gives me 401 even the password is correct. Firefox and Chrome works correctly. I checked the authorization headers with Fiddler, everything seems fine. Can you give me any hints on the problem?
p.s. Additionally I do have the same problem with implementing digest authentication in C#, I don't know these two are related.
Comment: Here's the server header.

Server: Apache/2.2.13 (FreeBSD) mod_ssl/2.2.14 OpenSSL/0.9.8e DAV/2 mod_wsgi/2.8 Python/2.5.4 PHP/5.2.12 with Suhosin-Patch
Answer: I was facing this problem and this was the only mention of it on the net. In Digest Access Authentication the sequence of events that take place is.

GET on /url
401 with a WWW-Authenticate header
This pops up the login dialog on your browser. After you enter your credentials.
GET on /url along with the Authorization header.
200 OK  (If everything goes well).

This works fine for Firefox and Chrome but was not working fully for IE8.
By fully I mean, that if I did a GET on a virtual location on the server it worked, but it did not work when I did a GET on a static file. In the case for a static file I was prompted for a login again and again.
After using a sniffer I found out that in the case of requesting a virtual location the sequence of events happened as mentioned above, but when I requested a static file the sequence was as follows:

GET on /url
401 with a WWW-Authenticate header
This pops up the login dialog on your browser. After you enter your credentials.
GET on /url        (WITHOUT THE Authorization header)
401 Un-Authorized.

Basically when it was a static file, it took the username and password but never sent it across in the Authorization header. Server not getting this header responded with 401 which again prompted the login.
To make IE8 work properly you have to fool it in thinking that this is not a static file, but is a virtual location. For me, it was easy as I had access the server's source code. I really don't know how to do it, if you don't have access to it.
If you have requested a virtual location.
1. GET /virtual_location
2. 401 with WWW-Authenticate header which will look something like
WWW-Authenticate: Digest realm="firstname.lastname@example.com", domain="127.0.0.1:80", qop="auth", nonce="9001cd8a528157344c6373810637d030", opaque="", algorithm="MD5", stale="FALSE"
Notice the opapue parameter is an empty string.
On the other hand if you requested a static-file
1. GET /staticfile.txt
2. 401 with WWW-Authenticate header which will look something like
WWW-Authenticate: Digest realm="firstname.lastname@example.com", domain="127.0.0.1:80", qop="auth", nonce="81bd1ca10ed6314570b7362484f0fd31", opaque="0-1c5-4f7f4c1e", algorithm="MD5", stale="FALSE"
Here the opaque parameter is a non empty string.
Hence, if you an ensure that the opaque parameter is always an empty string, IE8 will consider it as a virtual location and the request will go through normally. Since I had access to the the server's code I was able to do this.
Hope this is of any help.
Regards,
Satya Sidhu
Answer: I had the same problem.  In my case, I was requiring digest authentication for my entire site, using directives in either "<Directory />" or "<Location />".  Either way works for Firefox and Safari on Mac, PC, and iOS.  Unfortunately, IE8 seems to have trouble with this.  After trying several other changes, I finally found that if I only require authentication on a subdirectory (e.g.  "<Location /private>"), and move my content into the protected directory, IE8 started working.  I went back and forth a few times, changing only this attribute, to confirm that this is the critical difference.
Incidentally, it's worth noting that a tcpdump showed that IE8 wasn't even trying to send a digest authentication.  It presented the auth dialog box, took my username and password, then sent a normal GET request with no authentication info.
Are (were) you protecting the entire content tree?
I'm not sure why IE8 (and only IE8) cares about this distinction, but this is what I found.
In searching for a solution to the problem, yours was the only mention that seemed relevant, and I could find no answer posted on the net.  This leads me to believe that either no one tries to configure Digest authentication in this way, or most people just give up and use Firefox (or some other non-MS browser)
Answer: Wow, I'm definitely having the same problem.  I have two virtual hosts, both using digest authentication.  On one site I am trying to protect the entire site (i.e. ) and it works in all browsers I have tried except IE8.  On the other site, I'm only protecting a subdirectory, and that works fine in IE8.
Answer: I had the same problem and tried to use the digest authentication for the whole vhost. But the following configuration did not work on IE.
<Location />
    AuthType Digest
    AuthName "Login"
    AuthDigestDomain /
    AuthUserFile /path/to/.htdigest
    Require valid-user
</Location>

The workaround in http://lists.centos.org/pipermail/centos/2013-January/131225.html worked well:
ErrorDocument 401 "some random text"

A better solution is to exclude the apache error pages that are normally located at /error/.*
e.g.
Alias /error/ "/usr/share/apache2/error/"

The following configuration worked well for me (see also https://bz.apache.org/bugzilla/show_bug.cgi?id=10932#c5):
<LocationMatch "^/(?!error/)">
    AuthType Digest
    AuthName "Login"
    AuthDigestDomain /
    AuthUserFile /path/to/.htdigest
    Require valid-user
</LocationMatch>


Computing Confidence Intervals for Odds Ratio Based on Fitted Values

Question: I am trying to figure out how to get confidence intervals for odds ratios that were computed based on model fitted values from a logistic regression.
Here's an example with the basic idea:
<code>#Load packages
library(vcd)
library(dplyr)
data(Arthritis)

#Create binary outcome for logistic regression
Arthritis$Y <- ifelse(Arthritis$Improved=="None", 0,1)

#Fit Model
fit <- glm(Y ~ Sex + Treatment, family=binomial, data=Arthritis)

#Create small set to predict on, get fitted values, SEs, and odds
df <- expand.grid(Sex=levels(Arthritis$Sex),
                  Treatment=levels(Arthritis$Treatment)) %>%
  mutate(link=predict(fit, newdata=., type="link"),
         se=predict(fit, newdata=., type="link", se.fit=T)$se.fit,
         odds=exp(link))

#Odds ratio with 'Female, Placebo' as referent
df$OR <- df$odds/filter(df, Sex=="Female" & Treatment=="Placebo")$odds
</code>
Can I compute a confidence interval for the odds ratios? I've seen other responses showing how I can get a CI for the fitted estimates, but not for ratios based on those estimates. Thanks.
Answer: As I've commented at Stack Overflow, you could bootstrap them:
<code>library(boot)
set.seed(42)
bootres <- boot(Arthritis, function(DF, i) {
  fit <- glm(Y ~ Sex + Treatment, family=binomial, data=Arthritis[i,])
  df <- expand.grid(Sex=levels(Arthritis$Sex),
                    Treatment=levels(Arthritis$Treatment)) %>%
    mutate(link=predict(fit, newdata=., type="link"),
           se=predict(fit, newdata=., type="link", se.fit=T)$se.fit,
           odds=exp(link))
  df$odds/filter(df, Sex=="Female" & Treatment=="Placebo")$odds

}, R = 1000, strata = interaction(Arthritis$Treatment, Arthritis$Sex))

apply(bootres$t, 2, quantile, probs = c(0.025, 0.5, 0.975))
#      [,1]       [,2]      [,3]      [,4]
#2.5%     1 0.06236299  2.397555 0.3620032
#50%      1 0.21591348  6.295761 1.4285296
#97.5%    1 0.65358623 20.641313 5.2671106
</code>
I show stratified bootstrap here, but you get very similar results for non-stratified bootstrap.


Why is this equation not representing a superellipse$?$

Question: Any equation of the form $$x^n+y^n=1$$ represents a superellipse. But when I plot $$x^{999}+y^{999}=1$$ I get something uncanny.
This is certainly not a superellipse. What is this shape called$?$ Is desmos not working properly as it is not giving the plot of a superellipse$?$ Is this because of the high power in the variables$?$
Any help is greatly appreciated.
Comment: Why the downvotes? This is a perfectly legitimate question (in my opinion).
Comment: What do you get? How exactly do you plot? Can't you paste the resulting image?
Comment: @hans, Downvotes tend to be more correlated with the position of the stars than with the legitimacy of questions...
Answer: In the positive quadrant your picture really does show a quarter of a superellipse (and it nearly looks like a square, as it should, because of the high power).
If $x$ and $y$ are both negative, then obviously $x^{999}+y^{999}$ is negative as well, so it can't equal $1$, and your picture correctly shows no curve in that quadrant.
And if $x$ and $y$ have opposite signs and absolute value greater than $1$, then we must have $y \approx -x$ in order for $x^{999}+y^{999}$ to equal $1$, so you would expect to see something which looks much like the straight line $y=-x$, so your picture is correct there too.
In order to get the full superellipse in all quadrants, you need to use the correct equation, which is $|x|^{999}+|y|^{999}=1$.
Comment: To further add to this great answer, the $y = -x$ is actually an oblique asymptote of this equation. Mathematically, one can see why: $$y = \left( 1 - x^3 \right)^\cfrac{1}{3} = -x\left(1 - \dfrac{1}{x^3} \right)^\cfrac{1}{3}$$ This also applies when $n = 999$ or any odd $n$. Of course, having an asymptote means the super-ellipse no longer takes the shape that we are used to, of an everyday ellipse.
Answer: Have you tried other odd exponents? For instance, $x^3+y^3=1$ gives a very similar graph, just smooth, without edges, and without a cutoff: the graph goes on toward the upper left and the lower right edges of the screen.
This is a general pattern: superellipses with even exponents start like a circle and get closer to a square as the exponent increases. Superellipses with odd exponents start as a straight line (with $x+y=1$) and develop that hump which starts out smooth but becomes edgier as the exponent increases.
For an exponent of $999$, it should be close to perfectly edgy, which is what you're seeing in your picture. But a computational constraint will now occur: For $|x|$ or $|y|$ larger than $1$, $x^{999}$ and $y^{999}$ grow huge extraordinarily quickly. But desmos has to calculate them in order to compare them to decide wether to draw a point or not. Either the numbers are just too large to compute, or the accuracy of the calculation decreases so far that the comparison isn't accurate anymore.
Disclaimer: I'm not perfectly sure wether the graph is actually called a superellipse, or if the name superellipse is reserved for equations of the form $|x|^n+|y|^n=a.


Circle inscribed in Pythagorean triangle

Question: Given the question (from Burton):
"For an arbitrary positive integer $n$, show that there exists a Pythagorean triangle the radius of whose inscribed circle is $n$."
My solution is $3n$,$4n$,$5n$ while textbook hints at a solution of $2n+1$,$2n^2+2n$,$2n^2+2n+1$
The latter seems to describe a  Pythagorean triangle with side lengths that form a primitive Pythagorean triple while mine obviously does not except for the case $n=1$. Is that what is expected if the question does not specify? How does one approach generating such a primitive solution?
The text only says " let us define a Pythagorean triangle to be a right triangle whose sides are of integral length"
Answer: Your example fully answers the question as put.
For a primitive triple, suppose it has the standard representation $s^2-t^2,2st,s^2+t^2$ where $s$ and $t$ obey the usual conditions. Then the perimeter $p$ is $2st+2s^2$, and the area $A$ is $st(s^2-t^2)$.
If $r$ is the radius of the incircle, then $rp/2=A$, so $rp=2A$.
For an incircle of radius $n$, we want $n(2st+2s^2)=2st(s^2-t^2)$. Cancellation simplifies this to $n=t(s-t)$.
The simplest way to achieve this is to let $s=n+1$ and $t=n$. That ensures $s$ and $t$ are relatively prime and of opposite parity. For $n$ odd we can let $t=1$ and $s=n+1$.
These are the only possibilities for $n=1$ or $n$ an odd prime. Other alternatives are available for $n$ with a more complicated multiplicative structure.
Comment: That is very clear,  thank you
Comment: You are welcome.
Answer: For a triangle   with sides $a,b,c$ and area $E,$ and inradius $r,$ let $s =(a+b+c)/2.$ We  have $E=rs.$  Now if $a^2+b^2=c^2$ then $E=a b/2$ and $r=E/s=a b/(a+b+c).$ When also $a,b,c$ are positive integers, there are positive integers $k,d,e$ with $\{a,b\}=\{2 k  d e, k(d^2-e^2)\}$ and  $c=k(d^2+e^2).$ $$\text {This gives}\quad r=\frac {a b}{a+b+c}=\frac {2 k^2 d e (d^2-e^2)}{2 k(d e +d^2)}=k e (d-e).$$ Now  given positive integer $n$  let $n=2^p q$ where $p$ is a non-negative integer and $q$ is an odd integer.$$\text {Let }\; k=1,\;e=2^p\text { and}\;  d=e+q=2^p+q.$$ Then $r=n$  and $\gcd (d,e)=1, $ while $d,e$ are not both odd, so $\{a,b,c\}=\{2 d e, d^2-e^2,d^2+e^2\}$ is a primitive Pythagorean triplet..... Remark: To show that in any triangle ABC with area E, we have $rs=E \;$: Let $O$ be the center of the incircle $\Sigma$ and let $\Sigma$ be tangent to $BC$ at $A^*$. Since $A^*O$ is perpendicular to $BC$, the area of triangle $BOC$ is $(1/2)(BC)(A^*O)=(1/2)r a.$ Similarly the areas of COA and AOC are $(1/2)r b$ and $(1/2)r c.$ Adding these we have area $E=(1/2)(r a+r b+ rc)=rs.$
Answer:
The given the question from Burton is:
"For an arbitrary positive integer $n$, show that there exists a Pythagorean triangle the radius of whose inscribed circle is $n$."

That means there is a series of Pythagorean triangles whose inradii is $n$, means either $1,2,3,....,n$.
From Euclid's formula, if $m$ and $n$ $(m \gt n)$are positive integer co-primes with different parity, you can achieve all primitive Pythagorean triangles $(a,b,c)$ where $a = m^2-n^2$, $b=2mn$, and $c= m^2+n^2$. Suppose $m=n+1$ where $n$ is all positive integers $(n=1,2,3,..., \infty)$. Thus,
$$a = m^2-n^2 = (n+1)^2 - n^2 =(2n+1)(1) = 2n+1$$
$$b = 2mn = 2(n+1)n = 2n(n+1)$$
$$c= m^2+n^2=(n+1)^2+n^2= n^2 + 2n +1 +n^2=2n^2+2n+1$$
Thus, suppose following right triangle has following measurements:

$BC = a$, $AC = b$, and $AB = c$.
The perimeter $(p)$ of the triangle is:
$$p=a+b+c=(2n+1)+(2n^2+2n)+(2n^2+2n+1)=4n^2+6n+2$$
The area $(q)$ of the triangle is:
$$q= \frac12 \times a \times b = \frac12 \times (2n+1) \times (2n^2+2n) = n(2n+1)(n+1) $$
Also, you find: $OF = OD =OE = r$ where $r=$ the radius of inscribed circle, and
$$q = BOC + AOC + AOB = \frac12 (a \times r + b \times r +c \times r) = \frac12 \times r(a + b +c)\\ = \frac12 \times rp = \frac12 \times r(4n^2+6n+2)= r(2n^2+2n+1)$$
$$\therefore \ \ r(2n^2+3n+1) = n(2n+1)(n+1)$$
$$r(2n+1)(n+1) = n(2n+1)(n+1)$$
$$\therefore \ \ r = \frac{n(2n+1)(n+1)}{(2n+1)(n+1)} = n$$
Thereore, for an arbitrary positive integer $n$, there exists a Pythagorean triangle $(a,b,c)$, the radius of whose inscribed circle is $n$.
The $(a,b,c)$ is describe with $n$ as $(2n+1,2n(n+1),2n^2+2n+1)$, that is what your text book provided.


How can I retrieve $a$ and $b$ from $2^a \cdot 3^b\,$?

Question: When given a number $k$ in the form $2^a \cdot 3^b$ with integers $a,b$ , I want to use a function $f(k)$ to retrieve $a$ and a function $g(k)$ to retrieve $b$.
I know that prime factorization can help but I want to try avoid algorithmic approaches. I tried taking $\log_2 k$ and $\log_3 k$, but was unsuccessful in manipulating the results to isolate $a$ or $b$.
$$\log_2 k = a + b \log_2 3,$$
$$\log_3 k = b + a \log_3 2.$$
Thanks
Comment: Why is it bad to use "*"?
Comment: Please, avoid the use of `*` to denote multiplication. That's a common practice in programming, not in Mathematics. When using MathJax simply write `2^a 3^b` ($2^a 3^b$) or `2^a\cdot 3^b` ($2^a\cdot 3^b$)
Comment: This problem is equivalent to finding the integer points on the line $2^x3^y=k$. (This is indeed a line, since we can take logarithm each side as you've done.) Also, there can be only one integer point on the line (for appropriate k, that is, integer k's only having 2 and 3 as prime divisors ), since if there are two, then this violates the uniqueness of integer factorization. Hope this gives some insight.
Comment: @markvs that is good question, i dont see any advantage with dot over asterisk, they both valid notation for multiplication to me
Comment: https://www.wolframalpha.com/input/?i=solve+k+%3D+2%5Ea+%5Ccdot+3%5Eb+for+a
Comment: @markvs, the asterisk is often used in non-math formatting, for instance for creating *italic* or **bold** text (those have 1 and 2 pairs of asterisks around them). It's almost never used in mathematical notation, except sometimes as alternative to "prime" or the like.
Comment: @EricSnyder: So what? Letter "E" is used in many places too, and still you use it in your name.
Comment: hello there fellow @math_enthusiast :)
Comment: @MathEnthusiast314 wow i see in your reddit you make epic desmos graphs!
Comment: @math_enthusiast thanks, thanks for checking it out:)
Answer: I'm not sure how to interpret the question since ultimately anything you write down in math is going to correspond to some kind of algorithm. That being said, here's one way to try to do it which you can use in programs such as Desmos.
We know that $2^a \le k$ so we can round $k$ down to the nearest power of $2$ and write:
$$2^a = \gcd(k,2^{\lfloor \log_2(k)\rfloor})$$
In other words we have,
$$a = \log_2(\gcd(k,2^{\lfloor \log_2(k)\rfloor}))$$
Of course this is completely general for positive integers, so we can write the p power dividing $k$, called the p-adic valuation $v_p(k)$ as,
$$v_p(k) = \log_p(\gcd(k,p^{\lfloor \log_p(k)\rfloor}))$$
Here's a corresponding example in desmos to demonstrate.
Comment: THANKS THIS WAS EXACTLY WHAT I WAS LOOKING FOR, it is uncanny that i was looking for this in desmos and you just happened to also include desmos in your answer!!!


My SQL - return the rolls/ids from a where clause list which is not exist in table?

Question: The below query is a sample query. I am trying to get an idea from u guys. I wrote a query which return those results which has found in table but i used many rolls in where clause list, but all rolls are not found in database.
SELECT  roll,name,phone FROM my_tbl where roll in (1,2,3,4,5,6)

This query gives the result like

Roll    Name    Phone
2       name1   123
3       name2   345
6       name3   785

That query returns only those result which is stored into the table.
But I want to get all of rolls which is used in clause (1,2,3,4,5,6).
My expecting result should be like

 Roll   Name    Phone
    1       n/a      0
    2       name1   123
    3       name2   345
    4       n/a      0
    5       n/a      0
    6       name3   785

Is it possible ? If possible then how ?

Answer: You need a derived table with the values:
select *
from (select 1 as roll union all
      select 2 as roll union all
      . . .
      select 6 as roll
     ) r left join
     my_tbl t
     using (roll);

This fills in the values for the unknown rolls with NULL, which seems like a suitable values.
Comment: I have 50k+ roll . So is it possible to write select 1 as roll union all ......... select 50000 as roll union all ???
Comment: @SSopno . . . You can do that.  I would think, though, that if you have so many then you have a table with all the values.  And you can use that table.


Gitlab CI/CD with conditional scripts

Question: Here is what I wish to do in GitLab CI/CD:
Whenever something is pushed into a specific branch I wish to have multiple scrips and CI/CD should decide which script should be run based on the pushed files list.
For example:

IF anything changed in ./resources/assets/views/* then run SCRIPT1
IF anything changed in ./database/* then run SCRIPT2
etc...

Do you Lads have any idea for it?
Answer: You can achieve this using rules:changes keyword:
<code>job1:
  script:
    - ./script1.sh
  rules:
    - changes:
      - resources/assets/views/**/*

job2:
  script:
    - ./script2.sh
  rules:
    - changes:
      - database/**/*
</code>
Comment: Holy  sh*t  dude.  This question is not  relevant anymore because it  was already done. :D But thanks for the answer, I've marked it, so others can see it.

Gitlab CI/CD with conditional scripts


Use $\operatorname{ord}_{11}3$ to find remainder when..

Question: Find $\operatorname{ord}_{11}3$.  Then use what you found to find the remainder when you divide $3^{82}$ by $11$.
Work thus far:
$$\operatorname{ord}_{11}3=\  ?$$
$$3^1\equiv3\pmod{11}$$
$$3^2\equiv9\pmod{11}$$
$$3^3\equiv5\pmod{11}$$
$$3^4\equiv4\pmod{11}$$
$$3^5\equiv1\pmod{11}$$
$$\operatorname{ord}_{11}3=5$$
Not sure how to use this to find the remainder through.
Thanks
Answer: If by $\,ord_{11}3\,$ you mean the order of $\,3\,$ in the group $\,\Bbb F_{11}^*=\left(\Bbb Z/11\Bbb Z\right)^*\,$ , then working modulo $\,11\,$ in the following we get
$$ord_{11}3=5\Longrightarrow 3^{82}=\left(3^5\right)^{16}\cdot 3^2=1\cdot 9=9$$
Comment: How does $(3^5)^{16}$ become $1$?  Because $ord_{11}3=5$?  Are we using the fact that $3^5\equiv1 \pmod{m}$?
Comment: Yes, of course.
Answer: Hint $\rm\ \color{#0A0}{3^5}\equiv \color{#C00}1\:\Rightarrow\: 3^{2+5K}\!\equiv\, 3^2 (\color{#0a0}{3^5})^K\!\equiv\, 3^2(\color{#C00}1)^K\!\equiv\, 9$
Answer: We know that $3^{10} \equiv 1 \pmod{11}$
So $\operatorname{ord}_{11} 3 \in \{2,5, 10\}$.

$3^2 \equiv 9 \equiv -2  \pmod{11}$
$3^4 \equiv 4 \pmod{11}$
$3^5 \equiv 1 \pmod{11}$

So $\operatorname{ord}_{11} 3 = 5$.


Problema com Banco de Dados interno

Question: Estou tentando manipular um banco de dados interno com o seguinte código:
sql = "CREATE TABLE IF NOT EXISTS tipo ([codigo] integer autoincrement,nome text not null);";
bancoDados.execSQL(sql);
sql = "INSERT INTO \"tipo\" VALUES(1,\"ESTADUAL\");";
bancoDados.execSQL(sql);
sql = "INSERT INTO \"tipo\" VALUES(2,\"MUNICIPAL\");";
bancoDados.execSQL(sql);
sql = "INSERT INTO \"tipo\" VALUES(3,\"PRIVADA\");";
bancoDados.execSQL(sql);
sql = "INSERT INTO \"tipo\" VALUES(4,\"FEDERAL\");";

O erro que estou tendo é o seguinte:
03-23 20:22:26.419: E/Database(368):
Failure 19 (PRIMARY KEY must be unique) on 0x92ba0 when executing
'INSERT INTO "tipo" VALUES(1,"ESTADUAL");'

Eu já tentei algumas coisas: tirar o número que eu mesmo estava inserindo (por estar com um autoincrement), mas não deu e continuou o mesmo erro... Alguém sabe o que está errado?
Comment: No INSERT ou você coloca a lista de campos (omitindo o campo codigo que será gerado automaticamente) ou terá que informar o valor de todos os campos (o que você não fez no primeiro INSERT). Limpe sua tabela e refaça os INSERTs de uma única forma. Para verificar o que foi incluído rode um SELECT * FROM "tipo" .
Answer: Seu banco de dados está vazio? Seu campo código é auto-incremento, então se tiver um único registro que seja então o código 1 já estará "ocupado". O ideal quando se lida com campos desse tipo é deixar que o próprio sistema atribua os códigos/IDs para você:
INSERT INTO "tipo"(nome) VALUES("ESTADUAL");
INSERT INTO "tipo"(nome) VALUES("MUNICIPAL");
INSERT INTO "tipo"(nome) VALUES("PRIVADA");
INSERT INTO "tipo"(nome) VALUES("FEDERAL");

Usando essa sintaxe você atribui somente um [ou mais] campo específico, omitindo aqueles que não precisam ser atribuídos.
Nota: se esse for um script pra popular o banco de dados, talvez seja o caso de não executá-lo mais de uma vez. Caso contrário, cada vez que você o fizer uma nova linha será criada para cada um deles, de novo e de novo...
Comment: Cara, valeu mesmo! Eu não tava percebendo esses erros bobos que eu tava cometendo, tava pensando que podia ser problema do SQL Server, tava pirando... Arrumei as coisas e agora tá dando tudo certo, valeu mesmo!

Problema com Banco de Dados interno


Why [:1] and [0] do not generate the same result?

Question: Why do method 1 and method 2 not print the same output?
<code>>>> names = ["Apple", "Samsung", ]

# Method 1/Print the first item in names
>>> print(names[:1])
['Apple']

# Method 2/Print the first item in names
>>> print(names[0])
Apple
</code>
Answer: Slicing syntax (Method 1) always produces a new list, even if the new list has only one item.
Indexing (Method 2) produces the item at that position in the iterable.
Comment: I think this is definately adequately explained in the dupe, e.g. this answer https://stackoverflow.com/a/4729334/6260170
Comment: @Chris_Rands The question was not "explain slice notation".  It's not clear the OP knew it was *called* slice notation.
Comment: @Chris_Rands I do know a few things about slicing but actually I have never learned it deeply. Generally, problems like these confuse me so much.
Comment: I didn't downvote the OP but it's clearly a dupe, the answer i linked to even says "indexing gives items, not list" and "Slicing gives lists"


Product distribution of two uniform distributions which are centered around 1

Question: Consider the product distribution $Z = X_1\cdot X_2$ for
$$
\begin{aligned}
  X_1 &\sim \textrm{Uniform}[1 - a, 1 + a] \quad, \quad 0 < a < 1 \\
  X_2 &\sim \textrm{Uniform}[1 - b, 1 + b] \quad, \quad 0 < b < 1 \\
\end{aligned}
$$
I derived the CDF as follows (similar to this answer) but I'm having doubts that it is correct since a comparison with random sampling shows quite some deviation.
$$
\begin{aligned}
  F_Z(z) &= \textrm{Pr}[Z \leq z] \\
         &= \int_{1-a}^{1+a} \textrm{Pr}[X_2 \leq z/x] \, f_{X_1}(x) \; dx \\
         &= \int_{1-a}^{1+a} F_{X_2}(z/x) \, f_{X_1}(x) \; dx \\
         &= \int_{1-a}^{1+a} \frac{\frac{z}{x} + b - 1}{2b} \, f_{X_1}(x) \; dx \\
         &= \frac{b - 1}{2b} + z\cdot\frac{\tanh^{-1}(a)}{2ab}
\end{aligned}
$$
I estimate this CDF using the following Python snippet:
<code>import numpy as np

np.random.seed(0)

def F(z, *, a, b):
    return (b - 1) / (2*b) + z * np.arctanh(a) / (2*a*b)

def estimate(z, *, a, b, N=10**7):
    x1 = np.random.uniform(1 - a, 1 + a, size=N)
    x2 = np.random.uniform(1 - b, 1 + b, size=N)
    return np.mean(x1*x2 <= z)

def compare(z, *, a, b):
    e = [estimate(z, a=a, b=b) for _ in range(7)]
    diff = F(z, a=a, b=b) - np.mean(e)
    print(f'[{z=}, {a=}, {b=}] {diff} vs. {np.std(e)}')

for ab in [0.1, 0.2, 0.3, 0.4, 0.5]:
    compare(1.0, a=ab, b=ab)
</code>
which gives:
<code>[z=1.0, a=0.1, b=0.1] 0.0011786436966352287 vs. 9.239367413632735e-05
[z=1.0, a=0.2, b=0.2] 0.005161311390312617 vs. 0.00016954833637446384
[z=1.0, a=0.3, b=0.3] 0.012021147160144685 vs. 0.00013443702569435986
[z=1.0, a=0.4, b=0.4] 0.02242172114071983 vs. 0.0001156793157035264
[z=1.0, a=0.5, b=0.5] 0.037655831525252426 vs. 0.00018787333770497807
</code>
So the deviation grows quite big compared to the standard deviation of the estimates. However I can't spot what's wrong with the above formula. I'm glad for your help.
Answer: The CDF of $X_2$ is piecewise depending on the value of $z/x$.  Specifically, we have $$\Pr[X_2 \le z/x] = \begin{cases} 0, & z/x \le 1-b \\ \frac{z/x - (1-b)}{2b} & 1-b < z/x \le 1+b \\
1 & 1+b < z/x. \end{cases}$$  Therefore, your integration must consider the separate outcomes where the interval of integration $x \in [1-a, 1+a]$ is intersected/partitioned by these different cases.  Since the density of $X_1$ is uniform, we obtain
$$F_Z(z) = \frac{1}{2a} \left(\int_{x=c}^{d} \frac{z/x - (1-b)}{2b} \, dx + \int_{x=d}^{1+a} 1 \, dx \right),$$ where $$c = \max\left(1-a, \frac{z}{1+b}\right) , \\ d = \min\left(1+a, \frac{z}{1-b}\right).$$
Comment: I understand the reasoning behind the piecewise definition of $F_{X_2}$. But doesn't that place an upper bound on the $x$ integral? That is the boundaries of the right integral should be $\int_{1-a}^{c}$?


Loop infinito tentando calcular se o número é primo

Question: Estou sem ideia de como vou determinar a condição do for para números primos. Sempre acabo em looping.
#include <stdio.h>

int main() {

    int num = 1, primo;
    do {

        printf("Informe um numero primo maior que 1:");
        scanf("%d", &primo);

    } while (primo <= 1);

    for (num=1; num<=primo; primo++){

       if (primo%num==0)
           printf("Numero primo",primo);
       else
           printf("Numero não primo",primo);
    }

}

Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Para programar tem que pensar em tudo como o problema realmente é. Não adianta chutar coisas. Isto não é programar. Uma das coisas que ajudam clarificar os pensamentos é manter o código bem organizado, fácil de ler e entender, incluindo dando nomes para variáveis que são significativos, que indiquem o que realmente aquele nome representa. Tem que pensar bem o nome correto para tudo, caso contrário gera confusões como visto neste código.
Você só consegue saber se um número é primo ou não depois de ter testado todas possibilidades, não tem como saber testando cada uma das possibilidades, então a verificação não pode estar dentro do laço.
#include <stdio.h>

int main() {
    int i, numero;
    do {
        printf("Informe um numero primo maior que 1:");
        scanf("%d", &numero);
    } while (numero <= 1);
    for (i = 2; i < numero; i++) {
        if (numero % i == 0) {
            break;
        }
    }
    if (numero == i) {
        printf("Numero primo %d", numero);
    } else {
        printf("Numero não primo %d", numero);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: @FelipeAvelar sim, claro, obrigado.
Comment: Eu não quis complicar para ele que está começando neste caso. Eu já tenho uma resposta que eu uso esta técnica. http://pt.stackoverflow.com/a/50500/101
Comment: No for, acredito que seja `i < numero`, não?
Comment: Ou você poderia otimizar o código para `i*i <= numero`, já que você só precisa ir até `numero^(1/2)` pra saber se ele é primo ou não. (:
Answer: Para verificar se um número é primo ou não, você não precisa fazer todas as verificações de 2 até n. Porque o número 2 é o único número primo par, logo, pra verificar se 11 é primo ou não, você só precisa verificar até 5,porque os números restantes são múltiplos de 1, 2, 3, 4 e 5, ou seja, 3x2=6, 4x2=8 e 5x2=10, como todos os números naturais multiplicados por 2 são pares, logo não serão primos, com exceção de 2.Então assim, se você for verificar se um número muito grande é primo ou não, você vai obter o resultado mais rápido.
int isPrimeNumber(int num){
    if(num <= 1){
        return 0; //Retorna falso
    } else {
        int quant = num / 2;
        for(; quant >= 2; --quant)
            if(num % quant == 0)
                return 0; //Retorna falso
        return 1; //Retorna verdadeiro
    }
}

Código no ideone: Número primo


How to play low b note on soprano recorder

Question: is it possible to play low B (below middle C) on soprano recorder? If it is possible, how to play it? Do you have the chart? (hole)
Thank you
Answer: By design, the lowest note on a soprano recorder is C5 (which is in fact an octave above middle C). And unlike the high end, the low end of a wind instrument's range can't be arbitrarily extended through agressive overblowing or something, so this might well be answered "it's just not possible".
However, a B4 can actually be intoned, if badly, by partially covering the end hole of the recorder, in combination with very low blowing pressure.
So, just play the normal C with all standard holes covered and then also close the end hole partially. When playing while seated, this can be done with the knee.
I think there are also extended instruments available with an extra keyed hole that facilitates playing notes a little below the proper range.
An alternative that's even more awkward is to slightly extend the length of the instrument. Unless your recorder is one-piece, this can be accomplished by not-quite-properly plugging it together. Trouble is, this will change all notes in a hard-to-predict way.
The proper thing to do IMO, if you need notes like B, is to play the whole piece on an alto recorder instead.
Comment: The lowest note on a soprano is C5, not C4 - middle C, for that you'd need a tenor recorder and the same discussion applies, although getting that low B on a tenor is a real trick.
Comment: Upvoted, especially for the mention of the bell key, which isn't something a lot of recorder players seem to be aware of (admittedly, it isn't something easily available). Strictly speaking, the point of the bell key is to play several *high register* notes accurately, although it can be creatively abused. Would upvote again for the final paragraph - playing outside normal range is likely to be out of tune even in the best of circumstances.
Comment: @ohmi you're right, I neglected the "transposing" clef.
Comment: We could extend this to consider the semi-official way of getting an extra low semitone out if the larger saxophones which is to, literally, 'put your foot in it'.