Logic: Translate the following into everyday English

Question:
Translate the following into everyday English. Note that everyday English does not use variables.
In the following wfs $A^1(x)$ means $x$ is a person, $A^2(x,y)$ means $x$ hates $y$.

$i)\exists x (A^1(x)\land\forall y (A^1(y)\to A^2(x,y)))$
$ii)\forall x(A^1(x)\to\forall y(A^1(y)\to A^2(x,y)))$
$iii)\exists x (A^1(x)\land\forall y(A^1(y)\to(A^2(x,y)\leftrightarrow A^2(y,y))))$
I did i)
i) For every person, there exist another person such that the second hates the first person.
Is it correct?
Also note that I first translate the proposition inside $\forall y (A^1(y)\to A^2(x,y))$
How do I translate $ii)$ and $iii)$?
This is very difficult help please
Answer: Your (i) is incorrect.
Try writing out the definitions of the symbols $\exists$,$\forall$,$\implies$, $A^1$,$A^2$ then simplifying the English.
(i) reads "there exists $x$ such that $x$ is a person and for every $y$, $y$ being a person implies $x$ hates $y$.
More simply this is just "some dude $x$ hates all people"
Try the other two by first writing out the literal meanings then simplifying.
Comment: Sure it does! Someone's name might be $x$.  If you'd like, you could remove it to get "there exists a person who hates all people". Or even more simply, "someone hates everyone".
Comment: Everyday english doesn't use variables and you used variables in $i)$ (x andy), why?
Comment: ok, I translate ii) but I get confused when I try to simplify, "For every $x, x$ being a person implies that for every $y, y$ being a person implies that x hates $y$"
Comment: First simplify the second part "for every y, y being a person implies x hates y", so x hates all people.  Thus the statement becomes "For every x, x being a person implies x hates all people".  Can you get the last step?
Comment: "everyone hates everyone" or "everyone hates all people"?
Comment: Yep! Both of those statements work.


Does AUC/ROC curve return a p-value?

Question: When reading this article, I noticed that the legend in Figure 3 gives a p-value for each AUC (Area Under the Curve) from the ROC (Receiver Operator Characteristic) curves. It says:

The area under the curve (AUC) is 1.0 (p < .001) for the overall
  D-IRAP scores, 0.95 (p < .001) for the female picture bias scores and
  0.94 (p < .001) for the male picture bias scores.

I'm helping a friend who is developing a similar study. To draw the ROC curves and calculate their AUC, I'm using the R pROC package, which has a function called roc() which returns a roc object. Analyzing this roc object, however, I couldn't find anything similar to a p-value. What am I missing? How did the authors of the cited article come to that p-value? I couldn't find anything in their methods. Does ROC curves usually come with a p-value?
Comment: You won't usually find p-values with AUROC estimates, it is not really common practice, so you should delve deeper into the article to see how they did it. Possible solutions: simulations or a statistical test (for ex. proportion test).
Answer: No, it doesn't. p-values from ROC areas are new to me, but I read the following:
Mason and Graham (2002) show that the ROC area is equivalent to the Mann–Whitney U-statistic testing the significance of forecast event probabilities for cases where events actually occurred with those where events did not occur.
Function roc.area() of R-package verification applies this approach and uses function wilcox.test() to calculate the p-value. To me, it looks like this was done in the paper you referenced.

Does AUC/ROC curve return a p-value?


Run postgres operator with statement timeout airflow dag

Question: so i've been trying to run 2 postgres operator on my DAG and looks like this:
default_args = {
    'owner': 'local',
}

log = logging.getLogger(_name_)

TEMP_SETTLEMENT ="""
set statement_timeout to 0;
select function_a();
"""

VACUM_SETTLEMENT="""
vacuum (verbose, analyze) test_table;
"""

try:
    with DAG(
        dag_id='temp-test',
        default_args=default_args,
        schedule_interval=none,
        start_date=datetime(2021, 10, 1),
        max_active_runs=1,
        catchup=False
    ) as dag:

        pg = PostgresOperator(
            task_id="data",
            postgres_conn_id="connection_1",
            database="DB_test",
            autocommit=True,
            sql=TEMP_SETTLEMENT,
        )

        vacum = PostgresOperator(
            task_id="vacum",
            postgres_conn_id="connection_1",
            database="DB_test",
            autocommit=True,
            sql=VACUM_SETTLEMENT,    )

        pg >> vacum

except ImportError as e:
    log.warning("Could not import DAGs: %s", str(e))

i keep getting the statement timeout when i try to run the temp_settlement, is there any way to keep the statement_timeout=0?
Thanks
Answer: Update:
Note that PostgresOperator is deprecated. It is best to migrate to apache-airflow-providers-common-sql
Then use:
from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator

SQLExecuteQueryOperator(
...,
conn_id='postgres_default', # specify the Postgres conn_id
hook_params={'options': '-c statement_timeout=3000ms'}
)

If for some reason you are not able to use SQLExecuteQueryOperator then:
For apache-airflow-providers-postgres>=5.5.2
you can do:
PostgresOperator(
...,
hook_params={'options': '-c statement_timeout=3000ms'}
)

For apache-airflow-providers-postgres>=4.1.0
you can do:
PostgresOperator(
...,
runtime_parameters={'statement_timeout': '3000ms'},
)

This capability was added in PR that solved issue.
Original Answer:
You didn't mention it by from your description I assume that the timeout comes from Postgres and not from Airflow.
For the moment the PostgresOperator does not allow to override the hook/connection settings.
To solve your issue you will need to edit connection_1 in the extra field as explained in the docs you will need to add statement_timeout:
{'statement_timeout': '3600s'}

I opened https://github.com/apache/airflow/issues/21486 as a followup feature request to allow setting statement_timeout directly from the operator.
Comment: Sorry my bad @Elad, my timeout comes from the postgres. the function takes long time depends on how many data is coming. if i tried to use my code, the temp will execute 2 different state.
Comment: @YohanesLim do you will need to set this parameter in the connection
Comment: is there any way that i can set this temporary ? if i go to postgres and do the exact query, it will count as 1 state and will run. is there any way to use this using airflow ?
Comment: You can create a custom MyPostgresHook and custom MyPostgresOperator that will have the functionality you want
Comment: Thanks for the information @Elad ! do you know where to find a good example for this? i've been searching yet i got very low reference about this.
Comment: @YohanesLim Check updated answer.
Comment: Thanks. will try to see this new feature. @Elad


Boost undefined reference during compiling

