Correlation between products

Question: I have an idea of what I want to achieve, but have no clue what it is called in statistical analysis world, hence impossible to implement.
I have a database with unique order numbers, customer names, products etc. I would like to see the correlation between products within orders. I.e. if I pick product X, what is the likelihood that I will also choose a product Y.
I would like to know what to research to help me with this.
Comment: I notice that you've edited your title to say "[solved]". If one of the answers has addressed your problem, the way that you show that is by accepting an answer: click the check mark next to the answer that helped you the most. Please review the [help] for more information about how to use this website.
Comment: Thank you all for your input! I will try these and come back to you.
Comment: I have found that Data Mining add-in for excel can do wonders, but while add-in itself is free, it uses SQL Server's Analysis Services module, which unfortunately is not included in free products. Maybe somebody knows some other way that could be implemented in Excel?
Answer: Such relationships are called association rules.
One of the widely used algorithms for deriving association rules is Apriori, which is implemented in both R and Python.
Answer: It's called conditional probability $P(Y|X)$, i.e. probability of picking Y given that a customer picked X. There are relationships such as this one: $P(Y\&X)=P(Y|X)P(X)$, i.e. the probability that you pick Y and X is equal to probability of picking X multiplied by probability of picking Y conditional on picking X etc.
Answer: Basically you're wondering if the event where an individual chooses product $X$ is independent of the event where they choose product $Y$, or if these events are positively correlated.  You can check this by testing the hypothesis $p_1 = p_0$ against the alternative $p_1 > p_0$, where $p_1$ is the probability of choosing product $Y$ given that you've chosen product $X$, and $p_0$ is the same probability given that you didn't choose product $X$.  If your sample sizes are large you can test this with the statistic
$$
z = \frac{\hat{p}_1 - \hat{p}_0}{ \sqrt{\frac{\hat{p} (1 - \hat{p})}{n_1} + \frac{\hat{p} (1 - \hat{p})}{n_0}} }
$$
where $\hat{p}_1$ is the proportion of individuals who purchased product $Y$ among those who purchased product $X$, $\hat{p}_0$ is the proportion among those who didn't purchase product $X$ ($n_1$ and $n_0$ are the respective sample sizes), and $\hat{p}$ is the overall proportion.  When $p_1 = p_0$ this approximately follows a standard normal distribution, which can be used for the calculation of $p$-values.  Do you know where to go from here?
Comment: Could you please elaborate a little bit on further steps?
Comment: This seems to explain the test: https://onlinecourses.science.psu.edu/stat414/node/268

Correlation between products


which of the following is/are algebraic over rationals

Question: which of the following is/are true?

$\sin 7^\circ$ is an algebraic over $\mathbb{Q}$
$\sin^{-1}(1)$ is algebraic over $\mathbb{Q}$
$\cos (\pi/7)$ is algebraic over $\mathbb{Q}$
$\sqrt{2}+\sqrt{\pi} $ is algebraic over $\mathbb{Q}(\pi)$