Question: I am getting a compile error trying to compile a simple tester program from the documentation.
C:\DOCUME~1\A\LOCALS~1\Temp\ccRsXzHu.o:tester.cpp:(.text+0xa6): undefined reference to     `_imp___ZN5boost6thread4joinEv'
C:\DOCUME~1\A\LOCALS~1\Temp\ccRsXzHu.o:tester.cpp:(.text+0xb4): undefined reference to     `_imp___ZN5boost6threadD1Ev'
C:\DOCUME~1\A\LOCALS~1\Temp\ccRsXzHu.o:tester.cpp:(.text+0xcf): undefined reference to     `_imp___ZN5boost6threadD1Ev'
C:\DOCUME~1\A\LOCALS~1\Temp\ccRsXzHu.o:tester.cpp:    (.text$_ZN5boost11this_thread18interruptible_waitEy[boost::this_thread::interruptible_wait(    unsigned long long)]+0x4a): undefined reference to     `_imp___ZN5boost11this_thread18interruptible_waitEPvNS_6detail7timeoutE'
C:\DOCUME~1\A\LOCALS~1\Temp\ccRsXzHu.o:tester.cpp:     (.text$_ZN5boost6threadC1IPFvvEEET_NS_10disable_ifINS_14is_convertibleIRS4_NS_6detail13thre    ad_move_tIS4_EEEEPNS0_5dummyEE4typeE[boost::thread::thread<void (*)()>(void (*)(),     boost::disable_if<boost::is_convertible<void (*&)(), boost::detail::thread_move_t<void (*)()> >, boost::thread::dummy*>::type)]+0x23): undefined reference to     `_imp___ZN5boost6thread12start_threadEv'
collect2: ld returned 1 exit status

I am using mingw 4.5 and g++ 4.5.2 on windows. Boost version v1.4.8.
I hope someone can help me solve this problem.
Thanks.
Comment: It looks like you're not linking with boost_thread. Can you post your compile/link command?
Comment: You can't just give it a folder/directory. The -l command must specify the specific library file that you want to link to.
Comment: This appears to be a linking issue.  Did you tell it to link to the appropriate libraries?
Comment: Yes I used g++ -o tester.exe tester.c. I also did it once with -I/location/to/boostfolder but that didn't work either.
Comment: OK, than what lib should I link to?
Answer: It looks like you aren't linking to the boost libraries.
Boost doesn't come with windows since it isn't a standard library. You've got to download the headers and libraries, then include the headers in your project and link to the libraries at compile time. Since you're using g++, this means adding a -l line to your compile command. The -l line must be used with each specific library you want to use also, you can't just specify the boost directory.
This page will help you get started on Windows and this page will help you get started on *nix platforms.
Once you've compiled boost, then in your example, you should compile your program with
g++ -o tester.exe -Lpath/to/boost/libraries/ -lboost_thread tester.c

Comment: Yes I have looked at that page, although it isn't helpful at all. I have installed it with bjam and moved the header files into the right place so it can find it. But all that didn't do it.
Comment: It's not a header problem. It can definitely find the declarations of the boost functions in the header file. Because it's an "undefined reference", this means it's a linking issue. Try finding out the specific library that contains the function definitions for the functions you are trying to call, and then add -l/path/to/that/library to your g++ command.
Comment: You might also be missing the -L parameter which tells g++ where to look for libs. See the section in the *nix link I posted above called "Link Your Program to a Boost Library".
Comment: Oh ok. After you edited your post I got it. But now I still get an "cannot find lboost_thread error" from ld.exe. Even though I specified the libs directory.
Comment: So that means you've properly specified the library, but it can't find it. Maybe try setting LD_LIBRARY_PATH so it knows where to look for the libs? Try googling that error message, something should definitely come up.
Comment: It comes up with other -l errors though (everything buth -boost_thread). But to be sure, the libs/threads dir contains a build, doc, example, src, test and tutorial folder right? Could you tell me how to setup LD_LIBRARY_PATH if that would perhaps solve it?
Answer: Make sure you've got all your libraries linked properly.
Try putting this line first if your thread library is statically defined
#define BOOST_THREAD_USE_LIB

Also, check out  this thread.


Probability distribution exercise

Question: I'm never certain about my solutions on probability problems (applied), analytic probability and measure is good. I want to work as a TA on a engineering course, so i'm preparing myself doing problems. I'm having a bad time on this exercise, i don't know how to attack it. I would really appreciate your help.
An test software engineer at Adobe has proved that the probability that a program has fails is about 0.05. Actually, the test process is divided into two phases.
Phase 1: There is a random sample of 50 programs. If there are 2 bad programs, the lot is accepted. If there are at least 6, the lot is rejected, otherwise goto Phase 2
Phase 2:It's taken a second random sample of 100 software pieces. If the number of bad programs in this phase plus the number of bad programs in the first phase is not bigger than 6, the lot is accepted, otherwise it is rejected.
a) What is the probability that to a lot to be accepted in the first phase
b) If a lot of programs has to be tested by phase 2, what is the probability of been accepted
I would appreciate your help on that
Answer: The random variable representing program failure is Bernoulli, as it only has two states: Pass and Fail. The sum of a sequence of Bernoulli's is binomially distributed, so we will be dealing with that family.
Now we have three possible states:

Batch has no more than two failures - ACCEPT
Batch has between three and five failures - Go to Phase II
Batch has six or more failures - REJECT

The probability that out of a batch of 50, no more than two fail, is P(0) + P(1) + P(2). The probability of getting to Phase II is $P(3) + P(4) + P(5)$. The probability of rejection is the rest, or $1 - P(X \in \{0,1,2,3,4,5\})$. So as $p = 0.05$ we get:
$$
\begin{align}
P(0) = {50 \choose 0}0.05^0 0.95^{50} &\approx 0.076945\\
P(1) = {50 \choose 1}0.05^1 0.95^{49} &\approx 0.202487\\
P(2) = {50 \choose 2}0.05^2 0.95^{48} &\approx 0.261101\\
P(0) + P(1) + P(2) &\approx \mathbf{0.540533}\\
P(3) = {50 \choose 3}0.05^3 0.95^{47} &\approx 0.219875\\
P(4) = {50 \choose 4}0.05^4 0.95^{46} &\approx 0.135975\\
P(5) = {50 \choose 5}0.05^5 0.95^{45} &\approx 0.065841\\
P(3) + P(4) + P(5) &\approx \mathbf{0.421691}\\
P(\geq 6) = 1-P([0,\ldots,5]) \approx 1 - 0.540533 - 0.421691 &\approx \mathbf{0.037776}\\
\end{align}
$$
We have the answer to (a) now. The probability of accepting a lot in Phase I is $\mathbf{0.540533}$
Now for question b. First let's figure out the total possibilities of failure and accpetance in Phase II, or the proportion of the $0.421691$ gets rejected or accepted.
We have three possible entry points into Phase II: failures of 3, 4, or 5 units. If 3 fail, we can accept up to three more out of the 100, if 4 have failed in Phase I, we can only have 0, 1 or 2 fail in Phase II, and if 5 have failed, we must have no more than 1 failure. The possible probabilities are:
$$
\begin{align}
P(0) = {100 \choose 0}0.05^0 0.95^{100} &\approx 0.005921\\
P(1) = {100 \choose 1}0.05^1 0.95^{99} &\approx 0.031161\\
P(2) = {100 \choose 2}0.05^2 0.95^{98} &\approx 0.081182\\
P(3) = {100 \choose 3}0.05^3 0.95^{97} &\approx 0.139576\\
\end{align}
$$
So accepting in Phase II given 3 failures in Phase I is $P_I(3)\cdot P_{II}(0, 1, 2, 3)$ or approximately $(0.219875\cdot(0.257839) \approx 0.056692)$, accepting in Phase II given 4 failures in Phase I is $P_I(4)\cdot P_{II}(0, 1, 2)$ or approximately $(0.135975\cdot(0.118263) \approx 0.016081)$, and the probability of accepting in Phase II given 5 failures in Phase I is $P_I(5)\cdot P_{II}(0, 1)$ or approximately $(0.065841\cdot(0.037081) \approx 0.002441)$.
Question (B) asks for the conditional probability of acceptance given it has entered Phase II. This should be:
$$
P(\textrm{Accept}|\textrm{Phase II}) = \frac{P(\textrm{Accept} \cap \textrm{Phase II})}{P(\textrm{Phase II)}} \approx \frac{.075215}{.421691} \approx \mathbf{0.178364}
$$
Comment: Thank you, you are very clear

Probability distribution exercise


Tomcat não atualiza arquivos

Question: O problema é o seguinte, toda vez que eu altero um arquivo (index por exemplo), reinicio o tomcat(v7) e aperto F5 no navegador, ele fica na mesma, não atualiza nada, ou seja acaba ficando na versão anterior....
Alguém sabe o que pode ser?
Comment: O Tomcat deve estar fazendo cache dos arquivos. Tente fazer [isto](http://luizricardo.org/2012/09/evite-reiniciar-o-tomcat-6-e-deixe-a-inicializacao-mais-rapida/). Se funcionar eu adiciono uma resposta aqui.
Comment: Pode ser cache, se estiver usando o eclipse, click com o botão direito em cima do servidor e va em clear, reinicie o servidor e tente novamente.
Comment: @rray eu já tinha feito isso... Mas não deu certo....
Comment: Também não foi @utluiz
Answer: Naldson esse problema pode acontecer por vários motivos, vou te dar algumas opções pra ver se resolve seu problema, vamos lá.
1° veja se seu projeto esta com Build marcado como automático, no eclipse fica em Project > BuildAutomatically. Se não estiver marque, isso facilita um pouco.
2° Quando vc modifica algo na sua view, lá na aba servers esta mostrando Synchronized ? se estiver mostrando republish clique com botão direito e selecione a opção publish, vá no navegador e clique em F5, veja se funcionou.
3° Tente apertar Ctrl + F5 para atualizar, veja se funcionou.
Caso não de certo, veja se o terminal exibe algum log de erro.

Tomcat não atualiza arquivos


upload_max_filesize not getting updated after httpd restart

Question: I have a RHEL6 box with php and apache.  I want to increase my upload limit to 20MB.  I changed upload_max_filesize parameter in /etc/php.ini.  I restarted the httpd service.  But when I load the php_info() page, I still see a upload_max_filesize of 2MB (the default value).
I have SELinux enabled, but I don't see any recent "avc" entries in /var/log/audit/audit.log (though I have some from a few days ago).  Is there another .ini file I must change?  How can I get an upload_max_filesize value to stick?
Answer: Make sure to edit the right php.ini file. Run the following command to find the right config file -
php -i | grep php.ini

The output will show you the Loaded Configuration File and modify the upload_max_filesize there.
Comment: Thank you so much!  I actually had a syntax error in my php.ini file and didn't know it.  Your hint above gave me the location of the error.  Now everything is working.
Answer: Set the following in your php.ini file
post_max_size = 20M,
upload_max_filesize = 20M
=> Restart your HTTPD service
Check your upload limit now


SOAP Header Authentication in WP7/8 App

Question: I am having a webservice like given below:
                      POST /mobileservice.asmx HTTP/1.1
Host: services.segwaycommunications.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://services.segwaycommunications.com/ValidateUser"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <PlatformAuthentication xmlns="http://services.segwaycommunications.com">
      <UserName>string</UserName>
      <Password>string</Password>
    </PlatformAuthentication>
  </soap:Header>
  <soap:Body>
    <ValidateUser xmlns="http://services.segwaycommunications.com">
      <username xmlns="">string</username>
      <password xmlns="">string</password>
      <resellerid xmlns="">int</resellerid>
    </ValidateUser>
  </soap:Body>
</soap:Envelope>

Now, as we can see here soap header need authentication via a class platformauthentication.
Can anyone help how could I make authentication in windows phone 7/8 app using this webservice?
Ihave searched a lot but nothing has given me a proper solution.
Thanks if anyone can help.
Answer: as per my opinion Json parsing is best
so firrst you need to download Newtonsoft.Json dll for parse web serevice
Just follow bellow step
Step1: Add Service References by right click on add References.
Step2: Now put your web service link on Service References and press go button, And also add Namespace of service Reference

Step3: Now add using Newtonsoft.Json.Linq; name space in your .cs file
Step4: Now add bellow code in your cs file
 WhatsupServices.WhatsUpServiceSoapClient ws = new WhatsupServices.WhatsUpServiceSoapClient();
ws.ContactUsJSONCompleted += ws_ContactUsJSONCompleted;
ws.ContactUsJSONAsync(txtContactUsName.Text, txtContactUsPhone.Text, txtContactUsEmail.Text, txtContactUsComment.Text);

step6: now genrate your resopnce method
 void ws_ContactUsJSONCompleted(object sender, dynamic e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(LogIn.NetworkBusyMsg, LogIn.MsgHdr, MessageBoxButton.OK);
                busyIndicator.IsRunning = false;
            }
            else
            {
                busyIndicator.IsRunning = false;
                string Result = e.Result;
                JObject obj = JObject.Parse(Result);
                string ResultCode = (string)obj["ResultCode"];
                string ResponceMessage = (string)obj["ResponseMessage"];

                if (ResultCode == "1")
                {
                    MessageBox.Show("Thank you for your message. We'll get back to you soon.", LogIn.MsgHdr, MessageBoxButton.OK);
                    NavigationService.GoBack();
                }
                else
                {

                }
            }
        }

Hope it will help you.
If any query than comment here.I wll help you
Soap header authentication
soap header authentication solve in stack overflow
Custom authentication for web service using soap header
Using SOAP Headers to Validate Clients
Comment: Thanks but problem part is

string
string

I have to first authenticate the platform then and only then i can use whatever service is provided.... Help if you know coding about how to do soap header authentication.

SOAP Header Authentication in WP7/8 App


LINQ Lambda only select if exists

Question: I am using NHibernate which is abstracted away using Respositories and services.  We are not allowed to Lazy Load properties, so they have to be selected in the query.
My issue is that I am trying to get the most recent response number from the Answers table, but in many cases the object might not exist, so I am stuck with getting Null Reference exceptions, or "Code should be unreachable" exceptions.
Here is what i'm doing with the approprtiate sections commented.
.
var leaders =
    _storeService.GetAll()
                 .Where( p => p.Id.Equals(storeId) && p.Employees.Any() )
                 .SelectMany(p => p.Employees)
                 .Select(emp => new
                  {
                      LeaderId = emp.Id,
                      LeaderFirstName = emp.FirstName,
                      LeaderLastName = emp.LastName,
                      Followers = emp.Followers
                                     .Select(followers => new

{
    followers.FollowerEmployee.Id,
    followers.FollowerEmployee.FirstName,
    followers.FollowerEmployee.LastName,
    DepartmentName = followers.FollowerEmployee.Department.Name,

    //Problem Area
    AssessmentResponse = followers.FollowerEmployee
                                  .Answers
                                  .First( a => a.Answer.Question.IsPrimary )
                                  .Answer
                                  .Number
                                  //Null Reference Exception
} )

} ).ToList();

I've probably tried 15 iterations of this, not always using .First but sometimes .Single
I don't have access to the repository pattern or any of the NHibernate queries.  Is there a way to avoid this null reference exception with LINQ?  I can't lazy load, so it's a bit of an issue.
Comment: The indentation here is making this *really* hard to read...
Comment: FirstOrDefault maybe?
Comment: I've tried FirstOrDefault, SingleOrDefault, Single, First, Take(1)... Null Reference Exception or "Code Should Be Unreachable".
Comment: The null reference is coming from trying to get the Number property of answer? Could you do a where count is greater than 1?
Comment: Which property is giving you the `NullReferenceException`?
Comment: .Answers might not exist on an employee, also even if it does there might be one that is primary.
Answer: In EF/Linq-2-Sql, this can be made to work by casting to a nullable value since the underlying SQL does null-coalescing:
AssessmentResponse = (int?)followers.FollowerEmployee.Answers
    .First(a => a.Answer.Question.IsPrimary).Answer.Number

I'm not sure what the behavior would be in NHibernate but it's worth a try. If the Number property is already nullable, you could try coalescing it:
AssessmentResponse = (int?)followers.FollowerEmployee.Answers
    .First(a => a.Answer.Question.IsPrimary).Answer.Number ?? some default value

Finally, you could always do an explicity check:
AssessmentResponse = followers.FollowerEmployee.Answers.Any(a => a.Answer.Question.IsPrimary)
    ? followers.FollowerEmployee.Answers.First(a => a.Answer.Question.IsPrimary).Answer.Number ?? some default value
     : null

Answer: Instead of this:
AssessmentResponse = followers.FollowerEmployee
                              .Answers
                              .First( a => a.Answer.Question.IsPrimary )
                              .Answer
                              .Number
                              //Null Reference Exception

Try this:
AssessmentResponse = followers.FollowerEmployee
                              .Where(a=>a.Answers != null && a.Answers
                                                              .Where(a=>a.Answer.Question.IsPrimary)
                                                              .Count > 0)
                              .Answers
                              .FirstOrDefault( a => a.Answer.Question.IsPrimary )
                              .Answer
                              .Number
                              //Null Reference Exception

LINQ Lambda only select if exists


Why are $∇f(x*) = 0$, and $x^T H_x > 0$ necessary conditions for $x^*$ to be minimum?

Question: See the book OPTIMIZATION: Algorithms and Applications by Rajesh Kumar Arora, Page-$56$.

... ...
The necessary conditions for $x^*$ to be a minimum are that
      $$∇f(x*) = 0  \qquad  (3.1)$$
and $x^T Hx $ is positive definite $(x^T H x > 0)$. To ensure this,
  eigenvalues of $H$ are to be positive. Consider a two-variable
  function    $$f_x = {x_1}^2 + {x_2}^2 - 2x_1   \qquad  (3.2)$$
... ...

I have three questions:

What is $Hx$?
What does it mean by the term positive-definite?
Why are
  (a) $\displaystyle ∇f(x*) = 0$, and
  (b) $\displaystyle x^T H x > 0$
necessary conditions for $x^*$ to be minimum?
Answer:
$1$. What is $H$?

The matrix $H$ is referred to as the Hessian matrix, i.e.
$$H = \begin{bmatrix}
  \dfrac{\partial^2 f}{\partial x_1^2} & \dfrac{\partial^2 f}{\partial x_1\,\partial x_2} & \cdots & \dfrac{\partial^2 f}{\partial x_1\,\partial x_n} \\[2.2ex]
  \dfrac{\partial^2 f}{\partial x_2\,\partial x_1} & \dfrac{\partial^2 f}{\partial x_2^2} & \cdots & \dfrac{\partial^2 f}{\partial x_2\,\partial x_n} \\[2.2ex]
  \vdots & \vdots & \ddots & \vdots \\[2.2ex]
  \dfrac{\partial^2 f}{\partial x_n\,\partial x_1} & \dfrac{\partial^2 f}{\partial x_n\,\partial x_2} & \cdots & \dfrac{\partial^2 f}{\partial x_n^2}
\end{bmatrix}$$

$2$. What does it mean by the term positive-definite?

Positive definite means that if you grab any vector $z$, the term $z^T H z$ is always positive for any non-zero $z$. Informally speaking, it is a way of saying that your matrix is "positive". To see that, take a scalar and say it is positive-definite, it just turns out that the scalar is positive.

$3$. Why are
        (a) $∇f(x*) = 0$, and
        (b) $x^T H x > 0$
  necessary conditions for $x^*$ to be minimum?

In 1-dimensional functions, so that you have a local minimum around $x^*$, wiggling around $x^*$ should make your function larger, right? This means that we must have
$$f(x^*+\epsilon )\gt f(x^*)\Rightarrow f(x^*+\epsilon )- f(x^*)\gt 0$$
Taylor series tells us that
$$f(x^*+\epsilon)\approx f(x^*)+\frac{df}{dx}|_{x^*}\epsilon+\frac 12\frac{d^2f}{dx^2}|_{x^*}\epsilon^2+O(\epsilon^3)$$
We can substitute the approximation of $f(x^*+\epsilon)$ to the definition of minimum
$$f(x^*+\epsilon )- f(x^*)=f(x^*)+\frac{df}{dx}|_{x^*}\epsilon+\frac 12\frac{d^2f}{dx^2}|_{x^*}\epsilon^2-f(x^*)\gt 0$$
$$\frac{df}{dx}|_{x^*}\epsilon+\frac 12\frac{d^2f}{dx^2}|_{x^*}\epsilon^2\gt 0$$
Now in $n-$dimensional, which is your case, (note that $\epsilon$ becomes a vector now)
$$\nabla f(x^*)\epsilon+ \epsilon^T \frac 12\nabla^2 f(x^*)\epsilon\gt 0$$
We now use the assumption that $\nabla f(x^*)=0$, which gives
$$\epsilon^T \nabla^2 f(x^*)\epsilon\gt 0$$
Since the term $\epsilon^T A \epsilon\gt 0$ is always positive definite for every $\epsilon$ the condition for local minimum becomes
$$\nabla^2 f(x^*)\gt 0$$
Comment: What is $Hx$ or $Hz$?
Comment: @user366312 It is a vector which is computed upon multiplying matrix $H$ with vector $x$ (to give $Hx$) or vector $z$ (to give $Hz$). Please refer to this article https://mathinsight.org/matrix_vector_multiplication on more insights.


How do I include ? and = in a form redirection?

Question: I have a form and I would like to take the value from it, and use it as input for a page view which is created using exposed filters.
I have created a submit handler for my first form. I then redirect to the page view. The challenge is that I want to include search keys in the redirection. I can't figure out how to get this to work because the characters ? and = are converted.
I have created this function.
<code>function my_module_my_button_submit($form, &$form_state) {
  $url = 'some-path/search?keys=' . check_plain($form_state['values']['input']);
  $form_state['redirect'] = $url;
}
</code>
The URL that is created from this is 'http://site/some-path/search%3Fkeys%3Dtest'; the URL I want is 'http://site/some-path/search?keys=test'.
Answer: In Drupal 6, instead of setting `$form_state['redirect'] with a string, you set it with an array with tree items.
<code>$form_state['redirect'] = array('some-path/search', 'keys=' . check_plain($form_state['values']['input']), '');
</code>
The last item would be a value used as anchor. As in your case you don't need it, pass an empty string.
Comment: Super! Worked perfectly, thanks! (And it was a D6 question).


What exactly does this inequality do?

Question: I  this paper which is titled "KSVD: An Algorithm for Designing Overcomplete Dictionaries for Sparse Representation", in the section about "kmeans algorithm for vector quantization", there is the following paragraph:

we denote the codebook matrix by $C=[c_1,c_2,\dots,c_K]$ the codewords being the columns. when C is given, each signal  is represented as its closest codeword (under $l_2$-norm distance) we can write $y_i=Cx_i$ where $x_i=e_j$ is a vector from the trivial basis, with all zero entries except a one in the jth position. the index j is selected such that
$$\forall_{k \neq j} ||y_i-Ce_j||_2^2 \leq||y_i-Ce_k||_2^2          \\$$

I know how kmeans algorithm works and what does it do, the thing I don't understand is the above inequality and the selection of j.
Answer: The vector $Ce_k$ is the $k$th column of the matrix $C$ for $k = 1,\ldots,K$. So this inequality says that $Ce_j$, that is, the $j$th column of $C$, is closer to $y_i$ in the $l_2$-norm then all other columns of $C$. Another way of writing this is that $j$ is the index such that
$$
\|y_i - c_j\|_2^2 = \min_k \|y_i - c_k\|_2^2,
$$
where $c_k$ is the $k$th column of $C$.

What exactly does this inequality do?


Generate match list from two different content type on price basis

Question: I have two content type A & B in my application. The content type A have some attributes and a price attribute. The content type B have some other attribute and a price attribute.
Now say A have one item as A1 having price value X. And B has one item B1 that has price value Y.
I need to populate items of content A and B based on following price matching algorithm:
<code> (y- 20 percent of y) < X < (y+ 20 percent of y)
</code>
E.g:
<code>content type A :
items price
A1 - 100
A2 - 200
A3 - 300
A4 - 110

content type B :
    items price
    B1 - 80
    B2 - 100
    B3 - 290
    B4 - 310

Final list :
    A1 - B1, B2
    A2 -
    A3 - B3,B4
    A4 - B1,B2
</code>
Can any one suggest me how to archive this in drupal 7.
Answer: it could probably be done using Views

You need Views if
You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month. Views can do a lot more than that, but those are some
  of the obvious uses of Views.

and Views PHP

This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.

Creating a View limited to those content types, and including the relevant fields - it would allow you to create a Global:PHP sort field, in which you could use your formula to determine the sort order. It would be tricky though, since it appears you want to include duplicates and group them together.


Open intervals as union of closed intervals

Question: In Shreeve, it is stated that:

Since an open interval can be written as a sequence of closed intervals, $$(a,b)=\bigcup^\infty_{n=1}\left[a+\frac1n,b-\frac1n\right]$$