an algebraic number is a number that is a root of a non-zero polynomial in one variable with rational coefficients, I am perfectly sure that option $1$, $3$ are  algebraic number. could any one help me to find out others option?
Comment: For 1. see [When is $\sin x$ algebraic?](http://math.stackexchange.com/questions/112938/when-is-sin-x-an-algebraic-number-and-when-is-it-non-algebraic)
Answer: For option 2:
Evaluate $\sin^{-1}(1)$. It's easy
For $4$:
$\sqrt{2}+\sqrt{\pi}$ satisfies is a root of the equation:
$$(x^2-2-\pi)^2-2\pi=0$$
$$x^4-2(2+\pi)x^2+(\pi+2)^2-2\pi=0$$
$$x^4-(4+2\pi)x^2+\pi^2+2\pi+4=0$$
Hence $\sqrt{2}+\sqrt{\pi}$ is algebraic over $\mathbb{Q}(\pi)$

Here I will include the proofs of 2 useful facts:
Fact 1: Let $E$ be an extension field of a field $F$. Let $u\in E$. Then $u$
 is algebraic over $F$ iff $F(u)$ is finite dimesnsional over $F$.
Proof:
Forward direction: Consider the elements $1,u,u^2,...u^{[F(u):F]}$. If these $[F(u):F]+1$ elements were linearly independent over $F$, then the dimension of $F(u)$ over $F$ must be greater than or equal to $[F(u):F]+1$ (contradiction). Thus, we conclude that they are linearly dependent. Hence there exists $a_0,a_1,....,a_{[F(u):F]}\in F$ such that not all of thm are zero and:
$$a_{[F(u):F]}u^{[F(u):F]}+a_{[F(u):F]-1}u^{[F(u):F]-1}+...+a_1u+a_0=0$$
Hence $u$ is algebraic over $F$.
Backward direction: We start by showing that $F(u)=F[u]$. Clearly, $F[u]\subseteq F(u)$. Since $F(u)$ is the intersection of all subfields that contain $F\cup\{u\}$., therefore $F(u)\subseteq F[u]$ if $F[u]$. Now we verify that $F[u]$ is a field. Consider the  ring homomorphism $\phi: F[x]\rightarrow F(u)$ that sends $p(x)$ to $p(u)$. It can be shown that $\phi$ is surjective. Hence $F[u]\cong F[x]/Ker\phi$.    $Ker\phi=\{p(x)\in F[x]|p(u)=0\}$. Since $F$ is a field, therefore $F[x]$ is a PID. Since $Ker\phi$ is an ideal of $F[x]$, therefore $Ker\phi=(f(x))$ for some $f(x)\in F[x]$. It can be easily verified that $(f(u))$ is a prime ideal of $F[x]$. Since $F[x]$ is a PID, therefore $Ker\phi=(f(x))$ is a maximal ideal of $F[x]$. Hence $F[u]\cong F[x]/Ker\phi$ is a field. Thus $F(u)=F[u]$. Verify that $\{1,u,u^2,...,u^{deg(f)-1}\}$ is a basis for $F[u]$ over $F$. Hence, $F(u)=F[u]$ is a finite dimensional vector space over $F$.
Fact 2: Let $E$ be an extension field of a field $F$. Let $K:=\{x\in E|x$ is algebraic over$F\}$. Then $K$ is a field.
Proof: Let $x,y$ be algebraic over $F$. By fact 1, we deduce that $F(x)$ is finite dimensional over $F$. Since $y$ is algebraic over $F$, therefore $y$ is algebraic over $F(x)$. Thus, by fact 1 we deduce that $F(x)(y)$ is finite dimensional over $F(x)$. Since $F(x)$ is finite dimensional over $F$. Hence $F(x)(y)$ is finite dimensional over $F$. Since $x+y\in F(x)(y)$, therefore $F(x+y)$ is a subfield of $F(x)(y)$. Thus, $F(x+y)$ is finite dimensional over $F$. By fact 1, we deduce that $x+y$ is algebraic over $F$. Hence it is an element of $K$. The rest of the field axioms can be verified for $K$ similarly.

Since $\sqrt{2}$ is algebraic over $Q$, therefore it is algebraic over $Q[\pi]$. Similarly, $\sqrt{\pi}$ is algebraic over $\mathbb{Q}[\pi]$ (as it is the root of the equation $x^2-\pi=0$). Thus, we know that $\sqrt{2}+\sqrt{\pi}$ is algebraic over $\mathbb{Q}[\pi]$ by fact 2.
Comment: ooops $\sin ^{-1} (1)=\pi/2$ is not algebraic over $\mathbb{Q}$
Comment: Thank you very much for detail answer!


Animação jQuery antes da submissão do formulário

Question: Eu tenho este código, a animação acontece mas o redireccionamento para a próxima página (work.php) não.
Ou seja, não está a entrar na condição if (isset($_POST.... Se eu comentar o pedaço de código responsável pela animação o redireccionamento já acontece, mas não é isso que pretendo:
index.php:
if (isset($_POST['submit'])) {

    $firstName = htmlentities($_POST['name']);
    $firstName = str_replace(array('.', ',', ';', '?', '/', '|', '(', ')', 'º', '+', '#', '$', '@', "'", '"'), '' , $firstName);
    $firstName = trim(ucwords($firstName));

    if(!empty($firstName)) {
        $user->saveCookie($firstName);
    }

    header('Location: work.php');
}
require_once('includes/head.php');
?>

.....
<form action="" method="POST">
    <input name="name" type="text" autocomplete="off">
    <input type="submit" name="submit">
</form>
.....

js.js:
$('input[type="submit"]').click(function(event) {
        event.preventDefault();

        $('#footer').css({
            "position":"absolute",
            "bottom": "5px"
        });
        $('#wrapper').animate({
            "margin-top": "-1000px"
        }, 700, function(){
            $('form').submit();
        });
    });

Comment: @Kazzkiq, "redirecCionamento" é pt_PT ;)
Comment: hehe pois, mas por acaso eu também sou :P
Comment: @brasofilo My bad, eu dei uma pesquisada rápida e todos os resultados em português que vi não tinham o segundo "c", provavelmente por serem do Brasil, por isso editei a palavra.
Comment: Sem problema :)
Comment: @Kazzkiq, sem problemas, eu também já "corrigi" o Sergio só pra terminar me dando conta que é preciso tomar esse cuidado de não abrasileirar o português alheio.
Answer: O clique em "Yours" não está a executar este código. O código que está a ser executado é:
$('#formName').click(function(){
            $(this).css({
                "text-decoration": (underline = !underline) ? "none" : "underline"
            })
            $('form, h2, p').fadeToggle(500);
            $('h3').stop().animate({
                "top": (down = !down) ? "330px" : "290px"
            }, 500);
            $('form input').focus();
        });

Comment: Dsculpe, percebi agora o que quer dizer. Clique em "yours" para aparecer o form
Answer: Consegui resolver, 'submit' é uma palavra reservada de javascript logo o 'name' do 'input[type="submit"]' não pode ser 'submit', entra de alguma maneira em conflito com a função 'submit()' de javascript:
1ª alteração: HTML
<form action="" method="POST">
    <input name="userName" type="text" autocomplete="off">
    <input type="submit" name="nameCookie">
</form>

Depois disto parece que o form é submitido pois é feito um reload à página mas continua sem ser processado pela condição 'if(isset(...))' porque o redirecionamento não acontece. Continuava de alguma maneira a haver algum tipo de conflito com a parte de javascript, então alterei o argumento do 'isset', para em vez de ser o 'name' do "input[type='submit']" (nameCookie), passou a ser o 'name' do "input[type='text']" (userName):
2ª alteração: PHP
if (isset($_POST['userName'])) {
    $firstName = htmlentities($_POST['userName']);
    ...
    if(!empty($firstName)) {
        $user->saveCookie($firstName);
    }
    header('Location: work.php');
}

Não fiz qualquer alteração no js.js.
PS: Não sei (se alguém souber explique sff) os motivos técnicos para que esta segunda alteração seja necessária, mas resultou.


Sintaxe dentro de uma struct que parece uma função

Question: Estava a analisar um código em C++ e me deparei com a seguinte estrutura:
<code>struct ligacao {
  int v_;
  int w_;
  int ComEXp;
  ligacao(int v, int w, int ComEXp1) : v_(v), w_(w), ComEXp(ComEXp1) {} // Minha duvida seria concretamente aqui
};
</code>
Para que serve a 4º alinha desse trecho?
Comment: Foi util sim Ja aceitei
Answer: Isso é um método construtor. Não sabe o que é? Tem resposta sobre: Para que serve um construtor?.
Então é esse código que será executado quando for criar um objeto instanciado partindo dessa estrutura. Péra, que código? É, tem um código aí, ainda que de forma diferente.
A inicialização é feita de forma direta sem precisa atribuir os valores no corpo do método. Isso é garantido que a inicialização seja feita antes do corpo, seja feita inplace sem intermediários e que ocorra sempre, sem riscos de alguém apagar ou mudar a semântica inadvertidamente quando mexer no código do corpo. Isso pode ser visto com mais detalhes em Qual a diferença entre inicializar uma variável nesses construtores? E como colocar um construtor como padrão? e Qual é a diferença entre inicializar um construtor ou fazer atribuição dentro do construtor?.
A documentação disso está em https://en.cppreference.com/w/cpp/language/constructor.


Firefox Throws error with this js code(ReferenceError: event is not defined) need fix

Question: In chrome: if i excute this code(javascript)
<code> function abc(event){
      console.log('hello: '+event);
    }
abc(event);
</code>
the above code gives output as :
"hello:undefined"
but same code if we excute in firefox we get error
what is the simple solution for this.
Comment: Not all browsers have a global `event`, hence it is `undefined` for those browsers and not for the others.
Comment: The simple solution is to not use references that aren't defined.
Comment: Usually when using an `event` in a function, that means the function is actually triggered by an `event` like `click` or `change`. When setting the eventlistener you have the `event` there and you can pass it to another function.
Comment: @VishalPatil You're asking for the two different browsers to work the same? Good luck with that.
Comment: Browser not work as per your requirement. You need to write correct code.
Comment: But when you do that, you pass the function as event handler, not call it yourself. If you want to manually invoke the event, you need to construct an event object first and pass that.
Comment: But it's not really clear what you expect... The variable `event` doesn't exist when you call `abc`.
Comment: I know RefrenceError event is not defined in firefox passing paramerter also does not fixed it.
Comment: @Ovidiu Dolha i need same output as chrome in firefox
Comment: @  vi5ion yes i know that we should not use this but actually i need event in firefox as in my project i have given it functionality based on event variable.
Comment: The solution what i have read is that we need to pass event as parameter in many links.https://stackoverflow.com/questions/20522887/referenceerror-event-is-not-defined-error-in-firefox
Comment: i guess you should just do something like abc(this.event) but it's kinda ridiculous
Answer: There is no event happening in your script to track. You are simply calling a method and passing it a property.
If you want to grab "event" then you have to have to create an event.
Example:
This is a click event in jQuery.
<code>$(sometarget).click(function(e) {
  console.log(e);
});
</code>


Find the maximum number of points $P$ in a plane such that all the triangles having vertices in $P$ are not obtuse.

Question:
Find the maximum number of points $P$ in a plane such that all the
  triangles having vertices in $P$ are not obtuse. (Degenerate triangles are also considered)

Obviously the vertices of a rectangle satisfy the condition, and I suspect that $4$ is the maximum. Supposing otherwise, there are $5$ points satisfying the property. If there are $4$ points, let's say $A_1,A_2,A_3,A_4$ such that the convex envelope of them contains the $5$th point $A_5$, then since none of the angles $A_iA_5A_{i+1}$ is obtuse and their sum is $2\pi$, all are right angles. But in this case we have degenerate triangles - which have obtuse angle - therefore we get a contradiction. It remains open the case when none of the points is contained in the convex envelope of the other four and this is the case I need help with.
Comment: This might help: the sum of the interior angles of a convex pentagon is ...
Comment: @EthanBolker .. $3\pi$. How would this help?
Comment: One of the five angles is more than a right angle.
Comment: @EthanBolker But you assume the points are the vertices of a convex pentagon.
Comment: Isn't that the case you need help with?
Comment: @EthanBolker Well, I think you're right.
Comment: OK you can now post an answer to your own question, and accept it.
Comment: @EthanBolker Why would I do that?
Comment: People post answers to help other people. Your answer might help someone else. If @HagenvonEitzen 's answer is satisfactory you should accept it.
Answer: Let $P$ be a set, consisting of $n$ points. Among all circles having none of the points in its exterior, pick one of minimal radius. Then some points $p_1,\ldots, p_k$ are on the circle and the rest, $p_{k+1},\ldots, p_n$ are inside.
Certainly, $k\ge2$ as otherwise we can shringk the circle.
Each of the $k$ arcs determined by these points  is $\le180^\circ$, or otherwise we could shrink the circle.

Any $p_i$ outside the convex polygon spanned by $p_1,\ldots,p_k$ leads to an obtuse triangle with the two vertices determining the arc that $p_i$ is closest to.
Any $p_i$ ony an edge of said convex polygon leads to a degenerate obtuse triangle
For such any point $p_i$ in the inside of said convex polygon, the line $p_1p_i$ leaves the polygon by ntersecting some edge $p_ap_b$. Then $p_i$ is in the triangle $p_1p_ap_b$ and hence one of the triangle $p_1p_ap_i$, $p_ap_bp_i$, $p_bp_1p_i$ is obtuse (their angles at $p_i$ add up to $360^\circ$).

We conclude that $n=k$, i.e., the points of $P$ are concircular.
If the points are labelled in circular order, we must have that $p_ip_j$ is a diameter whenever $i,j$ are not concsecutive. In particulyr, $n>4$ would imply that $p_1p_3$ as well as $p_1p_4$ is a diameter, i.e., $p_3=p_4$, contradiction.
We conclude that
$n\le 4$.
Comment: Thank you for the answer. I have a question: you said "Each of the $k$ arcs determined by these points is $≤180 \circ$, or otherwise we could shrink the circle". If $k \ge 3$, no matter the measure of the arcs, we can't shrink the circle anymore since $3$ points or more determine a circle.


How do you archive an entire website for offline viewing?

Question: We actually have burned static/archived copies of our asp.net websites for customers many times.  We have used WebZip until now but we have had endless problems with crashes, downloaded pages not being re-linked correctly, etc.
We basically need an application that crawls and downloads static copies of everything on our asp.net website (pages, images, documents, css, etc) and then processes the downloaded pages so that they can be browsed locally without an internet connection (get rid of absolute urls in links, etc).  The more idiot proof the better.  This seems like a pretty common and (relatively) simple process but I have tried a few other applications and have been really unimpressed
Does anyone have archive software they would recommend?  Does anyone have a really simple process they would share?
Comment: Check out https://archivebox.io, it's an open-source, self-hosted tool that creates a local, static, browsable HTML clone of websites (it saves HTML, JS, media files, PDFs, screenshot, static assets and more).
Answer: You could use wget:
wget -m -k -K -E http://url/of/web/site

Comment: The longer, but less cryptic version: `wget --mirror --convert-links --backup-converted --adjust-extension http://url/of/web/site `
Comment: For me this just gets the index.html
Comment: Don't forget the -p switch to get images and other embedded objects, too. (-E is for converting to html extension. -K is to backup the original file with extension .orig)
Comment: From the --help, I can see what the rest do, but what do the flags K (capital) and E do?
Comment: Yes, for me too, it only retrieves index.html.  And the squarespace site I'm trying to get retrieve locally from keeps giving me error 429 "Too Many Requests". :(  I've event setup rate limiting and wait.
Comment: not working if links are with javascrpts. Javascript wget do not support.
Comment: For me, HTTrack worked a lot better. I archived a really old php page and all img tags pointed to a php file with query params. HTTrack renamed them to .jpg / .png files and adjusted the img tag accordingly.
Answer: In Windows, you can look at HTTrack.  It's very configurable allowing you to set the speed of the downloads.  But you can just point it at a website and run it too with no configuration at all.
In my experience it's been a really good tool and works well.  Some of the things I like about HTTrack are:

Open Source license
Resumes stopped downloads
Can update an existing archive
You can configure it to be non-aggressive when it downloads so it doesn't waste your bandwidth and the bandwidth of the site.
Comment: It also exists for Mac - `brew install httrack`
Comment: httrack also exists for linux.
Answer: The Wayback Machine Downloader by hartator is simple and fast.
Install via Ruby, then run with the desired domain and optional timestamp from the Internet Archive.
sudo gem install wayback_machine_downloader
mkdir example
cd example
wayback_machine_downloader http://example.com --timestamp 19700101000000

Answer: I use Blue Crab on OSX and WebCopier on Windows.
Comment: Blue Crab is a pretty damn crashy app today.
Answer: wget -r -k
... and investigate the rest of the options. I hope you've followed these guidelines:http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html so all your resources are safe with GET requests.
Answer: I just use: wget -m <url>.
Comment: This only gets the home page, not the whole site.
Answer: For OS X users, I've found the sitesucker application found here works well without configuring anything but how deep it follows links.
Comment: sitesucker.us website doesn't load as of Jan 2018.
Comment: works again but changed url to where sitesucker.us was redirecting to the author's development website ricks-apps.com
Answer: If your customers are archiving for compliance issues, you want to ensure that the content can be authenticated. The options listed are fine for simple viewing, but they aren't legally admissible. In that case, you're looking for timestamps and digital signatures. Much more complicated if you're doing it yourself. I'd suggest a service such as PageFreezer.
Answer: I've been using HTTrack for several years now.  It handles all of the inter-page linking, etc. just fine.  My only complaint is that I haven't found a good way to keep it limited to a sub-site very well.  For instance, if there is a site www.foo.com/steve that I want to archive, it will likely follow links to www.foo.com/rowe and archive that too.  Otherwise it's great.  Highly configurable and reliable.


Facebook app restricted on iPad

Question: I've created my first Facebook app at https://apps.facebook.com/splatanimate and it works fine in a PC browser but when I attempt to use it in the iPad Facebook app, it says "Use of app "Splatanimate" has been restricted" [Try Again] [Find another app]
I have checked that I have no application restrictons on in the app's Advanced Settings (e.g. age, alcohol) and there are no parental restrictions on the iPad.
Any ideas much appreciated!(or even tips on how to diagnose the problem).
Many Thanks
Comment: Have you set up a Mobile Site URL in your App's settings?
Comment: Yes...same as my main site url
Answer: Got an answer from the Facebook app developers group - turned out to be a bug in Facebook itself which they have now fixed for my app.

Facebook app restricted on iPad


OMNet++ 6: How to read real UDP video stream from internet?

Question: I have been trying to create Hardware in the Loop simulation, in which I want to get video stream from real devices into my simulation and then move those packets further into my network. Is there any existing example of this? or any way in which I can achieve this task?
Answer: Check the showcases/emulation/videostreaming folder in your INET instrallation. The text is available online.


can't query numeric field

Question: I can't seem to query on a field of type "numeric".
From hook_schema:
'id' => array(
  'description' => "ID",
  'type' => 'numeric',
  'unsigned' => TRUE,
  'precision' => 20,
  'scale' => 0,
  'not null' => TRUE,
  'default' => 0,
),

if I do something simple like the following code, I don't get anything.
$query = db_select('tablename', 't')
  ->fields('t', array('nid'))
  ->condition('id', $id, '=');

However, if I execute the following query on PHPMyAdmin, I get a row.
SELECT * FROM `tablename` WHERE id = 195755377227337728;

I did try to type cast the id with (int) $id, but that didn't work either.
Do you have any thought?
Comment: The size of your id is mind-boggling. Do you really have nearly 2 hundred quadrillion records?
Answer: Two things that might be causing the problem:

You need to execute the query: $result = $query->execute();
The id you gave is HUGE, and I don't know if it would ever work. Drupal comes with the nid column set to a length of 10.  Even if you've accounted for that, the max INT column size in MySQL is 4294967295 and your ID is 195755377227337728.  Theoretically you could use BIG INT instead of INT.  See: MySQL column type sizes

Also, try this Static Query instead of db_select():
$result = db_query("SELECT nid FROM {table} WHERE nid = :nid", array(':nid' => $nid,));

Comment: Ignore my answer (I've deleted it), my maths was off :) That ID is perfectly acceptable for PHP and MySQL as an integer type (assuming a 64bit system). Thanks @kiamlaluno for the sanity check. My money's on the problem being that the query hasn't been executed.
Comment: Well, I ended up having to do this (didn't try the Static Query option).  $rec = db_query("SELECT nid FROM {table} WHERE id = $id")->fetchAssoc();

can't query numeric field


Topological Spaces, Homeomorphism

Question: Let $X,Y,U,V$ be topological spaces, and $X$ is homeomorphic to $U$ and $Y$ is homeomorphic to $V$
Then is $X\times Y$ homemorphic to $U\times V$?
I have got the following maps
$n\colon X \rightarrow  U$
$m\colon U \rightarrow X$
$s\colon Y \rightarrow V$
$t\colon v \rightarrow Y$
with $m\circ n \cong Id_X$
$n\circ m \cong Id_U$
$t\circ s \cong Id_Y$
$s\circ t \cong Id_V$
But I have no idea how to use these!
edit : so to show that it is a homeomorphism can I show that
$g \circ f(x,y) = (m \circ n(x), t \circ s(y))$ and can i then say that this is homeomorphic to $Id_{X \times Y}$ as $m \circ n$ is to $Id_X$ and $t \circ s$ is to $Id_Y$ ?
Comment: Hi - have you tried anything yourself? If you give any ideas that you have had, even if they haven't worked out, it would be useful, and you would likely get a lot more responses
Comment: @JoeTait I have added an extra few lines, can i say that?
Comment: Please use LaTeX in your future questions: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: The map $f:X\times Y\to U\times V$ defined by
$f(x,y)=(n(x),s(y))$ is an homeomorphism with inverse $g(u,v)=(m(u),t(v))$.
Comment: i have added a few extra lines, is it sufficient to say that, and then for fog also?

Topological Spaces, Homeomorphism


Get a list of SQL Server Agent Jobs

Question: I've got an extensive selection of these to add to a spreadsheet and don't want to go through by hand.
What it the T-SQL command(s) to generate a list of SQL Server Agent Jobs?
Answer: On each server, you can query the sysjobs table in the msdb. For instance:
SELECT job_id, [name] FROM msdb.dbo.sysjobs;

Comment: Thanks, I think you just beat me to the punch so you get the prize!
Answer: -- List of all the jobs currently running on server
SELECT
     job.job_id,
     notify_level_email,
     name,
     enabled,
     description,
     step_name,
     command,
     server,
     database_name
FROM
    msdb.dbo.sysjobs job
INNER JOIN
    msdb.dbo.sysjobsteps steps
ON
    job.job_id = steps.job_id
WHERE
    job.enabled = 1 -- remove this if you wish to return all jobs

Comment: Can you format the SQL?
Answer: Here is my contribution - also gets the category name and filters out the report server jobs.
SELECT  sysjobs.name 'Job Name',
        syscategories.name 'Category',
        CASE [description]
          WHEN 'No Description available.' THEN ''
          ELSE [description]
        END AS 'Description'
FROM    msdb.dbo.sysjobs
        INNER JOIN msdb.dbo.syscategories ON msdb.dbo.sysjobs.category_id = msdb.dbo.syscategories.category_id
WHERE   syscategories.name <> 'Report Server'
ORDER BY sysjobs.name

Answer: My boss actually sorted out what I was after - this gave me the list I was after.
USE msdb
SELECT     name
FROM         sysjobs

Get a list of SQL Server Agent Jobs


Why do lighter picks sound "better" on acoustic guitars?

Question: I have a small variety of Dunlop Tortex pick sizes. Normally, the 0.73mm (green) is my favorite. When I recently picked up my first acoustic in ages, I chanced to discover that the lighter 0.56mm (I think, red) sounded sooooo much more brilliant. The lighter pick seems to make it sound brighter (for strummed chords). Why would a lighter pick create a "fuller", "brighter" sound?
EDIT: I should add that my electric guitars use 0.010-0.048 EB Slinkys, while this acoustic is strung with Martin "light" gauge strings.
Answer: When you have a lighter pick, it will bend more against the string before releasing, so the force on the string will be less, and the angle will be more like stroking the string rather than plucking it.
The lighter sound comes from a combination of the strings being easier to strum, and the softer sound made when you use a lighter pick.
The downside to lighter picks is that you have less control playing on a single string.  try playing some tremolo with a thin pick and a thicker one and you'll quickly realise that the bendiness of the lighter pick works against you.
Comment: I have a thin brass pick that's very stiff but still has the brilliant thin pick sound. I'm sure it has more to do with mass than flexibility.
Comment: generally mass reduces the flexibility, and in this case since you're using the same brand of picks at both widths I'm assuming the material is also the same.
Comment: If the materials were different between picks you could have a thicker, more flexable pick, between rubber, silicone, steel and plasic for example.


How to apply a patch file in composer to a submodule of a module?

Question: I've added the patch to composer.json like this:
  "drupal/admin_toolbar_tools": {
    "Bring back media to dropdown menu": "https://www.drupal.org/files/issues/2019-01-16/admin_toolbar-media_link-3026216-3-option2-D8.patch"
  }

However, admin_toolbar_tools is a sub-module of admin_toolbar (admin_toolbar/admin_toolbar_tools).
I ran composer install, but it doesn't trigger the patch apply process.
The patch I am trying to apply is the following one (https://www.drupal.org/files/issues/2019-01-26/admin_toolbar-media-link-3026216-8-option3.patch).
diff --git a/admin_toolbar_tools/admin_toolbar_tools.module b/admin_toolbar_tools/admin_toolbar_tools.module
index 9ac389c..1f8a36b 100644
--- a/admin_toolbar_tools/admin_toolbar_tools.module
+++ b/admin_toolbar_tools/admin_toolbar_tools.module
@@ -621,20 +621,23 @@ function admin_toolbar_tools_menu_links_discovered_alter(&$links) {

   // If module Media enabled.
   if ($moduleHandler->moduleExists('media')) {
-    $links['admin_toolbar_tools.add_media'] = [
-      'title' => t('Add media'),
-      'provider' => 'admin_toolbar_tools',
-      'route_name' => 'entity.media.add_page',
-      'menu_name' => 'admin',
-      'parent' => 'system.admin_content',
-    ];
+    // Displays media link in toolbar.
+    if (in_array('entity.media.collection', $routes)) {
+      $links['admin_toolbar_tools.media_add_page'] = [
+        'title' => t('Add media'),
+        'provider' => 'admin_toolbar_tools',
+        'route_name' => 'entity.media.add_page',
+        'menu_name' => 'admin',
+        'parent' => 'system.admin_content',
+      ];
+    }
     // Add node links for each media type.
     foreach ($entityTypeManager->getStorage('media_type')->loadMultiple() as $type) {
       $links['media.add.' . $type->id()] = [
         'title' => t($type->label()),
         'provider' => 'admin_toolbar_tools',
         'route_name' => 'entity.media.add_form',
-        'parent' => 'admin_toolbar_tools.add_media',
+        'parent' => 'admin_toolbar_tools.media_add_page',
         'route_parameters' => ['media_type' => $type->id()],
       ];
     }

Comment: Did you try just it's parent namespace admin_toolbar?
Comment: Yes I did try that, but it's not working.  I'll try again.  thanks @Kevin
Answer: Use admin_toolbar.
"drupal/admin_toolbar": {
  "Bring back media to dropdown menu": "https://www.drupal.org/files/issues/2019-01-16/admin_toolbar-media_link-3026216-3-option2-D8.patch"
}

Then run composer update or composer update --lock if you want to apply your new patch and do not want to update any packages.


How to run Vue.js from within iOS/Android app?

Question: Currently we have an app contains a webview, in webview the url address is our remote server. Problem is that when start app it will connect to our server to download html/js/css to show content. If network is slow, it will take long time to show a white screen.
For traditional html/css/js, we can just put all the contents in a local folder, then tell webview to load content from that local folder.
But we are using Vue.js. As you may know, even we build Vue.js to /dist folder, you cannot directly use file:// to access them, it must depends on a server.
So my question is: how can we run a small server in iOS/Android app to serve these /dist contents? So that webview can access http://localhost:8080 something to show the content.
Thank you!
Comment: I have exact same requirement. and I am stuck. Did you find any solution for this ?
Comment: @Nightswatch The only way I think of is to bundle a termux in app and run a nginx server in it. You can google for "termux".
Answer: Webview cannot access localhost.  Think about it, webview is running on someone's device, and that device doesn't (and can't ever) know what localhost is. If the http requests in your vue app go out to an actual, live http:// or https:// server, then the vue instantiation will work in a WebView (at least in Android, which is what I know).


A curious equality of integrals involving the prime counting function?

Question: This post discusses the integral,
$$I(k)=\int_0^k\pi(x)\pi(k-x)dx$$
where $\pi(x)$ is the prime-counting function. For example,
$$I(13)=\int_0^{13}\pi(x)\pi(13-x)dx = 73$$
Using WolframAlpha, the first 50 values for $k=1,2,3,\dots$ are,
$$I(k) = 0, 0, 0, 0, 1, 4, 8, 14, 22, 32, 45, 58, 73, 90, 110, 132, 158, 184, 214, 246, 282, 320, 363, 406, 455, 506, 562, 618, 678, 738, 804, 872, 944, 1018, 1099, 1180, 1269, 1358, 1450, 1544, 1644, 1744, 1852, 1962, 2078, 2196, 2321, 2446, 2581, 2718,\dots$$
While trying to find if the above sequence obeyed a pattern, I noticed a rather unexpected relationship:

Q: For all $n>0$, is it true,
  $$I(6n+4) - 2\,I(6n+5) + I(6n+6) \overset{\color{red}?}= 0$$

Example, for $n=1,2$, then
$$I(10)-2I(11)+I(12)=32-2*45+58 = 0$$
$$I(16)-2I(17)+I(18)=132-2*158+184= 0$$
and so on.
Comment: I checked your result up to $n=533$ (for $n \geq 534$, I have problems. Would you be interested by a huge table of $I(k)$ (I was able to generate it up to $k=540$). This is  a very interesting problem.
Comment: I have checked to confirm what you're asking is true for $n$ up to $18$. However, I have my doubts it'll always work, partially because it doesn't work for $n = 0$. Also, a similar type condition is that $I(6n) - 2I(6n + 1) + I(6n + 2) = 2$, which holds for $1 \le n \le 5$, but at $n = 6$, the LHS becomes $0$ instead. If I get a chance, I will investigate your equation to see if I can figure out why it's true for at least the first $18$ values and, more importantly, will it always stay true. Regardless, though, it's an excellent observation you've made, even if it doesn't always hold.
Comment: Up to $k=540$, $I(k)$ is a prime for this list $$\{13,57,119,167,171,173,175,341,395,397,427,431,473,515,519\}$$
Comment: Note your proposed equation doesn't hold for $n = 0$ as $I(4) = 0$, $I(5) = 1$ and $I(6) = 4$.
Comment: @JohnOmielan: A typo. I meant all $n>0$. I will correct it.
Comment: @ClaudeLeibovici: Thanks for checking, Claude! However, that table would be too huge for MSE. :)
Comment: @JohnOmielan: The conjecture is correct per Greg Martin's answer.
Comment: @ClaudeLeibovici: Oh, can you check your table how many $I(k)$ are prime? I've found 7 so far. That can be a partial answer to Ultradark's question in [the linked post](https://math.stackexchange.com/questions/3128276/how-many-primes-does-this-sequence-find).
Comment: @TitoPiezasIII I realized later as I was walking outside that your conjecture was correct, basically for the reason given in Greg Martin's answer. I was planning to write it up as an answer, but Greg beat me to it.
Comment: @ClaudeLeibovici: Pls send me the data as a txt file. I can copy-paste it into my very old Mathematica. My email is on my profile page.
Comment: As I did promise GNUSupporter 8964民主女神 地下教會 , I delete my "answer" which was the the table of the $I(k)$'s. You can still recover them from the deleted answer (you have a more than sufficient reputation for doing it). What about the suggested idea to submit the sequence to $OEIS$ ? IN any manner, I would like a discussion on chat. When you are availble, open a chat room and tell me to join you there.
Comment: @ClaudeLeibovici: Feel free to submit the sequence to OEIS (with a link to this post). You found more of the sequence than I did. :)
Comment: @TitoPiezasIII. By the end, did you get my e-mails and the files ? May I suggest that you submit the sequence (with me if you want). But I have had a lot of trouble trying to add stuff in OEIS so I prefer not to do the work. By the way, if you are available, could we go to a chat room ? If yes, open it and tell me. Cheers.
Comment: @ClaudeLeibovici: Yes, I got all your emails starting with the 2nd and responded to most. So I assume you didn't get my replies? I also had problems adding stuff in OEIS so I'm deferring that for now.
Comment: @TitoPiezasIII. I just received **1** e-mail from you where you gave me the MMA syntax.
Comment: Please raise a flag once you don't need the comments anymore. I don't want to complicate your communication, but certainly there is no point to keeping it indefinitely around.
Comment: By the way, this is [A333700](https://oeis.org/A333700) in the OEIS.
Comment: @JianingSong Thanks for the info. Too bad there is no link to this post.
Comment: @TitoPiezasIII Don't worry, I had already made an edit to that sequence to add the link to this question (and also your observation), before citing this A-number here. :)
Answer: The answer is yes. Sketch of solution:
$$
I(k) = \int_0^k \sum_{p\le x} \sum_{q\le k-x} 1 \,dx = \sum_p \sum_{q\le k-p} \int_p^{k-q} dx = \sum_p \sum_{q\le k-p} (k-(p+q)) = \sum_{m\le k} r(m)(k-m),
$$
where $r(m)$ is the number of ways of writing $m$ as the sum of two primes. Then
\begin{align}
I(6n+6) &{}-2I(6n+5)+I(6n+4) \\
&= \sum_{m \le 6n+4} r(m)\big((6n+6-m)-2(6n+5-m) +(6m+4-m)\big) + r(6n+5) \\&= 0 + r(6n+5);
\end{align}
and $r(6n+5)=0$ for every $n\ge1$, since the only way the odd integer $6n+5$ can be the sum of two primes is $6n+5=2+(6n+3)$, but $6n+3=3(2n+1)$ is always composite when $n\ge1$.
The same argument gives $I(6n+2)-2I(6n+1)+I(6n) = r(6n+1)$, which is $2$ if $6n-1$ is prime and $0$ otherwise; this is why (as observed by John Omielan) it equals $2$ for $1\le n\le 5$ but $0$ for $n=6$.
Comment: MSE never ceases to amaze me how fast some people can figure out the answer.
Comment: This really surprises me since I thought the equation will be eventually false...
Comment: Greg, do you know how to address Ultradark's [question](https://math.stackexchange.com/questions/3128276/how-many-primes-does-this-sequence-find) regarding when $I(k)$ is prime?
Comment: @stressedout it's arguably worse due to the HNQ list


Proving equivalence of two definitions of "dense" in $\mathbb R$

Question: Ok, so I've been trying to learn how to write proofs and I've been given this definition for DENSE:
D is dense in $R$ if for each x $\in$ $R$, $\exists$ {${d_n}$}$_{n=1}{^\infty}$ $\in$ D with $\lim_{n \to \infty} d_n$ = x
How would I go about starting to prove this? Is there a particular method that would be easiest?
EDIT: This is another definition I was given.
A set D $\subseteq R$ is DENSE if for each a < b, a,b $\in R$, $\exists$ d $\in$ D with a < d < b
Comment: Is that your definition of "dense"?  You can't prove a definition.  However, you can prove the equivalence of two definitions.  Do you know another way to define a "dense" set?  What fact are you trying to prove, and what facts are you starting with?
Comment: Well I was also given this definition.
Comment: You need to prove that both definitions are equivalent??
Comment: Well, if I can't prove a definition, then I guess I need to show equivalence of the two. How do I show the first is equivalent to the second?
Answer: The bottom definition is, in English,

A subset $D$ of $\mathbb{R}$ is dense if every open interval contains a member of $D$.

and the definition you are trying to prove is

A subset $D$ of $\mathbb{R}$ is dense if every point in $\mathbb{R}$ is the limit of some sequence of elements of $D$.

To prove that these are equivalent, you will have to show that the first implies the second and that the second implies the first.
To show that the first implies the second, begin by assuming that we have a set $D$ satisfying the first definition, that is every open interval in $\mathbb{R}$ contains a member of $D$.  Using this information, can you construct some sequence $\{d_n\}$ that converges to a limit $x$?  Perhaps by using a sequence of intervals containing or approaching $x$?
To show that the first implies the second, begin by assuming that every point $x \in \mathbb{R}$ is a limit of some sequence $\{d_n\}$.  If $d_n \rightarrow x$, what can we say about the existence of some $d_i$ in an open interval containing $x$?


django registration redux ignoring changes in templates

Question: I've been struggling with Django registration redux over the past two weeks. I'm using the templates that were provided in the documentation and I've made a couple of changes like adding crispy forms and changing the button and some other stuff but the problem is that none of these changes are being shown on http://127.0.0.1:8000/accounts/register or any other link.
I'm using Django registration redux 1.4, Django 1.8, python 2.7.10
Comment: Where do you store your customized templates?
Comment: @arie templates/register
Answer: Putting your customized templates in templates/registration (not register) should work.
At least if your TEMPLATES setting is correctly configured: https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/
And you probably already checked this hint from the project's FAQ?

I want to use custom templates, but django keeps using the admin
  templates instead of mine!
To fix this, make sure that in the INSTALLED_APPS of your settings.py
  the entry for the registration app is placed above
  django.contrib.admin.
Comment: Yes, I already did that. (sorry I meant templates/registration.)
Comment: And your TEMPLATES setting (see above) is correctly set for Django 1.8.? Does overwriting other templates (e.g. Django's admin templates) work?
Comment: Yes. the settings are correct, and everything else works just fine expect this part
Comment: That's strange. I just used the same app in a project and had no problems at all customizing the templates.


What does strict exogeneity condition of OLS really mean?

Question: In Hayashi's Econometrics, it is stated that one of the assumption of classical OLS is: $$\mathbb{E}(\epsilon_i\lvert\mathbf{x_1}, \mathbf{x_2}, \ldots, \mathbf{x_n}) = 0 \text{, for } i=1, \ldots, n. \tag{1}$$ And I know that the implications are that $\mathbb{E}(\epsilon_i) = 0$ for all $i = 1, \ldots,n$, and that the error term is uncorrelated with the regressors.
But, what does the equation (1) in itself actually mean? A pedagogical example would be helpful.
Answer: In English, it means that conditional on observing the data, the expectation of the error term is zero.
How might this be violated?
Example: omitted variable correlated with $x$
Imagine the true model is:
$$ y_i = \alpha + \beta x_i + \gamma z_i + u_i$$
But instead imagine we're running the regression:
$$ y_i =  \alpha + \beta x_i + \underbrace{\epsilon_i}_{\gamma z_i + u_i}$$
Then:
$$\begin{align*}
E[\epsilon_i \mid x_i ] &= E[\gamma z_i + u_i \mid x_i] \\
&=\gamma E[ z_i\mid x_i] \quad \text{ assuming $u_i$ is white noise}
\end{align*}$$
If $E[z_i \mid x_i] \neq 0$ and $\gamma \neq 0$, then $E[\epsilon_i \mid x_i] \neq 0$ and strict exogeneity is violated.
For example, imagine $y$ is wages, $x$ is an indicator for a college degree, and $z$ is some measure of ability. If wages are a function of both education and ability (the true data generating process is the first equation), and college graduates are expected to have higher ability ($E[z_i \mid x_i] \neq 0]$) because college tends to attract and admit higher ability students, then if one were to run a simple regression of wages on education, the strict exogeneity assumption would be violated. We have a classic confounding variable. Ability causes education, and ability affects wages, hence our expectation of the error in equation (2) given education isn't zero.
What would happen if we did run the regression? You would pickup both the education effect and the ability effect in the education coefficient. In this simple linear example, the estimated coefficient $b$ would pick up the effect of $x$ on $y$ plus the association of $x$ and $z$ times the effect of $z$ on $y$.
Comment: @MitchBaker Thanks for the comment. Indeed $E[z|x]$ is most directly at issue. I've tried to clarify somewhat.
Comment: Hello Matthew, I think in the second-to-last paragraph "more able individuals are more likely to obtain a college degree" should be replaced by something along the lines of "college graduates are expected to be more able persons", as we are considering $E(z_i|x_i)$ and not $E(x_i|z_i)$.
Comment: One the one hand, $E(Y|X=x,Z=z)=\alpha+\beta x+\gamma z$. On the other hand, $E(Y|X=x)=\delta+\theta x$ with $\delta\neq\alpha$ and $\theta\neq\beta$ except for special cases. These are conditional mean models that have nothing to say about causality. In this context, the regression $y_i=\alpha+\beta x_i+\epsilon_i$ has misleading parameter names. The following analysis of the error term suffers from the same problem. Perhaps some $\text{do}(\cdot)$ calculus notation is in order to disentangle the conditional mean parameters from the causal ones.
Comment: @RichardHardy Yeah, to be more precise my hypothetical example should have said something like $u$ is independent and distributed $\mathcal{N}(0, \sigma^2)$.
Comment: I am not sure that would help. The problem is that defining exogeneity only in terms of probability distributions and their derived features – without $\text{do}(\cdot)$ calculus or potential outcomes – gets hard to follow quite fast and probably does not get very far in the end. (I am reading Pearl ["Exogeneity and Superexogeneity: A No-tear Perspective"](https://escholarship.org/content/qt6kq1m2mp/qt6kq1m2mp_noSplash_2c8fc4751405174a9f330dc67c3050db.pdf) (2000) where this case is made in just a few pages.)


How to add column with Colon : in column name in table using SQL Server

Question: I have two SQL server databases, DB1 and DB2.
I am getting table and column names from DB1 and need to create the same in DB2.
While using SQL query to insert table and column in DB2, I am getting an error

Invalid Syntax near :

In DB1, the table name is Person and its columns are P:ID, P:Address.
This is the query which I used to create a new table with above column names in DB2:
INSERT TABLE NEW_PERSON (P:Name varchar(255), P:Address varchar(255))

I got references for MySQL database but my need is for SQL Server database.
Thank you in advance
Comment: Why are you prefixing all columns in the table with `P:` anyway? I suggest not doing that
Comment: Use Delimited identifiers. See [Database Identifiers](https://learn.microsoft.com/en-us/sql/relational-databases/databases/database-identifiers?view=sql-server-ver16#classes-of-identifiers) section in the docs
Comment: If possible in any way try to avoid special characters in db object like table names, column names etc. It will make your life much easier. If that's not possible here tell us why.
Comment: You may rethink you syntax by the way. I doubt you created a table with a `INSERT` statement.
Comment: In this example , I hardcoded column names with colon but in my Case  i Got column names from SQL Server Database 1 .In server itself it has Column name with colon attached below image .
I am getting all column names and stored in List .
Then for creating new table with column names in List by using above query i am getting invalid syntax error .

COLUMN_NAME
ARAS:UNIQUENESS_HELPER
KEYED_NAME
ID
Answer: P:Name will become [P:Name]
But please dont: special characters in database object names will lead to problems.


Defining additions in the ring of integers

Question: Is it possible to describe all possible ways in which one can define additions in the set of integers to give it a structure of ring when the multiplication is same as the usual multiplication ?
If the addition is same as the usual addition then one can easily describe all possible multiplications. What can we say when multiplication is usual ?
Comment: When you don't fix any structure, you just have a countable set. There is not much to say.
Comment: @Martin Brandenburg Yeah, I understand that there is not much to say about the general case. Can we say something when multiplication is usual ?
Answer: I assert the multiplicative structure of the integers is completely characterized by these three properties:

There are exactly two units: the square roots of unity
A unique factorization domain
Has countably infinitely many prime elements

So any ring with these three properties is isomorphic to the integers with non-standard addition, and conversely any non-standard addition defined on the integers gives a ring with these three properties.
Some examples of rings with these properties are:

Any polynomial ring over the integers
Any polynomial ring over the finite field of 3 elements
Any polynomial ring over the ring of integers in an imaginary quadratic number field of class number 1 that is neither $\mathbb{Q}(i)$ nor $\mathbb{Q}(\sqrt{-3})$.
Comment: Is there a classification of all such rings? I mean can you explicitly give me a list of all possible rules of multiplications?
Comment: The above is a classification of all such rings. :) But I know what you're asking, and I expect it to either be unfeasible or it has a simple answer that requires more arithmetic geometry than I know.
Comment: Nit-pick: a couple of those imaginary quadratic extensions with class number 1 have more than two units.
Comment: Argh. I think every version of that last bullet I had written down carefully avoided those two cases, except for the one I actually posted. :(
Answer: As Hurkly mentioned, this amounts to finding rings whose multiplicative monoid is isomorphic to that of the ring of integers, which is freely generated by the primes, and by the Conway prime $\,-1,$ of order $\,2$. Thus one seeks UFDs with two units and countably many primes. It is easy to find examples among well-known examples of UFDs (polynomial rings, number fields, etc).
Many properties of domains are purely multiplicative so can be described in terms of monoid structure. Let R be a domain with fraction field K. Let R* and K* be the
multiplicative groups of units of R and K respectively. Then
G(R), the divisibility group of R, is the factor group K*/R*.

R is a UFD $\iff$ G(R) $\:\rm\cong \mathbb Z^{\,I}\:$ is a sum of copies of $\rm\:\mathbb Z\:.$
R is a gcd-domain $\iff$ G(R) is lattice-ordered (lub{x,y} exists)
R is a valuation domain $\iff$ G(R) is linearly ordered
R is a Riesz domain $\iff$ G(R) is a Riesz group, i.e.
an ordered group satisfying the Riesz interpolation property: if  $\rm\:a,b \le c,d\:$  then  $\rm\:a,b \le x \le c,d\:$  for some $\rm\:x\:.\:$ A domain $\rm\:R\:$ is  Riesz if every element is primal, i.e. $\rm\:A\:|\:BC\ \Rightarrow\ A = bc,\ b\:|\:B,\ c\:|\:C,\:$ for some $\rm b,c\in R.$

For more on divisibility groups see the following surveys:
J.L. Mott. Groups of divisibility: A unifying concept for
integral domains and partially ordered groups, Mathematics
and its Applications, no. 48, 1989, pp. 80-104.
J.L. Mott. The group of divisibility and its applications,
Conference on Commutative Algebra (Univ. Kansas, Lawrence, Kan.,
1972), Springer, Berlin, 1973, pp. 194-208. Lecture Notes in Math.,
Vol. 311. MR 49 #2712


theme_image_style() doesn't output what is expected

Question: I have a module that doesn't seems to work correctly, so I dived into its code, and there is something that I don't understand:
The module does something like this: (I replaced the 'path' key with an hardcoded value to show the problem)
$params = array(
    'style_name' => $presetname,
    //'path' => $image_url,
    'path' => "public://images/image.jpg",
    'attributes' => $attributes,
    );

Then $param is sent to the theme_image_style() hook
$img = theme('image_style', $params);

The problem is that if i dump the output of theme_image_style():
dpm( $img);

then i get

In admin/config/media/file-system, my public path is set as: sites/default/files
I should have:
src="http://mysite.local/sites/default/files/images/image.jpg

instead of:
src="http://mysite.local/sites/default/files/styles//public/images/image.jpg

Why does the theme function add 'styles//public' and where could I remove this?
Thanx in advance for your help
Comment: If you don't want a styled version of the image, don't use `theme_image_style`, - use `theme_image` instead
Answer: Drupal 7 provide Image style functionality which allow administrator to set predefined size and can apply image style to any image in site.

Using image styles you can scale, crop, resize, rotate and desaturate
  images without affecting the original image. By default three sizes
  are defined: 'thumbnail,' 'medium', and 'large'. The thumbnail style,
  for example, is shown with the teaser for image posts and when
  browsing image galleries.

In your code, you have defined $img = theme('image_style', $params); which mean that you are applying image style to your image.
When we apply image style to any image, it will create a new image in styles/[stylename]/public directory and does not affect the original image source.
There is no stylename in your http://mysite.local/sites/default/files/styles//public/images/image.jpg url after style part of url, so I guess $presetname is not properly defined in your code.
You can try below exammple:
$params = array(
    'style_name' => 'thumbnail',
    //'path' => $image_url,
    'path' => "public://images/image.jpg",
    'attributes' => $attributes,
    );
$img = theme('image_style', $params);

Comment: Thanx jayendra,

I added a style to my picture, and it works now!  :)


Two conics have exactly one intersection point

Question: We have two conics $Q_1,Q_2$ on $\mathbb{P}_2$ over some algebraically closed field. Also $Q_1$ and $Q_2$ are supposed to be smooth. I've just discovered Bezout's theorem, which states that two algebraic curves with degrees $m$ and $k$ have exactly $km$ intersection points (of course some of them can be the same). So, I'd like to build some examples when two conics have exactly $1,2,3$ and $4$ distinct intersection points. All cases but not the $1$st are quite easy. For example, $q_1(x,y,z)=x^2+y^2-z^2$ and $q_2(x,y,x)=x^2+2y^2-z^2$ are two polynomials which define smooth conics on $\mathbb{P}_2$ and they have exactly $2$ intersection points $(1:0:1)$ and $(1:0:-1)$. When we need three or four points, there are similar examples. But what about $1$ point? I cannot build an example. Is it possible? I'd like to note that conics are smooth.
Answer: The conics $x^2-yz=0$ and $x^2+z^2-yz=0$ are smooth (in all characteristics) and intersect only in one point, namely $[0:1:0]$.
Comment: What is the method to finding the intersection? you follow the classic way?
Comment: @Bill:  For  $z=1$  you must solve $x^2-y=0, x^2+1-y=0$ (no solution) and for $z=0$ you must solve $z=0, x^2=0$ whose only solution is $[0:1:0]$ .
Comment: Thank you so much, I have two conics in $\mathbb{P]^2$, is there anyway to find the intersection of the conics by their symmetric matrices?
Answer: Take any two pairs of intersecting lines with different slope: $x^2+a_1y^2=0$ and $x^2+a_2y^2=0$ for $a_1 \neq a_2$. They only cross at the origin $(0:0:1)$
Also, take the double y axis $x^2=0$ and the double x axis $y^2=0$ (or any pair of double-lines with different slopes), which again only cross at the origin.
Comment: Dear rewritten, your conics are not smooth.
Comment: You are completely right.


Integral $\int \frac {dx}{\sin^2 x + \tan^2x}$

Question:
I am trying to find the following integral:
  $$\int \frac {dx}{\sin^2 x + \tan^2x}$$

I have tried the common thing to do when encountering rational functions that contains rational functions and converting everything in  terms of $\tan \frac{x}{2}$ then substituting it.
$$\tan\frac{x}{2}=t\Rightarrow \sin x=\frac{2t}{1+t^2},\ \cos x=\frac{1-t^2}{1+t^2},\  dx=\frac{2}{1+t^2}dt$$
$$\Rightarrow \int \frac{dx}{\sin^2 x + \frac{\sin^2 x}{\cos^2 x}}=\int \frac{\frac{2}{1+t^2}}{\left(\frac{2t}{1+t^2}\right)^2+\left(\frac{2t}{1-t^2}\right)^2}dt$$
However I am stuck. Is there perhaps an easier way to approach it?
Answer: Let $t=\tan(x)$, then $dx=dt/(1+t^2)$ and $\sin^2(x)=t^2/(1+t^2)$. Hence
$$\int \frac {dx}{\sin^2 x + \tan^2x}=\int \frac {dt}{(t^2+ (1+t^2)t^2)}=\int \frac {dt}{t^2(2+t^2)}=\frac{1}{2}\int \frac {dt}{t^2}-\frac{1}{2}\int \frac {dt}{2+t^2}.$$
Can you take it from here?
P.S. By letting $t=\tan(x/2)$, then $dx=2dt/(1+t^2)$, $\sin(x)=2t/(1+t^2)$ and $\tan(x)=2t/(1-t^2)$. Then we obtain the integral of a more complicated rational function.
Comment: For a trigonometric rational function a general substitution is $ t=\tan x$ (so your approach is right). In this case, with the squares, in order to have a polynomial of lower degree at the denominator it's better to use $t=\tan x$.
Comment: @rikodusennin We can write $\sin x,\,\cos x$ as functions of $\tan x/2$ as all three have the same period, $2\pi$. When each sine and cosine is raised to an even power, their period halves and we can use $\tan x$.
Comment: Thanks a lot . I have a very generic question. Will the substitution t=tanx work whenever we have sin x and cos x in the integrand?
Answer: $$\dfrac1{\sin^2x+\tan^2x}=\dfrac{\cos^2x}{\sin^2x(1+\cos^2x)}$$
Method$\#1:$
$$=\dfrac{\cos^2x+1-1}{\sin^2x(1+\cos^2x)}=\csc^2x-\dfrac1{(1-\cos^2x)(1+\cos^2x)}$$
Now $$\dfrac2{(1-\cos^2x)(1+\cos^2x)}=\dfrac1{1-\cos^2x}+\dfrac1{1+\cos^2x}$$
Finally $$\dfrac1{1+\cos^2x}=\dfrac{\sec^2x}{2+\tan^2x}$$
Method$\#2:$
$$\dfrac{\cos^2x}{\sin^2x(1+\cos^2x)}=\dfrac c{(1-c)(1+c)}=\dfrac A{1-c}+\dfrac B{1+c}$$ using Partial Fraction Decomposition where $c=\cos^2x$
Answer: $$\begin{align}\int\dfrac{dx}{\sin^2{(x)}+\tan^2{(x)}}\cdot\dfrac{\sec^2{x}}{\sec^2{x}}&=\int\dfrac{\sec^2{x}\ dx}{\tan^2{x}+\sec^2{x}\tan^2{x}}\\
&=\int\dfrac{\sec^2{x}\ dx}{\tan^2{x}+(\tan^2{x}+1)\tan^2{x}}\\
&=\int\dfrac{\sec^2{x}\ dx}{2\tan^2{x}+\tan^4{x}}\end{align}$$
Let $u=\tan{x}$ and $du=\sec^2{x}\ dx$
$$\begin{align}
&=\int\dfrac{du}{u^4+2u^2}\\
&=\int\left(\dfrac{1}{2u^2}-\dfrac{1}{2(u^2+2)}\right)du\\
&=-\dfrac{1}{2}\int\dfrac{du}{u^2+2}+\dfrac{1}{2}\int\dfrac{du}{u^2}\\
&=-\dfrac{1}{2}\int\dfrac{du}{2(\frac{u^2}{2}+1)}+\dfrac{1}{2}\int\dfrac{du}{u^2}\\
&=-\dfrac{1}{4}\int\dfrac{du}{\frac{u^2}{2}+1}+\dfrac{1}{2}\int\dfrac{du}{u^2}\end{align}$$
Let $s=\frac{u}{\sqrt{2}}$ and $ds=\frac{du}{\sqrt{2}}$.
\begin{align}
&=-\dfrac{1}{2\sqrt{2}}\int\dfrac{ds}{s^2+1}+\dfrac{1}{2}\int\dfrac{du}{u^2}\\
&=-\frac{\arctan{s}}{2\sqrt{2}}+\dfrac{1}{2}\int\dfrac{du}{u^2}\\
&=-\frac{\arctan{s}}{2\sqrt{2}}-\frac{1}{2u}+C\\
&=-\frac{\sqrt{2}u\arctan{\frac{u}{\sqrt{2}}+2}}{4u}+C\\
&=-\frac{1}{4}\left(\sqrt{2}\arctan{\frac{\tan{x}}{\sqrt{2}}\tan{x}+2} \right)\cot{x}+C
\end{align}
Which is equal to
$$-\frac{1}{4}\left(\sqrt{2}\arctan{\frac{\tan{x}}{\sqrt{2}}+2\cot{x}}\right)+C.$$
Comment: OP's integral is not $\int\sin^2{(x)}\tan^2{(x)}\ dx$...
Comment: As @RobertZ, has pointed out , the question is not regarding $∫\sin^2(x)\tan^2(x) dx$ . If there are any intermediate steps that you have used to arrive to that step, please point it out.


Magento USPS Not Properly Making API Request For International Country

Question: I have a magento store that needs to be able to ship orders to Curacao. By default this is grouped as Netherland Antilles in Magento, however, I found that even setting the order to this, wont get me the correct shipping rates from USPS even though international shipping is enabled.
I have added the country to magento via the en.xml file, and through the admin. I have enabled it as a country we can ship to under the USPS shipping method, and in the directory_country table in magento.
When the USPS API is called, I see this as a request and result:
2015-11-30T22:08:15+00:00 DEBUG (7): Array
(
[request] => <?xml version="1.0" encoding="UTF-8"?>
<IntlRateV2Request USERID="725CIGAR7315"><Revision>2</Revision><Package ID="0"><Pounds>0</Pounds><Ounces>0.8</Ounces><MailType>All</MailType><ValueOfContents>1</ValueOfContents><Country/><Container>VARIABLE</Container><Size>REGULAR</Size><Width/><Length/><Height/><Girth/></Package></IntlRateV2Request>

[result] => <?xml version="1.0" encoding="UTF-8"?>
<IntlRateV2Response><Package ID="0"><Error><Number>-2147219080</Number><Source>;IntlRateV2.UnpackIntlRateV2Node</Source><Description>Missing value for Country.</Description><HelpFile/><HelpContext/></Error></Package></IntlRateV2Response>
[__pid] => 2786
 )

Notice the empty Country tag in the request. I have dug through the code, and see where the country is supposed to be set via the  app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php file.
Of course, I have to override this file (not edit core magento directly) which i have done, but still I cannot get the Country tag to populate on the send.  I added this to the setRequest function:
    Mage::log("Destination Country: ");
    Mage::log($request->getDestCountryId());

    if ($request->getDestCountryId()) {
        $destCountry = $request->getDestCountryId();
    } else {
        $destCountry = self::USA_COUNTRY_ID;
    }

    $r->setDestCountryId($destCountry);

This outputs in my log "CW" which is the correct country code for the transaction, based on my DB settings. So what gives? Why doesnt the country code get passed to the API so I can get some pricing?
I figure this isnt a new issue, and that Im probably looking over something painfully obvious, so I was hoping someone out there can point me in the right direction as I am currently "stumped".
Thanks in advance!
Answer: The problem is that the USPS API takes full country names instead of ISO standard two letter country codes.
In this case your country code CW maps to "Curacao". These country names must be exact.
For a list of country code to USPS name mapping see:
https://docs.rocketship.it/php/1-0/usps-country-codes.html
For an official list of country names (no code mapping) see:
http://pe.usps.com/text/Imm/immctry.htm
Comment: Thanks for this - however - it doesnt solve the issue. The data is useful however.
Answer: So after some fairly exhaustive code tracing, and research I have figured out how to get it all working. It is a multi step process but it let me get Curacao, Bonaire, and Montenegro working with USPS. Im sure this same fix will apply to other countries - I just havent discovered any others yet that reflect the same issue yet.
Step 1
Find out the ISO2 and ISO3 country codes for the countries you want to add or enable to your USPS. I found what I needed on wikipedia.
Step 2
Edit your stores language file(s) in my case I only had one, which is en.xml, (located in "/lib/Zend/Locale/Data/en.xml"). Find the territories xml block:
<territories>

     <territory type="xxxx">Country</territory>

And add your territories (if they dont already exist - in my case Montenegro already did exist here).
  <territory type="CW">Curacao</territory>
  <territory type="BQ">Bonaire</territory>

Save this file.
Step 3
Login to your mysql database and insert the following rows into the directory_country table.
 insert into directory_country values('CW','CW','CUW');
 insert into directory_country values('BQ','BQ','BES');

Step 4
Edit the Usps Shipping Carrier class located in the core Mage libs. DO NOT MODIFY THE ACTUAL CORE - INSTEAD CREATE A LOCAL MODIFIED VERSION IN app/code/local. I will assume you know how to do this already.
In the file "app/code/local/Mage/Usa/Model/Shipping/Carrier/Usps.php" find the function called:
protected function _getCountryName($countryId)

Add the new countries to the array like this:
'BQ' => 'Bonaire',
'CW' => 'Curacao',

Mapping your ISO2 code to the Official USPS country name.
Save this file.
Step 5
Login to your stores admin. Disable compile mode, refresh your caches, and indexes. Go to Configuration > Web > General and enable your new countries. Save this change.
Step 6
Go to Config > Sales > Shipping Methods. Click on USPS, and Enable the new countries. If you have all countries already selected, set the drop down to selected countries, and then back to All Countries. This will force the selection of the newly added countries. Save this change.
Step 7
Re-enable and force a recompile of compile mode (if your using it), and take the new countries for a spin!


Chartrand Mathematical Proofs 3e Exercise 5.46

Question: I am self-studying this book, and am stuck on this question:
Prove that there exist four distinct positive integers such that each integer divides the sum of the remaining integers
This is what I have so far, but I am not sure where to go next:
Let a, b, c  and d be distinct positive integers. Without loss of generality, let $a<b<c<d$.
Then $$a\mid(b+c+d)$$ $$b\mid(a+c+d)$$ $$c\mid(a+b+d)$$ $$d\mid(a+b+c)$$
Since a,b,c and d are positive,
$$ap = b + c + d, p\in \mathbb Z^+ $$
$$bq = a + c + d, q\in \mathbb Z^+ $$
$$cr = a + b + d, r\in \mathbb Z^+ $$
$$ds = a + b + c, s\in \mathbb Z^+ $$
so
$$ ap + bq + cr + ds = 3(a+b+c+d)$$
One solution to this equation is when $p=q=r=s=3$
...and I'm stuck.
Am I even going in the right direction?
Answer: Consider the positive integers $1$, $2$, $3$, and $6$.
Comment: This is equivalent (by a simple transformation) to finding solutions to $1/a+1/b+1/c+1/d=1$ in distinct positive integers.  So for instance, using $a=2, b=3, c=7, d=42$ one gets the solution $(1,6,14,21)$.  Of course any integer multiple of a solution is also a solution, but there will only be finitely many such families (6, if I interpret WolframAlpha correctly).
Answer: Here is a systematic approach: note that $a \mid b+c+d$ is equivalent to $a \mid a+b+c+d$.  So we can rephrase the problem as finding $a,b,c,d$ that simultaneously divide $a+b+c+d$.  If we define $n=a+b+c+d$ for a putative solution then we can rephrase this yet again as "find an integer $n$ and four distinct divisors of $n$ which add up to $n$.
Now, any divisor of $n$ can be written as $n/A$ for some positive integer $A$.  So then we have yet another (equivalent, though less obviously so) form:
$$\frac{n}{A} + \frac{n}{B} + \frac{n}{C} + \frac{n}{D} = n,$$
whereupon the $n$ factors away and leaves the simple Egyptian fraction problem $1/A + 1/B + 1/C + 1/D = 1$.  (For the equivalence to be precise, we also need $n$ to be divisible by $A,B,C,D$ but this is easily done by taking LCMs).  This is a very well-studied problem, and it is not hard to see there are only finitely many solutions $(A,B,C,D)$ (see for instance, this similar question if you're unfamiliar with the finiteness argument).
In particular, assuming $A<B<C<D$ we have the six solutions
$$(A,B,C,D) \in \{(2,3,7,42), (2,3,8,24), (2,3,9,18), (2,3,10,15), (2,4,5,20), (2,4,6,12) \},$$
which give rise to the following primitive (in the sense of no common factor) solutions to the original equation:
$$(1,6,14,21),\\(1,3,8,12),\\(1,2,6,9),\\(2,3,10,15),\\(1,4,5,10),\\(1,2,3,6).$$


Is there some really powerful summation method?

Question: I know that Borel summation gives you a value if the coefficients are bounded by $n!C^n$.
 Is there a more powerful summation method (with nice properties comparable to Borel) that sums series with coefficients bounded by $(kn)!$ or even $(n^k)!$ ?
Comment: Have you tried Ramanujan summation?
Comment: I know of Ramanujan summation, but if i am not mistaken, it is not a regular summation method, and I would prefer some of those.
Comment: Mittag-Leffler summation is a veary easy generalization of Borel's but it has the nice property that sums series whose terms are of the first kind you mention.
Answer: In many situations "the most powerful possible generalization" of Borel's method is applicable.  It was introduced in (zillions of) Écalle's papers (for example, it is discussed in Chapter 3 of his "NATO" paper).
(Unfortunately, as Écalle's papers go, they all seem to be "popular expositions" of a [non-existent — or existing in a Platonic sense only] fundamental giga-mega-treatise.  This is not surprising: in its entirety, his work seems to be based on half-a-hundred of very deep non-trivial and intertwined ideas.  It is hard to imagine how to put the tangle of these ideas on paper.)
If all you are interested in is summation, Balser's books may be a better source.  He untangled a small chunk of these ideas: see the notion of "multisummability".  (I learned it from the book Formal Power Series and Linear Systems of Meromorphic Ordinary Differential Equations; I can see other people recommending From Divergent Power Series to Analytic Functions: Theory and Application of Multisummable Power Series as well.


Como inserir uma imagem do banco mysql numa datatables

Question: estou iniciando na programação PHP e baixei um código fonte para estar aprendendo, e este código apresenta um datatables, no qual pretendo inserir uma imagem na grid que encontra-se no banco de dados mysql. Meu codigo abaixo para quem puder orientar-me, fico grato a todos
$dados = array();

while( $row =mysqli_fetch_array($resultados) )
{

     $dado = array();

     $Foto = $row["Imagem"];

     $dado[] = "";

    $dado[] = $row["Id"];
    $dado[] = utf8_encode($row["Descricao"]);

                    $dados[] = $dado;
};

Não esta aparecendo a imagem na grid do datatables.
Comment: Uma obs.: vc está colocando a variável `$Foto` (supondo que seja o nome da imagem) fora do `src`.
Comment: Qual o formato da imagem? CLOB?
Comment: Estou usando na tabela o campo Imagem varchar(15), e as imagens possuem extensões .jpg
Comment: Estou guardando na variável foto da tabela apenas o nome da imagem. ex: prod1.jpg
Answer: Para adicionar a imagem da base de dados basta apenas gravar o nome, por exemplo "imagem.jpg", para receber a imagem e como todos os outros campo, a única diferença é na chamada que teras de introduzir o caminho onde vai esta guardada a foto.
";


How can I find out the machine names of user variables?

Question: I'm creating a custom user profile page and I know how to print certain items attached to the user like
$user_profile['user_picture']

but I don't know the names of any of the other fields. Is there a way that I can view a list of user profile field machine names?
Comment: [devel](https://www.drupal.org/project/devel), [`var_dump`](http://php.net/manual/en/function.var-dump.php) or simply [read them](https://www.drupal.org/files/Screen%20Shot%202013-02-18%20at%204.36.15%20PM.png) from configuration page...
Answer: All of the user variables are located in configuration->People->Account Settings->Manage Fields. So simply look at them over there.


Rotas acessíveis apenas para usuários logados no Laravel?

Question: Alguém pode me dar uma dica de como criar rotas que podem ser acessadas apenas por usuários que estão autenticados, utilizando o Laravel?
Por exemplo, as rotas que sejam referentes a compartilhar, editar, excluir e ver publicações sejam acessíveis apenas a usuários que estão logados.
Comment: Leitura: https://pt.stackoverflow.com/questions/119043/como-redirecionar-o-usu%C3%A1rio-autenticado-para-uma-p%C3%A1gina-espec%C3%ADfica
Comment: Leitura: https://pt.stackoverflow.com/questions/154386/routes-laravel-5-3/154413#154413
Answer: Para isso, você utilizará Middlewares.
Middlewares

Middleware provê um mecanismo para filtragem de requisições HTTP na
  sua aplicação. Por exemplo, o Laravel inclui um middleware que
  verifica se o usuário da sua aplicação está autenticado. Se o usuário
  não estiver autenticado, o middleware will redirecionará o usuário
  para a página de login. Entretanto, se o usuário estiver autenticado,
  o middleware permitirá a requisição seguir adiante na sua aplicação.

Auth Middleware
O Laravel já vem com algums middlewares pra você utilizar, e um deles é o auth. Você pode aplicar este middleware de várias formas.
Rota Específica
Atribuindo o middleware a rota via método fluente.
Route::get('admin/posts/create', function () {
    //
})->middleware('auth');

Grupo de Rotas
Atribuindo o middleware a um grupo de rotas.
Route::middleware(['auth'])->group(function () {
    Route::get('admin/posts/create', function () {});
    Route::get('admin/user/profile', function () {});
});

Via Controller
Você pode atribuir direto no controller também.
class PostsController extends Controller
{
    public function __construct()
    {
        // Nesse caso o middleware auth será aplicado a todos os métodos
        $this->middleware('auth');

        // mas, você pode fazer uso dos métodos fluentes: only e except
        // ex.: $this->middleware('auth')->only(['create', 'store']);
        // ex.: $this->middleware('auth')->except('index');
    }
}

Answer: Outra opção é agrupar as rotas que você quer proteger, dessa forma:
Route::group(['middleware' => ['auth']], function () {
     Route::get('sua_url', function());
}

Answer: Para isso você pode usar os Middleware do Laravel, que são basicamente funções executadas antes ou depois da rota que podem afetar a execução de uma controller / action.
Um exemplo de Middleware:
<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
    public function handle($request, Closure $next)
    {
        // Perform action

        return $next($request);
    }
}

Um exemplo de uma rota com um Middleware:
Route::get('admin/profile', function () {
    // Seu código
})->middleware('auth');

Answer: Você pode usar os  Middleware do laravel, conforme as respostas anteriores e "reforçar" em seu código HTML, como por exemplo, somente o usuário indicado como adm acesse.
Outra dica importante, é sempre bom vc prevenir que alguém acesse o histórico da página após o usuário deslogar/sair.
Com o Middleware também é possível fazer isso:
Um exemplo:
namespace App\Http\Middleware;

use Closure;

class PreventBackHistory
{

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $headers = [
        'Cache-Control' => 'nocache, no-store, max-age=0, must-revalidate',
        'Pragma','no-cache',
        'Expires','Fri, 01 Jan 1990 00:00:00 GMT',
        ];

        foreach($headers as $key => $value) {
            $response->headers->set($key, $value);
        }

        return $response;
    }
}


Facebook share button does not show up

Question: I want to add a very basic facebook share button as it is suggested here :
https://developers.facebook.com/docs/plugins/share-button?locale=fr_FR
The problem is the button does not simply show up, no javascript or network errors.
Can anyone say me what i'm doing wrong ?
<!DOCTYPE html>

<meta charset="utf-8"/>
<title>titre</title>

Thanks in advance for your help
Answer: The marked answer is silly. The javascript included in the code is what loads the SDK javascript.
The problem I faced was that I was looking at the html page without going through a web server. In other words, I was using the file:// protocol and the facebook SDK doesn't work when run under that protocol. Although it does pull a lot of stuff in and affect the DOM, the Facebook share button does not show up.
Setting it up to run through a true web server on just localhost (in my case, IIS) and lo-and-behold the button shows up. Hopefully that will help some folks.
Answer: For me it was the size attribute that prevented the button from showing.
Just add
data-size="large"

to the div tag for the button and it shows.
BTW, based on the documentation, there is no medium size avaialable.
Answer: The first line tells you to add the sdk javascript which you havent done. Do the following and you should be good to go:

Comment: This script tag is not present in the code example, or anywhere in the FB SDK documentation. That's the reason you couldn't provide the location in your example. Web devs shouldn't have to guess or search to put a blimming button on their web page, just because the code examples are incomplete. https://developers.facebook.com/docs/plugins/share-button#example
Comment: This is a silly answer... the facebook script is a script loader itself. It loads the javascript SDK it needs by inserting a script tag into the document.
Comment: i will do it in 4 minutes ;)
Answer: Sometimes these problems with seeing Facebook buttons is because of browser extensions like Disconnect that block scripts communicating with Facebook etc, so whitelist your site if that's the case.
Answer: I had to add "http:" to url in addition to changing "sdk.js" to "all.js" as suggested above, i.e:
Instead of:
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1";
Use:
js.src = "http://connect.facebook.net/en_US/all.js#xfbml=1";
Good Luck
Answer: STEP 1: Get a Facebook App ID for the domain the Share Button will live on.
STEP 2: Add the Facebook JavaScript SDK to your Web page.
STEP 3: Add code to load the jQuery library on your Web page
STEP 4: Add some jQuery and fb.ui code to display the Share dialog box

Facebook share button does not show up


Rename images while uploading and put in specific folder

Question: I am using drupal 7.
I have created an Advertisement content type. This contains a field where end user can upload images of their Brands.
I want to rename the images which are uploaded by the field of content type and put in specific folder named user id of the user. So uploaded file location would look like it:
/sites/default/files/images/user_id/
Answer: File (Field) Paths let you set file name and file path for file field:


How can I add the close icon in the top right corner of the Material UI Dialog Header?

Question: I Want to add the close icon in the header section at the top right corner.
I am using the Material UI Dialog. Everything is working fine, but I want the close button on top section, as shown in the image:
Answer: I know this was asked pre Material UI V1 but the accepted answer works for Material UI version 0 (or whatever they called it).
For people wanting help with version 1 the MUI guys have exposed a <DialogTitle /> component that accepts a disableTypography so you can customize your dialog.
EG
<Dialog open={this.state.show} onClose={this.onClose}>
    <DialogTitle disableTypography className={styles.dialogTitle}>

Dialog...

        <IconButton onClick={this.onClose}>
            <CloseIcon />
        </IconButton>
    </DialogTitle>
    <DialogContent>
        Dialog Content
    </DialogContent>
</Dialog>

I just use flex with space between for the h2 and the Icon
.dialogTitle {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

Hope that helps somebody out. :-)
Answer: For anyone looking for a solution using Material UI V4.
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';

 <DialogTitle id="id">
         <Box display="flex" alignItems="center">
                <Box flexGrow={1} >{title}</Box>
                <Box>
                    <IconButton onClick={onClose}>
                          <CloseIcon />
                    </IconButton>
                </Box>
          </Box>
  </DialogTitle>

Answer: Put the image icon in the title, and use the css to position it correctly, Try this:
Apply this css on close image:
let closeImg = {cursor:'pointer', float:'right', marginTop: '5px', width: '20px'};

<Dialog
    modal={false}
    open={true}
    title={

                ABC

        }
>
    Hello
</Dialog>

Check the working fiddle: https://jsfiddle.net/ve0qbgLr/
Comment: Thanks It works for me.. I have used following.  title={{this.props.title} }
Comment: it will also work, you can put any element, glad to help you :)
Comment: @ofir_aghai glad, it helped you :)
Answer: I think you can also use Grid (see tutorial here).
Something like
import Grid from '@material-ui/core/Grid';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';

<DialogTitle>
  <Grid container direction="row" justify="space-between" alignItems="center">
    {myTitle}
    <IconButton aria-label="close" onClick={closeDialog}>
      <CloseIcon />
    </IconButton>
  </Grid>
</DialogTitle>

Answer: MUI 5 solution with no tricks or absolute positioning (only flex):
<DialogTitle sx={{ display: 'flex', alignItems: 'center' }}>
    Dialog Title
    <IconButton sx={{ ml: 'auto' }}>
        <CloseIcon />
    </IconButton>
</DialogTitle>

Answer: I know this is an old question but I found it because I had the same issue. So for people like me Material-UI's Dialog-Demo lists an example with a close button:
import React from 'react';
import { createStyles, Theme, withStyles, WithStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import MuiDialogTitle from '@material-ui/core/DialogTitle';
import MuiDialogContent from '@material-ui/core/DialogContent';
import MuiDialogActions from '@material-ui/core/DialogActions';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';
import Typography from '@material-ui/core/Typography';

const styles = (theme: Theme) =>
  createStyles({
    root: {
      margin: 0,
      padding: theme.spacing(2),
    },
    closeButton: {
      position: 'absolute',
      right: theme.spacing(1),
      top: theme.spacing(1),
      color: theme.palette.grey[500],
    },
  });

export interface DialogTitleProps extends WithStyles<typeof styles> {
  id: string;
  children: React.ReactNode;
  onClose: () => void;
}

const DialogTitle = withStyles(styles)((props: DialogTitleProps) => {
  const { children, classes, onClose, ...other } = props;
  return (
    <MuiDialogTitle disableTypography className={classes.root} {...other}>
      <Typography variant="h6">{children}</Typography>
      {onClose ? (
        <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
          <CloseIcon />
        </IconButton>
      ) : null}
    </MuiDialogTitle>
  );
});

const DialogContent = withStyles((theme: Theme) => ({
  root: {
    padding: theme.spacing(2),
  },
}))(MuiDialogContent);

const DialogActions = withStyles((theme: Theme) => ({
  root: {
    margin: 0,
    padding: theme.spacing(1),
  },
}))(MuiDialogActions);

export default function CustomizedDialogs() {
  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };
  const handleClose = () => {
    setOpen(false);
  };

  return (

      <Button variant="outlined" color="primary" onClick={handleClickOpen}>
        Open dialog
      </Button>
      <Dialog onClose={handleClose} aria-labelledby="customized-dialog-title" open={open}>
        <DialogTitle id="customized-dialog-title" onClose={handleClose}>
          Modal title
        </DialogTitle>
        <DialogContent dividers>
          <Typography gutterBottom>
            Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis
            in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
          </Typography>
          <Typography gutterBottom>
            Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis
            lacus vel augue laoreet rutrum faucibus dolor auctor.
          </Typography>
          <Typography gutterBottom>
            Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel
            scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus
            auctor fringilla.
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button autoFocus onClick={handleClose} color="primary">
            Save changes
          </Button>
        </DialogActions>
      </Dialog>

  );
}

Answer: From the MUI Docs: Customized Dialog
Use the sx property.
// import mui components as needed

...

return (
    <Dialog
        className='modal-dialog'
        open={isModalOpen}
        onClose={onClose}
    >
        <DialogTitle sx={{m: 0, p: 2}}>
            <IconButton
                aria-label="close"
                onClick={onClose}
                sx={{
                    position: 'absolute',
                    right: 8,
                    top: 8,
                    color: (theme) => theme.palette.grey[500],
                }}
            >
                <CloseIcon/>
            </IconButton>
        </DialogTitle>
        <DialogContent>
            <DialogContentText>
                Your dialog content here
            </DialogContentText>
        </DialogContent>
    </Dialog>
);

Answer: Here is the most minimalist code I know that does that with only inline css.
import React, { useState } from "react";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import IconButton from "@mui/material/IconButton";
import CloseIcon from "@mui/icons-material/Close";

function MyDialog() {
  const [show, setShow] = useState(true);

  return (
    <Dialog open={show}>
      <DialogContent style={{ position: "relative" }}>
        <IconButton
          style={{ position: "absolute", top: "0", right: "0" }}
          onClick={() => setShow(false)}
        >
          <CloseIcon />
        </IconButton>
      </DialogContent>
    </Dialog>
  );
}

I'm not using and DialogTitle in this example but you could do the same trick by setting style={{ position: "relative" }} for the DialogTitle and move the IconButton in it.
I usually control showing/hiding the dialog via the parent component and I pass the setter in props.
Answer: This is the way I am doing it with MUI 5, using the Grid component.
import React from "react";
import Dialog from "@mui/material/Dialog";
import { DialogContent, DialogTitle, Grid, IconButton } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";

<Dialog
  fullWidth
  maxWidth="sm"
  onClose={handleClose}
  PaperProps={{
    sx: {
      position: "fixed",
      top: 10,
      left: 0,
      right: 0,
      m: "0 auto",
    },
  }}
>
  <DialogTitle>
    <Grid container>
      <Grid item>Title</Grid>

      <Grid ml="auto" item>
        <IconButton aria-label="close" onClick={handleClose}>
          <CloseIcon />
        </IconButton>
      </Grid>
    </Grid>
  </DialogTitle>

  <DialogContent>

Content

  </DialogContent>
</Dialog>

The dialog is positioned on the top, centered horizontally, and a small width.
Answer: My solution:
   <IconButton
            open={open}
            onClose={handleClose}
            aria-label="Close"
            onClick={handleClose}
            sx={{
              position: 'absolute',
              right: 6,
              top: 6,
              color: 'black',
              fontSize: 34
            }}
          >
            <CloseIcon />
    </IconButton>

Answer: This is what we made, extending the default close reasons :
import { FC, useEffect, useState } from 'react'
import MUIDialog, { DialogProps as MUIDialogProps } from '@mui/material/Dialog'
import styled from 'styled-components'
import { DialogTitle } from '@mui/material'

export type DialogProps = MUIDialogProps & {
  onClose?: (event: {}, reason: 'backdropClick' | 'escapeKeyDown' | 'closeIcon') => void
}

const StyledMaterialDialog = styled(MUIDialog)`
  &.MuiDialog-root {
  }
`

const Dialog: FC<DialogProps> = ({ children, ...props }) => {
  const initialValue = !!props.open

  const [open, setOpen] = useState(initialValue)
  const forceClose = () => {
    setOpen(false)
    props.onClose && props.onClose({}, 'closeIcon')
  }

  useEffect(() => {
    setOpen(!!props.open)
  }, [props.open])

  return (

  )
}
export default Dialog

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: I don't think inserting the IconButton inside the DialogTitle is right, because it will render to a button inside an h2 tag(!).
I found a very easy solution:
        <Dialog
            dir={dir}
            open={shouldOpen}
            onClose={reset}
        >
            <IconButton sx={{ position: "absolute" }}> {/* <--------- */}
                <CloseIcon />
            </IconButton>

            <DialogTitle>
                <Typography>
                    {i18n.title}
                </Typography>
            </DialogTitle>
        </Dialog>

Just insert it directly under the Dialog and add a position: "absolute" css rule
Result: (Attention the location of the X)


A web server to store files with unlimited bandwith

Question: I've recently started an android app (using Unity) and users will need to upload a (~200kb) file somewhere, and have another user download it later. I was planning to use Dropbox as they have a 20gb daily bandwith allowance, but I can't find a way to upload files to my dropbox account through code. Is there a way to upload to a dropbox account using C#?
I know it's possible using PHP, and I could have the user upload to a web server and then send it to a public dropbox folder. Though all the web servers I have found do not allow file storage/sending like that.
So also, what web servers do popular apps use to store all their data and have enough bandwith? If my app did become popular, I can't find a web server to handle thousands or more of concurrent users downloading and uploading.
Comment: search google for 'dropbox api' and you will get the gory details of the web services. AFAIK web services can be implemented with Csharp.
Comment: You will need to have some network storage. That is accessible to preferably only server, or if that is not possible the client. And upload to there. drobox is possible, but not good practice.
Comment: Thanks, I thought dropbox wouldn't be good practice, but I thought it would be a good way to start as I don't want to pay for storage when there might only be 10 app users.
Answer: Have a look at Dropbox Rest API
and Unity's WWW-Class.
You should be able to consume the Dropboxapi via Unity.


show that $\lim_{r\to\infty} \int_0^2 g(x) \exp^{ikrx} dx = 0$

Question: let g(x) be a sufficiently smooth function and k,r $\in \rm I\!R$
via partial integration ($\int uv' = [uv] - \int u'v$), I arrive at
$$I:\lim_{r\to\infty}\left( \left(\frac{g(2)}{ikr}\exp^{2ikr}-\frac{g(0)}{ikr}\right)-\left[  \int_0^2 \frac{1}{(ikr)}g'(x) \exp^{ikrx} dx\right]\right)$$
When I then choose g'(x) to be v' and the exponential term to be u, I get
$$II:\lim_{r\to\infty}\left( \left(\frac{g(2)}{irk}\exp^{2ikr}-\frac{g(0)}{ikr}\right)-\left[ \left[g(x) \frac{1}{ikr} \exp^{ikrx} \right]^2_0 -\int_0^2 g(x) \exp^{ikrx} dx\right]\right)$$
The terms in front of the integral cancel each other and I arrive back at the start. When I choose u & v' the other way arround I'll get
$$III:\lim_{r\to\infty}\left( \left[g(x) \frac{1}{ikr} \exp^{ikrx} \right]^2_0-\left[ \left[g'(x) \frac{1}{(ikr)^2} \exp^{ikrx} \right]^2_0 -\int_0^2 g''(x) \frac{1}{(ikr)^2} \exp^{ikrx} dx\right]\right)$$
I don't see how this approach could bring me further, since the integral didn't simplify. I haven't used the limit $\lim_{r\to\infty}$ yet, so I guess this should be rather important. But on the other hand side, I also don't see how the limit would help, since the exponential function will always go to infinity faster than the fraction.
I missed that the exponential function is oscilating, so it will go to zero for r going to infinity. This clears removes the terms in front of the integral in III. For the integral $\int_0^2 g''(x) \frac{1}{(ikr)^2} \exp^{ikrx} dx$, can I argue that it will also go to zero, since the integral of $exp^{ikr}$ will always be oscilating an the prefactor $\frac{1}{(ikr)}$ overpowers the rest?
Comment: @t.rathjen $e^{ikrx}$ is a unit complex number so it doesn't go to infinity...you can write it as: $\cos(krx)+i\sin(krx)$, hence it is oscillating but it can't go to infinity
Comment: @t.rathjen $g(x)$ is a sufficiently smooth function, so the integral is bounded and the factor ${1\over ikr}$ goes to zero...your thoughts are right
Comment: $e^{ikrx}$ is a phase factor so ${e^{ikrx}\over ikr}\to 0$ when $r\to\infty$
Comment: What is $k?$ It just appears, with no explanation. Explain please.
Comment: @zhw. I editet the question. k is a real number.
Comment: whart if $k=0?$
Answer: Let $f_{g,k}(r):=\int_0^2g(x)e^{ikrx}dx$. Then if I understand the question right, we want to show that $f_{g,k}(r)\to_{r\to\infty} 0$ for all $k\in\Bbb R\setminus \{0\}$ (not true for $k=0$!) and for all sufficiently smooth $g:[0,2]\to \Bbb C$.

First, let $g:[0,2]\to\Bbb R$ and $k>0$.
Note that
$$f_{g,k}(r) = \int_0^2g(x)\cos(krx)dx+i\int_0^2g(x)\sin(krx)dx\text.$$
Since a complex series converges if and only if its real and imaginary parts converge, we need to show that $\Re f_{g,k}(r)\to_{r\to\infty} 0$ and $\Im f_{g,k}(r)\to_{r\to\infty} 0$.
We show $\Im f_{g,k}(r)\to_{r\to\infty} 0$. The same argument works for $\Re f_{g,k}$.
Let $r>\frac{\pi}k$. Then we split the integral to parts according to the periodicity of the $\sin$ function. The idea being that the sum is "almost $0$" because each part is. Formally:
$$\Im f_{g,k}(r) = \int_0^2g(x)\sin(krx)dx=\\
\int_0^\frac{2\pi}{kr}g(x)\sin(krx)dx+\int_\frac{2\pi}{kr}^\frac{4\pi}{kr}g(x)\sin(krx)dx+\cdots+\int_\frac{2N\pi}{kr}^2g(x)\sin(krx)dx=\\
\sum_{n=1}^N\underbrace{\int_\frac{(2n-2)\pi}{kr}^\frac{2n\pi}{kr}g(x)\sin(krx)dx}_{(*)}+\underbrace{\int_\frac{2N\pi}{kr}^2g(x)\sin(krx)dx}_{(**)}$$
where $N\in\Bbb N$ is naturally selected such that $\frac{2N\pi}{kr}\le 2<\frac{(2N+2)\pi}{kr}$ (namely, $N=\left\lfloor\frac{kr}\pi\right\rfloor$).
Then,
$$|(**)|=\left|\int_\frac{2N\pi}{kr}^2g(x)\sin(krx)dx\right|\le\int_\frac{2N\pi}{kr}^2\left|g(x)\sin(krx)\right|dx\le\int_\frac{2N\pi}{kr}^2\left|g(x)\right|dx\le\\
\left(2-\frac{2N\pi}{kr}\right)\max|g|<\left(\frac{(2N+2)\pi}{kr}-\frac{2N\pi}{kr}\right)\max|g|=2\max|g|\frac\pi{kr}\text.$$
Since $g'$ is continuous on $[0,2]$, there exists $M:=\max g'([0,2])$. So,
$$|(*)|=\left|\int_\frac{(2n-2)\pi}{kr}^\frac{(2n-1)\pi}{kr}g(x)\sin(krx)dx+
\int_\frac{(2n-1)\pi}{kr}^\frac{2n\pi}{kr}g(x)\sin(krx)dx\right| \underset{x=y+\pi/kr}{=}\\
\left|\int_\frac{(2n-2)\pi}{kr}^\frac{(2n-1)\pi}{kr}g(x)\sin(krx)dx+\int_\frac{(2n-2)\pi}{kr}^\frac{(2n-1)\pi}{kr}g\left(y+\frac\pi{kr}\right)\underbrace{\sin(kry+\pi)}_{=-\sin(kry)}dy\right|=\\
\left|\int_\frac{(2n-2)\pi}{kr}^\frac{(2n-1)\pi}{kr}\sin(krx)\cdot\left(g(x)-g\left(x+\frac\pi{kr}\right)\right)dx\right|\le\int_\frac{(2n-2)\pi}{kr}^\frac{(2n-1)\pi}{kr}\sin(krx)\left|g(x)-g\left(x+\frac\pi{kr}\right)\right|dx\le\\
\int_\frac{(2n-2)\pi}{kr}^\frac{(2n-1)\pi}{kr}\sin(krx)\cdot|M|\cdot\left|x-\left(x+\frac\pi{kr}\right)\right|dx=2|M|\frac\pi{k^2r^2}=\frac{2N\pi}{kr}\cdot\frac{|M|}{Nkr}\le2\frac{|M|}{Nkr}\text,$$ which yields
$$\left|\sum_{n=1}^N(*)\right|\le\sum_{n=1}^N|(*)|\le\sum_{n=1}^N2\frac{|M|}{Nkr}=2\frac{|M|}{kr}\text.$$
Putting it all together,
$$\left|\Im f_{g,k}(r)\right|=\left|\sum_{n=1}^N(*)+(**)\right|\le\left|\sum_{n=1}^N(*)\right|+\left|(**)\right|<2\frac{|M|}{kr}+2\max|g|\frac\pi{kr}\to_{r\to\infty}0\text.$$

Now, let $k<0$. Then $$f_{g,k}(r) = \int_0^2g(x)\cos(krx)dx+i\int_0^2g(x)\sin(krx)dx=\\
\int_0^2g(x)\cos(-krx)dx-i\int_0^2g(x)\sin(-krx)dx\to_{r\to\infty} 0$$
as shown.

Finally, let $g:[0,2]\to\Bbb C$. Then $$f_{g,k}(r)=\int_0^2g(x)e^{ikrx}dx=\int_0^2\Re g(x)e^{ikrx}dx+i\int_0^2\Im g(x)e^{ikrx}dx\to_{r\to\infty}0+i\cdot 0=0$$
applying the above result to $\Re g$ and $\Im g$, which are real-valued.


A simple estimation

Question: Let's say $X$ is a normed linear space, and $X^*$ is its dual space.
One can define the norm in $X$ in such a way
$$
\|x\| = \sup\{|\phi(x)|:\phi \in X^*,\|\phi\|\le 1\}.
$$
The direction
$$
\|x\| \ge \sup\{|\phi(x)|:\phi \in X^*,\|\phi\|\le 1\}
$$
is obvious.
How about the other direction?
Sol:
apply Hahn-Banach thm, there exists a functional $\psi:x\mapsto \|x\|$ with $\|\psi\| = 1$.
$$
\psi(x) = \|x\|\le \sup\{|\phi(x)|:\phi \in X^*,\|\phi\|\le 1\}.
$$
Hence equality is achieved.
Answer: Hint: use the Hahn-Banach theorem.

A simple estimation


Estimating user ability (success or fail) using maximum likelihood and Item response theory

Question: I am trying to estimate the user ability (success or fail) using item response theory. So, I am re-implementing an algorithm from this paper but I can not understand the following line:

In the equation, a (discrimination parameter (slope)), b (difficulty parameter), and c (guessing parameter) are estimated using item response theory. i refers to the user, j problem and u refers to the user response.
My question is, should I calculate the Maximum likelihood for each (u,a,b,c) separately, and then calculate the average, or Maximum likelihood need to be calculated for all (u,a,b,c) together.
Thanks
Comment: Please provide reference for the line that you quote.
Answer: For simplicity, let's assume a very simple model
$$ X \sim \mathcal{N}(\mu, \sigma^2) $$
and you are looking for
$$ \DeclareMathOperator*{\argmax}{arg\,max}
\hat \theta  = \argmax_{\mu,\sigma^2} \; \prod_{i=1}^n \mathcal{N}(x_i; \mu, \sigma^2)
$$
The function has two parameters $\theta = (\mu,\sigma^2)$, how would you imagine maximizing it with one of the parameters being undefined? How would you evaluate normal density with undefined mean, or undefined variance?
There are algorithms such as Expectation-Maximization algorithm (in fact, often used in IRT models) that let you estimate parameters by leaving some of them unknown by filling them with "temporary" values, but still, they maximize over all of the parameters.
See the Maximum Likelihood Estimation (MLE) in layman terms tread to learn more about maximum likelihood estimation.
Comment: Thanks, @Tim for your reply. Now, I got the idea better. Let's check if I understand it well, μ: mean, σ2: variance for the normal distribution and x_{i} refers to the user response to the item `i`. Here, you imagine a normal distribution which in my case is a Bernoulli distribution. My understanding from your answer is to estimate the `θ` for each `(u,a,b,c)` by assuming a type of distribution, and then estimate the `argmax` of  `θ`. Is it correct?
Comment: @user3233712 no. The distribution is the likelihood function - it is distribution assumed for your *data*. u,a,b,c are parameters of your model and you maximise likelihood by finding such combination of them that leads to greatest likelihood.