How can this be true?
Comment: Does the union of intervals on the right contain $a$? Does it contain $b$?
Comment: Also, beside JVV's comment, does the union contain every $a<x<b$? Can you find a closed interval $[a+1/n,b+1/n]$ that contains an arbitrary $x$ in $(a,b)$?
Comment: Does this answer your question? [Why is $\bigcup_{n=1}^{\infty} [a+\frac{1}{n},b-\frac{1}{n} ]=(a,b)$?](https://math.stackexchange.com/questions/276739/why-is-bigcup-n-1-infty-a-frac1n-b-frac1n-a-b)
Answer: $x \in (a,b) \iff a<x<b \iff$ there is $n \in \mathbb N$ such that $a+1/n \le x \le b-1/n \iff x \in [a+1/n,b-1/n] \iff x \in \bigcup_{n \in \mathbb N}[a+1/n,b-1/n].$


Serialize circular object networks using writeObject / readObject

Question: I'm about to implement
public function writeExternal( output:IDataOutput ):void {...}
public function readExternal( input:IDataInput ):void {...}

to make a set of object serializable.
Although I'm pretty sure, that I implemented all correctly, readExternal(..) at a certain point complains about too few data left to read:
RangeError: Error #2006: The supplied index is out of bounds.
    at flash.filesystem::FileStream/readObject()

I wonder, if I have a circular object network like
A = { left -> B, right -> B }
B = { father -> A }

and I call
writeObject( a )

will Flex serialize the hole object network and each object once and only one?
I did this:

Declared type annotations like this: [RemoteClass(alias="model.MyClass")]
Implemented parameter-free constructors
Declared all classes using implements IExternalizable

SharedObject's send() method is guaranteed to send each object once and only once.
Additional infos:

Reading and writing a ByteArray
Using Remote Object Components
IExternalizable interface

Please have a look at this related question.
Comment: Hm, work suddenly. Probably come back later....
Answer: The meta [RemoteClass] is an instruction for and only for classes used in projects that Flex compiler identifies as using Flex framework. It is basically equivalent to calling registerClassAlias(MyClass, "model.MyClass"); For a number of reasons that extend the capacity of this topic, I'd suggest that you use registerClassAlias instead.
Regarding AMF built-in writer, the behavior is as follows: if the writer receives all objects it needs to write at once (as in a tree, you give it the root node), then it will write fully the object only once, the next time the reference to that object appears, it will use the reference. However, if you continually feed it objects, which may have already been referenced (such as through successive calls to writeExternal) it will treat every object as if it was new. At least theoretically, it should work the other way too. That is if the objects were serialized by reference, once they deserialized, the reference should be used. It would help to see more of your code, particularly the implementation of writeExternal and readExternal to give a better answer.
Comment: Marked as answer, although the actual problem is no longer visible. One problem was, that I called writeExternal() at the top-level, where I should have called writeObject. Internally, inside the serialization code of objects, writeExternal() and readExternal() need to be implemented but need to rely on e.g. writeObject() or readObject(). Regarding class registration: Yes, I'm aware, that class annotations are required to map byte streams to object instances. Thx!


Nginx server blocks and socket.io - CORS

Question: I have been running apps with this server blocks structure for sometime and it has never given me any problems.
geo $authentication {
  default "Authentication required";
  `Some ip number` "off";
}

server {
  listen         80 default_server;
  listen    [::]:80 default_server;
  server_name my.domain.com;
  return 301 https://$host$request_uri;
}

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  ssl_certificate /etc/letsencrypt/live/my.domain.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/my.domain.com/privkey.pem; # managed by Certbot

  include /etc/letsencrypt/options-ssl-nginx.conf;
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

  server_name my.domain.com;
  client_max_body_size 200M;

  root /var/www/;
  index index.php index.html index.htm;

  location / {
    add_header Access-Control-Allow-Origin *;
    auth_basic $authentication;
    auth_basic_user_file /var/www/.htpasswd;
    try_files $uri $uri/ =404;
  }

  # Here is for example the app where I am running socket.io from
  location /myapp {
    auth_basic $authentication;
    auth_basic_user_file /var/www/.htpasswd;
    try_files $uri $uri/ =404;
  }

  # If this app has some sort of api route for express I do a proxy pass
  location /api/upload/ {
    proxy_pass http://localhost:5003/api/upload;
  }

However I am trying to use socket.io and I am having problems understanding if the subfolder is a problem as I keep getting CORS if I try to connect from the client as in
import { io } from 'socket.io-client'
const socket = io('http://localhost:5003')

On the server I got this
import express from 'express'
import { createServer } from 'http'
import { Server } from 'socket.io'

const app = express()
const prod = process.env.NODE_ENV === 'production'
const port = process.env.PORT || prod ? 5003 : 4000
const httpServer = createServer(app)

const io = new Server(httpServer, {
  cors: {
    origin: '*',
    methods: ['GET', 'POST']
  }
})

const connections = []

io.on('connection', (socket) => {
  connections.push(socket)
  console.log(`Socket id ${socket.id} connected`)

  socket.on('disconnect', () => {
    connections.splice(connections.indexOf(socket), 1)
  })
})

httpServer.listen(port, () => console.log(`App listening on port ${port}.`))

I can see that whereas on development it all works fine and it establishes a web socket connection:

On the server after the CORS of course it does not:

No matter what I try, I always end up getting this:
Answer: In your second picture, the socket.io lib is using polling. This may come because you didn't set the nginx config properly.
location /socket.io/ {
    proxy_pass http://localhost:5003/socket.io/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header Host $host;
}

Here is a good example.After changing this you should be able to reach your backend just using the following:
import { io } from 'socket.io-client'
const socket = io()

Notice that if all your request go through the Nginx, you don't need the CORS directives as all your request will be going to the same address and port.
Comment: Thanks but where is `http://wsbackend` coming from? I tried it with `http://localhost:5003/socket.io/` and I get 404
Comment: Is the address of your backend express + socket.io server. If the Nginx and backend are running in the same host you can try with 127.0.0.1, if it is a docker container it is the name of the container/service. from your code `const port = process.env.PORT || prod ? 5003 : 4000` if you don't set is in an env var and you are in development, then the port is 4000
Comment: I am doing this without docker just with a nginx server on ubuntu on linode, when I run the server I can see with pm2 that the app is indeed listening on 5003. I mean I want to run on port 4000 when in dev and 5003 when in production and that part actually works
Comment: are you serving your frontend code also over the nginx, if not you will get the CORS problem.
Comment: The react front end is just accessed when you go to`https://my.domain.com/myapp/index.html` is the front end who access the backend with the proxy_pass from nginx,  when I need to request something from an express route. The nginx file you see is the one that I am using.
Comment: Did you change the frontend code (`const socket = io()`)? If you did you could try `const socket = io('wss://my.domain.com')` to force TLS as you don't have a redirect to port 443 when you connect to port 80.
Comment: When I do that I don't get CORS but the ws tab on network is blank and socket.io do not work
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/119954/discussion-between-alvaro-and-sepef).


Where did I go wrong on this approach?

Question: I have the following DE $y'' + xy=0$, then I have to use power series method to break apart my problem: leading me to then do the following \begin{align}\sum_{n=2}^\infty n(n-1)c_nx^{n-2}+x\sum_{n=0}^\infty c_nx^n&=0\\ 2c_2+\sum_{n=3}^\infty n(n-1)c_nx^{n-2}+\sum_{n=0}^\infty c_nx^{n+1}&=0 \\ 2c_2+\sum_{k=0}^\infty(k+3)(k+2)c_{k+3}x^{k+1}+\sum_{k=0}^\infty c_kx^{k+1}&=0 \end{align} To top it off I got the following zeroes for the equation: \begin{equation}c_2=0\end{equation}\begin{align} c_{k+3}=\frac{-c_k}{(k+3)(k+2)}\end{align}
My question is my approach right and will I got a nice looking factorial in a summation for the end answer or will it be just a infinite sum? I was doing the work and I keep getting two products like for $c_6=\frac{c_0}{6*5*3*2*1}$ I noted that right there I had a 4 missing so I thought if it would be a factorial over a factorial any thoughts I would be grateful.
Comment: @Aryadeva I posted the solution which I was looking for to provide a distinction to that question, and prevent it from labeled a duplicate.
Comment: You can collect the factors in a product of two Gamma functions and a power of $3$. See "Airy functions".
Comment: Looks good to me.. As Lutz said the DE  has Airy's functions in its solution.
Comment: Here is a link to the equation https://math.stackexchange.com/questions/1197528/solution-of-yxy-0
Comment: No problem. I posted Dylan's answer because it's interesting
Answer: Following from your work on can then follow the power series solution method, and by that I mean: \begin{equation}c_0+c_1x+c_2x^2+c_3x^3+c_4x^4\dots\end{equation}
Then you just have to group your solution sets into two solutions, which would be the at most expected from a second order differential equation: \begin{align}y(x)=c_0(1-\frac{x^3}{3\cdot2}+\frac{x^6}{6\cdot5\cdot3\cdot2}\dots)+c_1(x-\frac{x^4}{4\cdot3}+\frac{x^7}{7\cdot6\cdot4\cdot3 }\dots)\end{align} This would be the indicated solution without using any Products, and factorials.

Where did I go wrong on this approach?


Como colocar o menu boostrap no meio da tela?

Question: Observem a imagem;

Clique aqui
Como faço para esse menu ficar no meio da tela?
A dificuldade existe porque estou usando Bootstrap 4, já tentei de tudo.
Queria que ficasse semelhante a esse abaixo;
www.esperancapaixao.com
Answer: Onde tem a listagem dos menus, se você for ver o código fonte vê que o ul tem margin-right:auto !important, ou seja, ele irá encostar ao lado esquerdo. Então basta adicionar-lhe um style com o seguinte código.

E para pôr o HOME junto aos restantes menus, terá de mudá-lo para dentro do ul mas fará com que ele desapareça na vista para mobile e apareça junto dos menus
Comment: FICOU MUITO BOM, muito obrigado.
Comment: @wladyband O facto de o Home ficar fora de vista em mobile não fez mal?
Answer: Na documentação oficial é usada a classe justify-content-md-center para fazer isso. Assim fica centralizado só até telas MD. Link dos exemplos oficiais https://getbootstrap.com/docs/4.0/examples/navbars/
OBS: Como é responsivo tem que executar como "Página toda"

Veja como fica no exemplo abaixo:

<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"/>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample08" aria-controls="navbarsExample08"
            aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    Centered nav only
                        (current)

                    Link

                    Disabled

                    Dropdown

                        Action
                        Another action
                        Something else here


C program output is confusing

Question: #include<stdio.h>
#include<conio.h>
#define PROD(x) (x*x)
void main()
{
clrscr();
int p=3,k;
k=PROD(p+1); //here i think value 3+1=4 would be passed to macro
printf("\n%d",k);
getch();
}

In my opinion, the output should be 16, but I get 7.
Can anyone please tell me why?
Comment: Schoolbook example of where C macros go wrong :)  Use functions instead.
Comment: Isn't this the *first* thing they warn about in any C programming book?  Whatever you use, I'm sure you can find a better one.
Comment: Urgh, a `void main()`...
Comment: "In my opinion" ... opinions aren't relevant, language standards are.
Answer: Macros are expanded, they don't have values passed to them. Have look what your macro expands to in the statement that assigns to k.
k=(p+1*p+1);

Prefer functions to macros, if you have to use a macro the minimum you should do is to fully parenthesise the parameters. Note that even this has potential surprises if users use it with expressions that have side effects.
#define PROD(x) ((x)*(x))

Answer: The problem here is that PROD is a macro and will not behave exactly like you intend it to. Hence, it will look like this:
k = p+1*p+1

Which of course means you have:
k = 3+1*3+1 = 7

Answer: The preprocessor expands PROD(p+1) as follows:
k = (p+1*p+1);

With p=3, this gives: 3+1*3+1 = 7.
You should have written your #define as follows:
#define PROD(x) ((x)*(x))

Answer: #define PROD(x) (x*x)

PROD(3+1) is changed by the preprocessor to 3+1*3+1
Answer: macro are not function . These are replaced by name
It will be p+1*p+1
Answer: This is what compiler is going to see after preprocessors does its job: k= p+1*p+1. When p =  3, this is evaluated as k = 3+(1*3)+1. Hence 7.
Answer: This is exactly why you should use functions instead of macros. A function only evaluates each parameter once. Why not try
int prod(int x)
{ return x * x; }
and see the difference!

C program output is confusing


Consulta SQL com joins entre 3 tabelas SQL Server

Question: Possuo as seguintes tabelas:

A (idA, nome, valor)
B (id, idA, nome, valor)
C (id, idA, nome, valor)

Portanto, tenho as seguintes relações A -> B e A -> C
Eu preciso gerar uma consulta que retorne pra mim todos os registros de A que estão na tabela C MAS que não estejam na tabela B.
Alguma dica de como poder solucionar este problema ?
Eu sei desenvolver o INNER JOIN quando tenho que relacionar mais de uma tabela porém nessa situação que mencionei fiquei em dúvida realmente sobre como resolver.
Comment: olá, veja se isso ajuda: https://codingstatus.com/sql-join-3-tables/
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Uma maneira de resolver o problema é utilizando a cláusula NOT IN
Desta forma a consulta resultante ficaria o seguinte:
SELECT a.* FROM a
INNER JOIN c ON a.idA = c.idA
where a.idA NOT IN (SELECT id FROM a INNER JOIN b ON a.idA = b.idA);

Outra maneira é utilizando a cláusula EXCEPT (que é equivalente à operação subtração de conjunto, a maneira acima também é equivalente à operação de diferença de conjuntos):
SELECT a.* FROM a
INNER JOIN c ON a.idA = c.idA
EXCEPT SELECT a.* FROM a INNER JOIN b ON a.idA = b.idA;

Para mais informações consulte a documentação.
Comment: Muito obrigado Dani pela ajuda, consegui resolver graças a sua resposta
Grato ;)


explain the pointers to pointers issue

Question: I'm new into C and I'm trying to get a grip on pointers. I came across this expression
char *foo = *(char **)bar;

what exactly is going on? I understand that * is pointer ** is pointer to pointer, but I don't really get what is *(char **)bar
edit:
worth to mention that bar is declared as const void *bar
Answer: *(char**)bar;

Cast bar to a pointer to pointer to char and dereference, which results in a pointer to char (i.e., a char*).
Remember that pointers are merely indirection.  When you dereference a pointer you "drop a star", i.e.:
char ***p = ...;
p    -> char***
*p   -> char**
**p  -> char*
***p -> char

Answer: Beginners and experts alike can benefit from getting the basics really solid.

A "variable of type t" is a storage location which can be used to store or fetch a value of type t.
A "pointer to t" is a value.
Applying the dereferencing operator * to a "pointer to t" produces a "variable of type t".

So what have we got?
void *bar = whatever;
char *foo = *(char **)bar;

bar is a variable of type "pointer to void".
foo is a variable of type "pointer to char".
casting bar to char** reads the variable bar and fetches a value of type "pointer to void". That value is then converted into a value of type "pointer to pointer to char".
Dereferencing that value produces a variable of type "pointer to char".
The value of that variable is then fetched, and the value is assigned to variable foo.

Make sense?
Comment: Yes thanks, bar in this case was of type void* hence the cast to char**
Answer: I don't know what type bar is without the cast, but here goes:
bar is being cast into a pointer to a pointer to a char.
The * before the (char **) is "dereferencing" the value to its right. In this case, it is returning the char * pointer held in the location pointer to by bar.
The result of the "dereferencing" is a char * -- pointer to a character -- which is assigned to the foo variable of the same type.

explain the pointers to pointers issue


A point $p$ of a variety $X$ is smooth if and only if it is smooth in $U\subset X$ an open sub variety.

Question: I want to show the following:

Let $X$ be an algebraic variety, let $U$ be an open subvariety of $X$ containing $p$. Then $X$ is smooth at $p$ if and only if $U$ is smooth at $p$.

Here is my definition of being smooth at a point

Definition: Let $X$ be an algebraic variety. We say $X$ is smooth at $p$ if there is an open subvarity $U$ of $X$ containing $p$ and an isomorphism $\varphi: U \rightarrow Z(f_1,..,f_{n-d})\subset \mathbb A^n$ for some $d\leq n$ for some $f_1,..,f_{n-d}$ such that the rank of $$\left(\frac{\partial f_i}{\partial x_j}(\varphi(p)\right)$$
is maximal.

Attempt:
($\Leftarrow$)
Let $U$ be smooth at $p$, then there is some $\overline{U}$ an open subvariety of $U$ and $\varphi:U\rightarrow Z(f_1,...,f_{n-d})$ satisfying the smoothness criterion. Since $U$ is a subvariety of $X$ so to is $\overline{U}$. Again this $\varphi:U\rightarrow Z(f_1,...,f_{n-d})$ still satisfies the smoothness crieterion so we are done.
($\Rightarrow$)
Let $X$ be smooth at $p$, then there is some $\overline{U}$ an open subvariety of $X$ and an isomorphism $\varphi:\overline{U}\rightarrow Z(f_1,..f_{n-d}$ satisfying the smoothness criterion.
We want an open subvariety of $U$, define $V=U\cap\overline{U}$ this certainly is an open subvariety of $U$. And $\varphi\mid_V$ is an isomorphism onto its image. But how do we know its image is of the form $Z(f_1,...,f_{n-d})$ and how do we know that the Jacobian of the restriction still has full rank?
Answer: The other answer has some valuable content, but it's long, not an easy read to my eyes, and could be more self-contained. Here I present what I feel is a more direct solution.

One direction is easy: if $p\in X$ is smooth as a point of $U\subset X$, then the open neighborhood $U'\subset U$ obtained from the definition of smoothness is also an open neighborhood of $p\in X$ satisfying the same required properties.
For the other direction, suppose $p\in X$ is a smooth point and $U$ is an open neighborhood of $p$. Let $U'$ be the open neighborhood of $p$ guaranteed by the definition of smoothness. If $U'\subset U$, we're done. Else, $U'\cap U$ is an open subset of $U'$, with closed complement $V\subset U'$.
As $V$ is a closed subvariety of the affine variety $U'\cong Z(f_1,\cdots,f_{n-d})\subset \Bbb A^n$ which is disjoint from $p$, we can find a function $f$ on $U'$ vanishing on $V$ and nonvanishing on $p$. Then $D(f)\cap U'$ is an open subset of $U\cap U'$ and also an affine variety, cut out in $\Bbb A^{n+1}$ by the equations $(fx_{n+1}-1,f_1,\cdots,f_{n-d})$.
To see that the Jacobian matrix of this system has rank $n+1-d$, it suffices to check that the entry corresponding to $\frac{\partial (fx_{n+1}-1)}{\partial x_{n+1}}$ is nonzero: every other term of the form $\frac{\partial f_i}{\partial x_{n+1}}$ is zero because $f_i$ doesn't depend on $x_{n+1}$. But $\frac{\partial (fx_{n+1}-1)}{\partial x_{n+1}}=f$, which is nonvanishing on $D(f)\cap U'$. So our Jacobian matrix looks like $$\begin{pmatrix} \frac{\partial(f_1,\cdots,f_{n-d})}{\partial(x_1,\cdots,x_n)} & 0 \\ * & f \end{pmatrix}$$ and this has rank $n+1-d$, so we're done.
Comment: Thank you, this is much more the kind fo answer I was looking for. The top right zeros are all because $f_i$ does not depend on $x_{n+1}$. What is * representing here? Also, nice moccasins Mr Scorpio!
Comment: I use the asterisk to denote entries that don't matter for the end result and that I don't want to write out. Explicitly, they're $x_{n+1}\frac{\partial f}{\partial x_i}$ for $1\leq i\leq n$, but they don't affect whether the matrix is invertible.
Answer: If $X:=V(I)\subseteq \mathbb{A}^n_k$ is an affine algebraic variety over a field $k$ of characteristic zero (the ideal $I$ is assumed to be a prime ideal) it follows from Hartshorne's book (HH) and Thm I.3.2 that $\Gamma(X,\mathcal{O}_X)=A$ where $A:=k[x_1,..,x_n]/I$. Again by   HH Thm I.3.2 it follows $\mathcal{O}_{X,p} \cong A_{\mathfrak{p}}$ where $\mathfrak{p} \subseteq A$   is the prime ideal corresponding to the point $p\in X$. By HH.II.1 (the section on stalks) it follows the stalk $\mathcal{O}_{X,p}$ is the limit of $\mathcal{O}_X(V)$ over all open subsets $V$ containing $p$. We may restrict the sheaf $\mathcal{O}_X$ to the open set $U$ to get the structure sheaf $\mathcal{O}_U$ on the open sub-variety $U$. It follows from the defnition there is an isomorphism $\mathcal{O}_{X,p} \cong \mathcal{O}_{U,p}$.
Hence the sheaves $\mathcal{O}_X$ and $\mathcal{O}_U$ have the same stalk at the point $p$. Again by HH.I.5 we define the point $p$ to be non-singular using the Jacobian matrix of a set of generators $f_i$ of the ideal $I$ defining $X$. This definition is independent of choice og generators $f_i$ of the ideal $I$. By HH.I.5.1 it follows $p$ is non-singular iff the local ring $\mathcal{O}_{X,p}$ is a regular local ring. Since $\mathcal{O}_{X,p}\cong \mathcal{O}_{U,p}$ it follows we may define non-singularity using any open set $U$ containing $p$. Hence we may use the local ring at $p$ to define non-singularity for any variety of finite type over $k$, where $k$ is a field of characteristic zero.
Example 0. If $X$ is a (projective) variety of finite type over $k$ and $p \in X$ is a closed point, we may choose an open affine set $p\in U \subseteq X$. By definition $U:=Spec(A)$ with $A=k[x_1,..,x_n]/I$, where $I:=\{f_1,..,f_l\}$ is a set of polynomials. Then we may use the Jacobian criterion to check if $p$ is a non-singular point of $X$. This does not depend on the choice of open affine subset $U$ containing $p$ and the choice of generators $f_i$ of the ideal $I$.
Let us prove your claim using the Jacobian criterion. Let $U:=Spec(A)$ and $V:=Spec(B)$ be two open affine subvarieties containing $p$ with $A:=k[x_1,..,x_n]/(f_1,..,f_l)$ and $B:=k[y_1,..,y_n]/(g_1,..,g_t)$. Let $U$ be smooth/non-singular at $p$ by the Jacobian criterion. It follows from HH that $\mathcal{O}_{U,p}$ is a regular local ring. There is an isomorphism of local rings $\mathcal{O}_{U,p}\cong \mathcal{O}_{V,p}$ (this is a formal property of limits, and the proof may be found in Atiyah-Macdonalds (AM) book on commutative algebra), hence it follows $\mathcal{O}_{V,p}$ is a regular local ring. Again by HH it follows the Jacobian criterion holds for the generators $g_i$ at the point $p \in V$. The converse is similar and the claim is proved.
Note: This proof uses Chapter I in HH which is "elementary", a formal result on limits in AM - this is also "elementary" - and the definition of the stalk of a sheaf in Chapter II in HH. This is also an "elementary" definition.  Hence this proof is in a sense "elementary". To students: Do you think this proof is "elementary enough" or is there a more "elementary" proof "somewhere out there"?
Example 1. There are problems arising in characteristic $p>0$. Let $k$ be a field of characteristic $p$ and let $f(x,y) \in k[x^p,y^p]$ be any polynomial. It follows $\partial f/\partial_x=\partial f/\partial_y=0$, hence the Jacobian matrix of $f$ is identically zero.
If $k$ is any algebraically closed field and $f:X \rightarrow Y$ a morphism of schemes of finite type over $k$, we say "f is smooth of relative dimension $n$" if the following holds:
$f$ is flat.
For any irreducible components $X' \subseteq X$ and $Y' \subseteq Y$ with $f(X') \subseteq Y'$ it follows $dim(X')=dim(Y')+n$.
For any point $x\in X$ it follows $dim_{\kappa(x)}(\Omega_{X/Y}\otimes \kappa(x))=n$.
Theorem III.10.2 in Hartshorne says that $f$ is smooth of relative dimension $n$ iff $f$ is flat and for any $y \in Y$ it follows the fiber $X_y:=f^{-1}(y)$ is geometrically regular, which means that the fiber product $X_y \times Spec(\overline{\kappa(y)})$ is regular (meaning all local rings are regular local rings). Here $\overline{\kappa(y)}$ is the algebraic closure of $\kappa(y)$. Hence if $Y=Spec(k)$ with $k$ an algebraically closed field it follows the morphism $f:X \rightarrow Spec(k)$ is smooth iff the local ring $\mathcal{O}_{X,p}$ of $p \in X$ is a regular local ring for any point $p$. Hence if the base field $k$ is algebraically closed we may use the module of relative differentials $\Omega^1_{X/Y}$ to define "regularity/non-singularity": We define $X$ (a scheme of finite type over an algebraically closed field $k$) to be "non-singular" iff the canonical map $f:X\rightarrow  Spec(k)$ is smooth of relative dimension $dim(X)$.
Example 2: Let $k$ be an algebraically closed field of characteristic $p>0$ and let $f(x_1,..,x_n)\in k[x_1^p,...,x_n^p]$ be a polynomial. It follows there is a polynomial $g(x_1,..,x_n)$ with $g^p=f$, hence $f$ is never irreducible.
The module of Kahler differentials is "functorial" in the following sense: If $f: X \rightarrow Y$ is a morphism of schemes and $i:U \rightarrow X, j:V \rightarrow Y$ are open subschemes with $f(U) \subseteq V$, it follows there is an isomorphism of sheaves $i^*\Omega^1_{X/Y} \cong \Omega^1_{U/V}$. Hence for any point $p \in U$ it follows there are isomorphisms at the stalks $\Omega^1_{U/V,p}\cong \Omega^1_{X/Y,p}$ and at the fiber $\Omega^1_{U/V}\otimes \kappa(p) \cong \Omega^1_{X/Y}\otimes \kappa(p)$.  Hence the stalk and fiber of the module of Kahler differentials at $p$ does not depend on the choice of open subscheme $U \subseteq X$ containing $p$. We may choose $U:=Spec(B)$ and $V:=Spec(A)$ and then $i^*\Omega^1_{X/Y}$ is the sheafification of the module $\Omega^1_{B/A}$ of relative differentials.
Example 3: If $f(x_1,..,x_n)\in k[x_1^p,..,x_n^p]$ is any polynomial and $char(k)=p>0$ it follows $\partial f/\partial_{x_i}=0$ for all $i$. It follows the differential $df:=\sum_i \partial f/\partial_{x_i} dx_i=0$. If $X:=Spec(k[x_1,..,x_n]/(f))$ it follows the cotangent bundle $\Omega^1_{X/k}$ is a trivial $\mathcal{O}_X$-module of rank $n$.
Comment: In the setting of Hartshorne chapter I, the problem you mention in characteristic $p$ does not actually occur. $x^p+y^p+1=(x+y+1)^p$, so you haven't actually chosen a generator of the ideal of that curve. The fact that regularity is a property of the local ring is a good solution to the problem, though.
Comment: Yes, it seems in this case the affine scheme $C:=Spec(B)$ with $B:=k[x,y]/(f)$ is a copy of the affine line $\mathbb{A}^1_k$ with a non reduced structure, and this is introduced in Section II in Hartshorne's book. But one could choose any irreducible polynomial $f(x^p,y^p)\in k[x^p,y^p]$, and the corresponding Jacobian matrix would be identically zero.


Where are OAuth 2.0 with Gmail for Server-Side Authorization examples for Java?

Question: I need to implement OAuth2 for a web application written in Java to access Gmail. Unfortunately Google's documentation has only a Python example regarding this topic:
https://developers.google.com/gmail/api/auth/web-server
I've googled now for hours and could not find a good example which explains the topic - I'm new to OAuth2 and therefore a step-by-step example in Java would be very useful.
Thanks in advance :)
Comment: @VladBochenin thanks for your comment. Yes, I've seen this, but the problem with this example is, that "public static Credential authorize()" prints to the commandline only instead of returning the url to redirect the user. I don't know but as fas as I understand I can't use the code for a web application..
Comment: Have you seen this: https://developers.google.com/gmail/api/quickstart/java
Answer: I've tried to make a contribution to the Gmail Quickstart Guides.  I think the path of least resistance would be to just copy what I have here.
Assuming that you have your secrets handy, and you have already obtained a refresh_token in a previous authorization process.  You can try this out.
<code>
    /**
     * Assuming the user of this application has already obtained an refresh_token, this will create a Credential object
     * using the provided secrets and the provided refresh_token.
     *
     * @param refreshToken   Refresh Token obtained in previous authorization process
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final String refreshToken, final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        GoogleClientSecrets clientSecrets = getGoogleClientSecrets();

        return new GoogleCredential.Builder()
                .setJsonFactory(JSON_FACTORY)
                .setTransport(HTTP_TRANSPORT)
                .setClientSecrets(clientSecrets)
                .build().setRefreshToken(refreshToken);
    }
</code>
Full: GmailQuickstart.java
<code>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// [START gmail_quickstart]
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;

import java.io.*;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class GmailQuickstart {
    private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_LABELS);
    private static final String CREDENTIALS_FILE_PATH = "credentials.json";

    private static GoogleClientSecrets getGoogleClientSecrets() throws IOException {
        // Load client secrets.
        File credentialJson = new File(CREDENTIALS_FILE_PATH);
        if (!credentialJson.exists()) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        return GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(new FileInputStream(credentialJson)));
    }
    /**
     * Launches a small local server on 8888 which facilitates the authorization process from scratch.  In turn creates
     * an authorized Credential object when the user proceeds with the authorization.
     *
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        GoogleClientSecrets clientSecrets = getGoogleClientSecrets();

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

    /**
     * Assuming the user of this application already has an refresh_token handy, this will create a Credential object
     * using the provided secrets and the provided refresh_token.
     *
     * @param refreshToken   Refresh Token obtained in previous authorization process
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final String refreshToken, final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        GoogleClientSecrets clientSecrets = getGoogleClientSecrets();

        return new GoogleCredential.Builder()
                .setJsonFactory(JSON_FACTORY)
                .setTransport(HTTP_TRANSPORT)
                .setClientSecrets(clientSecrets)
                .build().setRefreshToken(refreshToken);
    }

    private static Credential getCredential(NetHttpTransport HTTP_TRANSPORT) throws IOException {
        Credential credentials;
        switch (getAuthPreference()) {
            case FULL_AUTH:
                credentials = getCredentials(HTTP_TRANSPORT);
                break;
            case REFRESH_AUTH:
                System.out.print("please provide refresh_token:");
                String refreshToken = getUserInput();
                credentials = getCredentials(refreshToken, HTTP_TRANSPORT);
                break;
            default:
                credentials = getCredentials(HTTP_TRANSPORT);
        }
        return credentials;
    }

    private static WhatToDo getAuthPreference() throws IOException {
        // Enter data using BufferReader
        System.out.println("You can choose how to authorize your request.");
        System.out.println("\t1) Need to do full authorization");
        System.out.println("\t2) Already have refresh_token handy.  Can provide this next.");
        String userInput = getUserInput();
        if (userInput.equals("1")) {
            return WhatToDo.FULL_AUTH;
        }
        if (userInput.equals("2")) {
            return WhatToDo.REFRESH_AUTH;
        }
        System.err.println("Your Input was incorrect! ");
        return getAuthPreference();
    }

    private static String getUserInput() throws IOException {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(System.in));
        // Reading data using readLine
        String userInput = reader.readLine();
        return userInput;
    }

    enum WhatToDo {
        FULL_AUTH,
        REFRESH_AUTH
    }

    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredential(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

        // Print the labels in the user's account.
        String user = "me";
        ListLabelsResponse listResponse = service.users().labels().list(user).execute();
        List<Label> labels = listResponse.getLabels();
        if (labels.isEmpty()) {
            System.out.println("No labels found.");
        } else {
            System.out.println("Labels:");
            for (Label label : labels) {
                System.out.printf("- %s\n", label.getName());
            }
        }
    }
}
// [END gmail_quickstart]

</code>


The affine space of covariant derivative

Question: Let $\nabla$ be a connection on a smooth manifold $M$.
(i) Show that the set $\text{Conn}(M)$ of connections on $M$ is equal to $$\text{Conn}(M) = \left\{\nabla + A \mid A \in T_2^1(M)\right\}.$$
(ii) Let $\nabla$ be torsion-free. Show that the set of torsion-free connections $\text{Conn}(M, [\cdot, \cdot])$ on $M$ is equal to $$\text{Conn}(M,[.,.]) = \left\{\nabla + A \mid A \in T_2^1(M),~ A(X,Y) = A(Y, X)\text{ for all } X, Y ∈ X(M)\right\}.$$
(iii) Let $\nabla$ be metric with respect to a semi-Riemannian metric $g$ on $M$. Find a similar description of the set $\text{Conn}(M, g)$ of connections on $M$ which are metric with respect to $g$.
for first part, I am confused how could I get a $(1,2)$-tensor out of the connection, since connection is a map : $X\times X \to X$, $X$ is vector field. for second part and third part, I dont have any clue, could anyone show me how to prove it?
Comment: For $(i)$, show that if $\nabla^1,\nabla^2$ are connections, then $\nabla^1 - \nabla^2$ is a tensor: you can show this by showing it is $\mathcal{C}^{\infty}(M)$-linear in each variables (use the definition of a connection: it is not just a map $\mathfrak{X}(M)\times \mathfrak{X}(M) \to \mathfrak{X}(M)$, it has properties). For $(ii)$, just use the description of $(i)$ and look at what the torsion-free condition implies.
Answer: I think you confusion lies in the following.
An affine connection is a map $\nabla:\mathfrak{X}(M)\times \mathfrak{X}(M)\to\mathfrak{X}(M)$ fulfilling some properties, or let's write it $\mathcal{T}_0^1(M)\times\mathcal{T}_0^1(M)\to\mathcal{T}_0^1(M)$. So it takes two $(0,1)$-tensor fields and gives back a $(0,1)$-tensor field. If you now leave open the first argument, say for fixed $Y\in\mathfrak{X}(M)$ you consider the map $$\nabla_{(\cdot)}Y:\mathcal{T}_0^1(M)\to\mathcal{T}_0^1(M),~X\mapsto \nabla_XY,$$
you find that this map is $\mathcal{C}^\infty(M)$-linear (which is one of the properties mentioned above). Hence, the resulting vector field $\nabla_XY\big|_p$ evaluated at some $p\in M$ depends only on $X\big|_p$ and on no other value of $X$ and you can consider the map
$$
\nabla_{(\cdot)}Y\big|_p:T_pM\to T_pM,~v\mapsto \nabla_{X_v}Y\big|_p
$$
with any $X_v\in\mathfrak{X}(M)$ s.t. $X_v\big|_p=v$. In other words the previous map is an element of ${T_p}_1^1(M)$ and collecting all these maps again into one field you obtain $\nabla_{(\cdot)}Y\in\mathcal{T}_1^1(M)$. Taken together you can equivalently define a connection as a map $\tilde{\nabla}:\mathfrak{X}(M)\to\mathcal{T}_1^1(M)$. Indeed some authors make it the one way, some the other, some need both versions and call one of them a covariant derivative, and some do not even make a notational difference.
Now you may notice that the lack of $\mathcal{C}^\infty(M)$-linearity in the second argument prevents you from regarding $\nabla$ as an element of $\mathcal{T}_2^1(M)$. But you can show that for two connections $\nabla,\tilde{\nabla}$ the difference $\nabla-\tilde{\nabla}:\mathfrak{X}(M)\times \mathfrak{X}(M)\to\mathfrak{X}(M)$ is $\mathcal{C}^\infty(M)$-linear in both arguments, making it indeed possible to regard it as an element $\nabla-\tilde{\nabla}\in\mathcal{T}_2^1(M)$.
Does this help you with your confusion? For your concrete problems with (ii) and (iii) you have to evaluate what the properties of being torsion-free and being metric means for the difference tensor of two connections with the respective properties.


The Mathematics of Shuffling Poker Chips?

Question: First, I must say that I do not have an advanced understanding of mathematics and I don't know what category this question belongs in. This is just a question that I have been thinking about recently.
I've been teaching myself to shuffle poker chips and I noticed a weird trend. I decided to model it in C# and not only did I fail to answer my question, but it seemed to make less and less sense to me.
So basically, this is what I did. I chose a certain number of chips, along with a certain number of colors, to see how many shuffles it takes to return to the initial form. The shuffles are the same simple shuffle everyone sees at a poker table. The chips are all grouped by color in the beginning and the condition to satisfy is a return to this initial position.
I did this for Chips ranging from 1-20, and colors ranging from 1 to 11. This is the data that I generated: https://i.stack.imgur.com/kGvU7.png
I've looked at this paper: http://scott-n.com/Archives/Docs/Mathematical%20Trends%20in%20Binary%20Chipshuffling.pdf
It is a short paper that seeks to detail some of the trends that exist when using only 2 colors.
Can anyone enlighten me on the subject? On the surface it seems relatively simple, but the more I look into it, the more difficult it becomes.
Comment: I don't understand the exact setup. The "simple shuffle at a poker table" mixes two stacks of equal size. You could do this to a blue and a yellow stack, say. But what exactly are you doing if you use 3 colors?
Comment: I would have imagined that only *cards* are shuffled, not chips, at a game of poker ...?
Comment: @HagenvonEitzen: Some people smoke cigarettes when they get nervous. Poker players tend to shuffle their chips instead. Just type 'shuffle poker chips' into youtube to see how this works.
Comment: please see  @Kevin my answer if  it is  good for you
Comment: yes  pattern_recognition  i have not deleted  i was  thinking that it was  OP's primary interest
Comment: question like how many from other set or something like this belongs combinatorics.for example choose $n$ sample from $m$ population and how many way is for this.it is combinatorics.also maye help you probability if you want to calculate probability of something.for this probability theory.else combinatorics could be useful. see this http://en.wikipedia.org/wiki/Combinatorics let us imagine it like this ,we have $1 ,2 ,3 ,4$ how many permutation(arrangment is necessary to return it's original distribution
Answer: Just as azimut's comment: I also don't understand your setup for more than two colors. However for two colors there is an answer.
The answer for two colors
Let's say we have $n$ chips (in total, not per color) and we want to find the number of shuffles needed which we call $k$.
There are two different ways how you can shuffle the chips: in-shuffles and out-shuffles, depending on which way you shuffle the chips:
In-shuffle:
RRRRBBBB => BRBRBRBR

Out-shuffle:
RRRRBBBB => RBRBRBRB

Basically, when doing an out-shuffle, the outermost chips never change position, and so $outShuffle(k) = inShuffle(k-2)$. For the following, I'll assume we are talking about in-shuffles
The number of shuffles is the smallest positive integer $k$ so that $(n+1)$ divides $(2^k-1)$.
It can also be written as the smallest positive integer $k$ so that $2^k\equiv1 \mod (n+1)$
This is the same as the multiplicative order of $2 \mod (n+1)$.
Explanation
This question can be explained with permutation group theory. Unfortunately, I can't give you a real explanation, nor a proof, but I can give you an idea how the formula I gave above can be explained.
Easy case: 8 chips
Let's number the stack of chips from $1$ to $n$
12345678
RRRRBBBB

and let's then watch what happens to the chip on position $1$ over time. After one shuffle, we get the following picture:
12345678
BRBRBRBR

The chip from position $1$ is now on position $2$. Another shuffle later, it is on position $4$, then on position $8$, before returning to position $1$. So we have the cycle
$
1\rightarrow
2\rightarrow
4\rightarrow
8\rightarrow
1$
of length $4$.
However, not only does the chip from position $1$ follow this cycle. All 4 chips on this cycle are just rotating their places, which means that after 4 shuffles, they all return to their original place. The same happens with the other 4 chips, in another cycle.
Consequentely, after 4 shuffles, the original position is restored.
More complicated: 10 chips
Let's now check what happens with the first chip, when there are 10 chips in total.
We get the following permutation:
$
1\rightarrow
2\rightarrow
4\rightarrow
8\rightarrow
5\rightarrow
10\rightarrow
9\rightarrow
7\rightarrow
3\rightarrow
6\rightarrow
1$.
The sequence has a length of 10, so it takes 10 shuffles to restore the original configuration. The question is however, what the mathematical structure behind this sequence is.
If you examine this sequence more closely, you find out that the formula to get to the next position is $(pos*2)\mod11$. In general, this formula is $(pos*2)\mod(n+1)$.
General case
The $k$th position of a chip can be calculated by duplicating it $k$ times, while calculating modulo $(n+1)$.
The $k$th position of the first chip is though $2^k\mod(n+1)$. If and only if this is $1$, the first chip has returned to its position after $k$ shuffles.
While this is by no means a complete proof, you can see that this might lead to the searched number being the smallest $k>0$ for which $2^k\equiv1\mod(n+1)$.
What is missing

Why can't there be a longer cycle than the one starting at position $1$?
Why isn't there a situation in which the colors of the chips are right, even without the chips returning to their original position.

See also

A002326: Multiplicative order of 2 mod 2n+1 (here $n$ is the number of chips of one color, therefore $2n+1$ not $n+1$)
xkcd forum thread about this topic
Answer: If each shuffle reorders the chips the same way, and all chips are different, this is just repeating a permutation (multiplying it by itself), so (by elementary group theory) the initial configuration does repeat eventually. If you divide the chips into undistinguishable groups (colors), the configuratins that are "the same" as the starting point are more, and you'll perhaps hit one of them before.
If the shuffle reorders chips in different ways, it is a random walk on the possible configurations. An interesting, but far from easy problem, is to compute the average time for repeats.


Use Java 10 with Spring MVC 5

Question: Currently I am using Java 8 and Spring MVC 4. I want to upgrade java into 10 and spring into 5. So Is Spring MVC 5 is compatible with Java 10 ?
Answer: They added support for JDK9 features, most notably the Flow API (cf their documentation). And, as far as I know, it seems compatible with JDK10.

The language changes in java 10 are pretty minor and retro-compatibles. I'm using spring 5 with java 10 and still haven't noticed any regression.
Comment: Yes you can. But that's more of an issue of retro-compatibility on the java side rather than Spring. Java 9 brought the concept of modules which could be troublesome with libraries but java 10 is fairly small. Meaning : if it works with java9, it'll probably work with java 10. (Except when the jdk10 bugs :))
Comment: Means i can use `java 10` with `spring mvc 5`
Answer: Looking to the service Spring Initializr in full version it is possible to choose between java 8 and java 10, so I think that it is fully compatible.

Use Java 10 with Spring MVC 5


How to view live code coverage in Visual Studio?

Question: I have Visual Studio Enterprise. At the linked timestamp, this guy has green little checkmarks on the left side of his window that seem to show code coverage in real time.
How do I turn this on?

I tried searching all over, but I don't know what this setting is called.
Comment: this feature  (live unit testing) is available in the enterprise version of Visual Studio, Another cool plugin that does the same work is NCrunch.
Comment: see also https://learn.microsoft.com/en-us/visualstudio/test/live-unit-testing
Answer: This feature is only available on Visual Studio Enterprise Edition.
After establishing the corresponding class library and unit test method, you can pass
Test=>Live Unity Testing=>Start

Conduct Live Unity Testing.

For detailed steps, please refer to: https://learn.microsoft.com/en-us/visualstudio/test/live-unit-testing-start?view=vs-2022
As you develop your application, Live Unit Testing automatically runs any affected unit tests in the background and displays the results and code coverage in real time. When code is modified, live unit testing provides feedback on how the changes affect existing tests and whether the new code added is covered by one or more existing tests.
Comment: I have run live unit testing, but I see no green checkmarks next to my tests.
Comment: @SIT_account If your operation steps are OK, you need to delete the .vs folder in the project directory (this is a hidden folder). Then try starting the live unit test again


Find Circumdiameter of Δ HBC.

Question: If H is the orthocenter of an acute angled ΔABC whose circumcircle is $x^2+y^2=16$, then circumdiameter of the triangle HBC is
Answer: Hint: The reflection of $H$ in $BC$ lies on the circumcircle of $\triangle ABC$. What does this say about the reflection of the circumcircle in $BC$?
Comment: I know that fact but it does'nt helps in solving for the circumdiameter of HBC
Comment: The fact that the circumcircles of $\triangle ABC$ and $\triangle BHC$ are reflections of eachother in $BC$, implies that they have equal circumradius.
Answer: By the sine theorem, the circumradius is given by:
$$ R = \frac{a}{2\sin A}. $$
Since $\widehat{BHC}=\pi-\widehat{HBC}-\widehat{HCB}=\widehat{B}+\widehat{C}=\pi-\widehat{A}$, the circumradius of $BHC$ is the same as the circumradius of $ABC$.
Answer:
Let O and I be the circum-centers of ⊿ABC and ⊿HBC respectively. HD HE and HF are perpendicular to BC, BA and AC respectively.
The red line is the line of centers and the purple line (BC) is the common chord. In addition, BC is perpendicularly bisected at K.
For some reasons, the brown (AEHF) and green (BHCJ) quadrilaterals are cyclic.
We have the following relations:-
$$\angle BOC = 2 \angle A = 2 \angle FHB = 2 \angle J = \angle BIC.$$
Using all of the above information, we can conclude that OBIC is a rhombus.
Thus, the circum-diameter of ⊿HBC is the same that of ⊿ABC.

Find Circumdiameter of Δ HBC.


Xamarin - download image to gallery

Question: I've found this: How to download image and save it in local storage using Xamarin-Forms.?
This partially adresses my problem except for two points:

I'd need to download the image to the gallery, not the apps'path
I need this to work for both, android and IOs. This seems to only work for Android.

Basically i know the URL of a file online, and need to download it to the gallery. It would be great if ic ould "save" it from inside the application, instead of "downloading". It would be nice if the client cant figure out the URL of the images he wants to save.
EDIT:
Now I am using FFImageLoading.. here is my current (not working) code..
 private async void SaveToGallery_Clicked(object sender, EventArgs e)
    {
        var img = await MyImage.GetImageAsJpgAsync(quality: 100);

        string fileName = uri.ToString().Split('/').Last();

        DependencyService.Get<IMediaService>().SaveImageFromByte(img, fileName);
    }

Android MediaService.cs
[assembly: Xamarin.Forms.Dependency(typeof(MediaService))]
namespace GalShare.Droid
{
public class MediaService : IMediaService
{
    Context CurrentContext => CrossCurrentActivity.Current.Activity;
    public void SaveImageFromByte(byte[] imageByte, string fileName)
    {
        try
        {

            Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
            string path = System.IO.Path.Combine(storagePath.ToString(), fileName);
            System.IO.File.WriteAllBytes(path, imageByte);
            var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(path)));
            CurrentContext.SendBroadcast(mediaScanIntent);
        }
        catch (Exception ex)
        {

        }
    }
}
}

Android MainActivity.cs:
namespace GalShare.Droid
{
[Activity(Label = "GalShare", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    public int STORAGE_PERMISSION_CODE = 101;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
        FFImageLoading.Forms.Platform.CachedImageRenderer.Init(enableFastRenderer: false);

        base.OnCreate(savedInstanceState);

        Forms.SetFlags("CollectionView_Experimental");

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        CachedImageRenderer.InitImageViewHandler();

        string fileName = "galleries.db3";
        string folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        string completePath = Path.Combine(folderPath, fileName);

        checkPermission("android.permission.write_external_storage", STORAGE_PERMISSION_CODE);

        LoadApplication(new App(completePath));
    }

    public void checkPermission(String permission, int requestCode)
    {
        var thisActivity = Android.App.Application.Context as Activity;
        // Checking if permission is not granted
        if (ContextCompat.CheckSelfPermission(
                Android.App.Application.Context,
                permission)
            == Android.Content.PM.Permission.Denied)
        {
            RequestPermissions(new String[] { Manifest.Permission.WriteExternalStorage }, requestCode);

        }
        else
        {

        }

    }

}
}

Comment: downloading a file is the same as in any c# application - use HttpClient to get the bytes, then write to file using Sytem.IO.File.  There are numerous existing questions that address this.  Saving to the gallery will vary between iOS and Android, but there are MULTIPLE existing questions on SO that explain how to do it.
Comment: @Jason thanks.. I've been looking around and found a lot of topics, but none of them brought me to a solution. I updated the topic with the code I have so far. but when I click nothign happens, Also, the path somehow does not corrispond to the gallery..
Comment: "not working" - what does this mean?  Does it have a compile error, or does it crash at runtime with an exception?  Does it doing (or not doing) that it shouldn't?  As I explained before, saving to the gallery will be a platform specific operation.  Have you looked at other questions that address this?
Comment: @Jason, I made some huge changes, implemented the permission request, and am working on the andoid side. Currently nothing happens.. the file simply does not get saved.. Updating the Post with the current code
Comment: seems like this is null: ` Context CurrentContext => CrossCurrentActivity.Current.Activity;` inside the mediaservice.cs
Answer: Initialilzing CrossCurrentActivity in the MainActivity.cs solved the problem:
CrossCurrentActivity.Current.Init(this, bundle);

Xamarin - download image to gallery


convert to show percentage of the sum of 2 or more combined columns

Question: I have looked at the similar questions and was unable to find anything that answered my question.
I have a column that is the calculation of other columns of which sum I would like to divide by a set number and show results in percentage from. I have tried the below query and am able to show in decimal. Basically find out what percentage of UPH an associate is doing...This way I can tell if they are slacking in their department or exceling. I am using 150 as my base rate
SELECT
ID
  , DeptCode AS 'DC'
  , OpCode AS 'OC'
  ,Units = sum(Units)
  ,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
  ,Percentage = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0)) / 150

FROM dbo.TimeLog
 WITH (NOLOCK)

WHERE DeptCode = 'FB'
  and OpCode   = 'PU'
  and Units IS NOT NULL
GROUP BY
    ID
  , DeptCode
  , OpCode

Here is my result...
ID      DC  OC  Units   UPH Percentage
11259   FB  PU  553     114 0.760000
2375935 FB  PU  263     70  0.466666

I would like to see column 'Percentage' like the below
ID      DC  OC  Units   UPH Percentage
11259   FB  PU  553     114 76%
2375935 FB  PU  263     70  47%

Any help would be appreciated and I apologize in advance if this is elementary for a lot you, I am relatively new to SQL
Answer: Try this instead (SQL 2012 and later):

Percentage = CONCAT(cast(isnull(sum(Units) /
  nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as
  decimal(10,0)), '%')

Refer: https://learn.microsoft.com/en-us/sql/t-sql/functions/concat-transact-sql
Try this instead (SQL 2008):

(convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/150*100 as as decimal(10,0))) + '%') as Percentage

Refer: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/string-concatenation-transact-sql
Comment: Hi, I just tried that.... Msg 195, Level 15, State 10, Line 26
'CONCAT' is not a recognized built-in function name.  Running SQL 2008R2
Comment: ran the second got this error code. Msg 8114, Level 16, State 5, Line 17
Error converting data type varchar to numeric.
Comment: try the aforementioned query now
Comment: oh wait one last question,  This is only showing me the percentage of the UPH I want to divide the number of the UPH by a set number,  say its 150...
Comment: it would be same. you need to.. (cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60) / 150 ....
Comment: try something like this:
(convert(varchar, (cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/150 as decimal(10,0))) + '%') as Percentage
....given you want to divide by a set number like 150. let me know if this works. :)
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/145923/discussion-between-druidruid-and-somdip-dey).
Answer: You can use format(decimal, 'p') as below:
      ,Percentage = Format(cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0)) / 100 , 'p')

Comment: 'Format' is not a recognized built-in function name. Im running 2008R2
Comment: Gotcha... Format is there from 2012 only