Ajuda para inserir dados na tabela

Question: Tenho uma tabela no MySQL com o nome usuários com os seguintes itens: convite,quantidade_de_convites. Quero que ao adicionar um convite, atualizar a quantidade como faço isso?.
Answer: Se você quer atualizar a tabela de usuários após inserir um registro na tabela convite,  você pode utilizar uma TRIGGER. Aqui tem um exemplo:
DELIMITER $$
CREATE TRIGGER update_convite AFTER INSERT ON convite
FOR EACH ROW BEGIN
UPDATE usuarios SET quantidade_de_convites = quantidade_de_convites + 1 WHERE USUARIO_ID = NEW.USUARIO_iD;
END $$
DELIMITER ;

No caso deste exemplo, a tabela de usuário receberia um campo chamado usuario_id, ele seria a chave para atualizar a tabela de usuários
Aqui tem um tutorial explicando como funcionam triggers
https://www.devmedia.com.br/mysql-basico-triggers/37462
Comment: preciso fazer algo antes de criar a trigger? aqui ta dando erro de tabela

Ajuda para inserir dados na tabela


Page redirect with condition

Question: I want to redirect the users to a particular page when they view a certain page when there are some conditions. The condition is that the user has uploaded a node, for example an article.
Say there are two pages, Page A and Page B.
Page A Link <-- if the user has not uploaded a node, clicking on this link will take him to Page B
I have installed the node limit module which allows the user to upload only one content.
Comment: can you provide more info? clarify how he/she uploads a content?...
Comment: @xurshid29 I made the edits. The user uploads the content type normally.
Comment: you mean user creates a node? or uploads a file?
Comment: Yes..sorry my drupal terms are not exact
Comment: @xurshid29 I mean creates a node.
Comment: @nabeela ok.. Let me try to guess what you want to acheive, So, I (authenticated user) want to create a content(node. I haven't create them yet). Created it (article type).. want to create another content(also article type), but at this time you redirect me to the `Page B`.. Am I right?
Comment: Yes. Thats correct.
Answer: It seems you can achieve that using the Rules module.

The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.
Comment: I tried using the Rules module. But I'm not exactly sure how to go about it..
Comment: How do I put the condition that user has uploaded one content
Comment: not content.. I mean node*
Comment: Sorry about that @Krishna

Page redirect with condition


All positive continuous functions $g$ on $[0,\infty)$ s.t. $\frac{1}{2}\int_0^x [g(t)]^2 dt = \frac{1}{x}\left(\int_0^x g(t)dt\right)^2$.

Question: Repeating the title, the question is as followed:

Find all positive continuous functions $g$ on $[0,\infty)$ such that $\frac{1}{2}\int_0^x [g(t)]^2\text{ d}t = \frac{1}{x}\left(\int_0^x g(t)\text{ d}t\right)^2$ for $x > 0$.

Clearly $g(t) = 0$ is a solution, but it is not positive so it is not what the question is asking for. One can check that $g(t)$ can never be a positive constant function.
I don't really know how to proceed with this question. I conjectured that $g(0) = 0$ necessarily, which implies that no such positive function exists but to no avail.
Any help is appreciated.
Answer: Let $g:[0,\infty)\to\mathbb{R}$ be a continuous function such that
$$\dfrac{x}2\,\int_0^x\,\big(g(t)\big)^2\,\text{d}t=\left(\int_0^x\,g(t)\,\text{d}t\right)^2\tag{1}$$
for every $x\geq 0$.  Differentiating both sides with respect to $x$ yields
$$\frac{1}{2}\,\int_0^x\,\big(g(t)\big)^2\,\text{d}t+\frac{1}{2}\,x\,\big(g(x)\big)^2=2\,g(x)\,\int_0^x\,g(t)\,\text{d}t\,.\tag{2}$$
Write $G(x):=\displaystyle\int_0^x\,g(t)\,\text{d}t$ for all $x\geq 0$ (so that $G'=g$).  Then, (1) and (2) imply that
$$\big(G(x)\big)^2+\frac{1}{2}\,x^2\,\big(g(x)\big)^2=2\,x\,g(x)\,G(x)$$
for every $x\geq 0$.  Thus,
$$\big(G(x)-x\,g(x)\big)^2=\frac{1}{2}\,x^2\,\big(g(x)\big)^2$$
for all $x\geq 0$.  By continuity of $G$ and $g$, we conclude that there exists $s\in\{-1,+1\}$ such that $G(x)=\left(1+\frac{s}{\sqrt{2}}\right)\,x\,g(x)$ for each $x\geq 0$.  That is, $$\frac{\text{d}}{\text{d}x}\,\left(\frac{1}{x^{2-\sqrt{2}\,s}}\,G(x)\right)=0\text{ for each }x>0\,.$$
That is, for some constant $k$, $G(x)=k\,x^{2-\sqrt{2}\,s}$ for all $x>0$.  By continuity, $G(x)=k\,x^{2-\sqrt{2}\,s}$ for every $x\geq 0$.  Hence, $$g(x)=G'(x)=K\,x^{1-\sqrt{2}\,s}$$ for all $x\geq 0$, where $K:=\left(2-\sqrt{2}\,s\right)\,k$.  However, $g(x)$ must be defined at $x=0$.  This implies $s=-1$.  Thus,
$$g(x)=K\,x^{1+\sqrt{2}}\text{ for all }x\geq 0\,.$$
We can check that $g$ satisfies the requirement:
$$\int_0^x\,g(t)\,\text{d}t=\frac{K\,x^{2+\sqrt{2}}}{2+\sqrt{2}}$$
and
$$\int_0^x\,\big(g(t)\big)^2\,\text{d}t=\frac{K^2\,x^{3+2\sqrt{2}}}{3+2\sqrt{2}}$$
for all $x\geq 0$.  Since
$$\left(\frac{1}{2+\sqrt{2}}\right)^2=\frac{1}{2}\left(\frac{1}{3+2\sqrt{2}}\right)\,,$$
every such $g$ satisfies the equation (1).
In general, for $\alpha\in\mathbb{R}$, there exists a nonzero continuous function $g:[0,\infty)\to\mathbb{R}$ such that
$$\alpha\,x\,\int_0^x\,\big(g(t)\big)^2\,\text{d}x=\left(\int_0^x\,g(t)\,\text{d}t\right)^2$$
for all $x\geq 0$ if and only if $0<\alpha\leq 1$.  For $\alpha\in (0,1]$, all solutions are of the form
$$g(x)=K\,x^{\frac{1-\alpha+\sqrt{1-\alpha}}{\alpha}}$$
for all $x\geq 0$, where $K$ is a constant.


Python: Pip command is not recognized

Question: Here is a screenshot I took.

When I try to use pip in command prompt I get the following error message:
pip is not recognized as an internal or external command, operable program or batch file.
I already checked this thread: How do I install pip on Windows?
All I could find there was I had to add "C:\PythonX\Scripts" to my classpath, where X stands for python version.
As you can see on my screenshot I already have this path. I already tried restarting the computer but that didn't work, o.O. The screenshot also shows my C:\Python27\Scripts folder.
Does anyone know what I am doing wrong?
Comment: Did you open a new DOS prompt? Also print what `echo %PATH%` says for you.
Comment: @SenthilKumaran: OP said they restarted the whole computer
Comment: The variable should be `PATH` (not `Path`), and does not have any spaces between the separators (the `;`).
Comment: Does this answer your question? ['pip' is not recognized as an internal or external command](https://stackoverflow.com/questions/23708898/pip-is-not-recognized-as-an-internal-or-external-command)
Comment: @jdi - sorry that escaped me.
Comment: echo %Path%
Returns  "C:\Python27\Scripts;" in the end.
Comment: Lol, it was the space. I feel so stupid now.
Comment: @BurhanKhalid: The space is problem, but the case doesn't matter
Comment: Is `easy_install available` for you? Also, what is the error that is being thrown?
Comment: @user1303142 You should answer the question, and mark your answer as accepted and close the question :)
Comment: @SenthilKumaran

The problem was the space. After I removed it pip is recognized.
Comment: @user1303142 - glad that it worked for you!
Comment: Refer: [add pip to PATH](https://stackoverflow.com/a/46097258/2142994)
Comment: This question should have been closed as a typo at the time; redirecting it as a duplicate now.
Answer: There is a space before the last path entry, right after the previous semicolon, that is causing the problem.
Answer: Go to C:\Python27\Scripts
Now select the url bar and replace whole content with cmd
This way you directly reach to the directory where pip is available in command prompt
Now type  pip install Django==1.8.5
it will download and install Djanog
Answer: I had the same exact problem, but typing your command in the "Scripts" folder fixed it!
In other words:

Open command prompt (right click windows start menu and click on "Command Prompt (Admin)"
Use "cd" command to change directory to where python is installed, but go to your scripts folder (for me, this is cd C:\Program Files\PythonXX\Scripts where the XX is the version number of Python)
Once in "Scripts" folder, type pip install cython and press enter
Answer: what I did is for example in the command prompt or cmd in windows:
py -m pip install pygame

Answer: It started working for me when I added ; in PATHEXT  after .PY
Answer: 1) browse here - C:\Python27\Scripts
2) open the cmd window/terminal (shift+'right click')
3) type pip install django
Comment: What's the difference here with arvind kumar's answer?
Comment: 2nd step, a bit easier.
Answer: 1) open cmd as an administrator
2) enter: cd c:\python27\scripts (go to python and shift right click on folder. Than copy to path)
3) press enter
4) pip install
Answer:
Add "your python path"\Scripts to PATH variable. See How to set path variable
Don't forget to restart the command prompt.

Now pip will work in any path.
Answer: Go to your Python Script Path, copy the path, go to CMD and type cd "paste the path you copied".
type pip --version
You will see the version of pip your system is running.
Answer:
Check if you have python installed properly.
next install pip using

a) Download get-pip.py to a folder on your computer.
b) Open a command prompt and navigate to the folder containing get-pip.py.
c) Run the following command:
python get-pip.py

Pip is now installed!

Copy the path of executable file in environment variable. It is the Script folder path where python is installed. like
C:Programs\Python\Python35-32\Scripts OR
C:\Users(username)\AppData\Local\Programs**\Python\Python35-32\Scripts**
Restart your command prompt and its done

Python: Pip command is not recognized


Calculate running total with over(partition by order by) within update statment

Question: I am trying to create a running total of revenues over product subgroups with discounts given ordered ascending.
I have used the following query
Update Z_Discount_Tool1 Set Cum_Net_Revenue_Discount =
(Select Sum([Umsatz_Netto]) Over (Partition by [WUGR_act] Order by [Discount] From Z_Discount_Tool1)

However, I receive the following error message

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

I can't find the error in my code. So any help is appreciated. Thanks in advance!
Comment: Based on the syntax, I added the sql-server tag.
Answer: This looks like SQL Server.  You can use an updatable CTE:
with toupdate as (
      select dt.*,
             Sum([Umsatz_Netto]) Over (Partition by [WUGR_act] Order by [Discount]) as new_Cum_Net_Revenue_Discount
      from Z_Discount_Tool1 dt
     )
Update toupdate
     Set Cum_Net_Revenue_Discount = new_Cum_Net_Revenue_Discount;


smtpException was unhandled by user code

Question: here is the code.
void sendMail()
{
    MailMessage mail = new MailMessage();

    mail.To.Add("email@example.com");
    mail.From = new MailAddress("firstname.lastname@example.com", txt_name.Text);
    mail.Subject = txt_subject.Text;
    mail.Body = txt_body.Text;

    SmtpClient smtp = new SmtpClient("smtp.gmail.com");
    smtp.EnableSsl = true;

    NetworkCredential yetki = new NetworkCredential("firstname.lastname@example.com", "11111111");
    smtp.Credentials = yetki;

    smtp.Send(mail);

    Response.Write("mailiniz başarılı bir şekilde gönderilmiştir");
}

protected void btn_gonder_Click(object sender, EventArgs e)
{
    sendMail();
}

Answer: Use a try/catch block
void sendMail() {

   try{
      MailMessage mail = new MailMessage();

      mail.To.Add("firstname.lastname@example.com");

      mail.From = new MailAddress("firstname.lastname@example.com", txt_name.Text);

      mail.Subject = txt_subject.Text;

      mail.Body = txt_body.Text;

      SmtpClient smtp = new SmtpClient("smtp.gmail.com");

      smtp.EnableSsl = true;

      NetworkCredential yetki = new NetworkCredential("email@example.com", "11111111");
      smtp.Credentials = yetki;

      smtp.Send(mail);
      Response.Write("mailiniz başarılı bir şekilde gönderilmiştir");
   }
   catch(Exception e){
      Response.Write(e.Message);
   }

}

Comment: i changed my code. but it still gives error and message dont send firstname.lastname@example.com
Comment: So, now you need to tell us what the real error message is, instead of the one in your title.
Answer: The error indicating it is unhandled means you didn't catch the exception.  Now what you actually do in the catch block to handle the exception is up to you, such as logging it to a file, queuing a retry, or showing a message box.  Or trying to do something to prevent the exception in the first place.
protected void btn_gonder_Click(object sender, EventArgs e)
{
  try{
    sendMail();
  }
  catch(Exception ex)
  {

  }
}

Also note you can access ex.Message to see the exception message, or add a break point to the catch block and inspect ex.  It is possible there is more you need to do to get it to work with gmail because of the requirements for authentication.  I don't know if the network credentials are enough.  I've always had trouble with it and resorted to using my ISP's email account that doens't require authentication.
Comment: @gmcalab Because it is framework code.  I would only put it inside sendMail if I planned to take some definitive action that would correct the error and successfully complete the call to sendMail, or I planned to rethrow a more specialized exception.  If I am just displaying a message box I want it outside of the reuseable portions of code.  I wouldn't want to call sendMail from a service and have it try to display a message box the user will never see.
Comment: @gmcalab I mean really, the whole point was just to show him a try/catch.  The topic of where to put the try/catch and what to actually do in the catch will vary vastly depending on the context of where he is using this code.  You are narrow minded to think there is a one solution fits all approach.
Comment: @gmcalab FYI I gave your solution an upvote because I believe it is just as valid as my solution.  Again, where the try/catch goes is splitting hairs because it is a discussion that could be very vast and beyond the scope of the question.
Answer: You add a try/catch block to your code and ignore the error, or you post the entire exception message so that we can help you solve the actual problem.
Answer: According to this page when sending mail over SSL you should use port 465 i.e.
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.EnableSsl = true;
smtp.Port = 465;
...

You should probably still wrap the call to Send in a try/catch block and handle any SmtpException that gets thrown if you can do anything about it.
Note you can also put smtpClient configuration in the web.config file (see here for example).
Comment: +1 beat me to it! :-) Yes, the port must be set correctly, that's most likely the issue
Answer: You haven't specified the port number for Gmail which is 587.
smtp.port = 587;

And your problem should be solved.  Otherwise your code looks good.


pagespeed cleanup performance issue

Question: I configured pagespeed to cache js and css files to improve server performance. But sometimes server loads and performance lag is quite visible. So want to tune pagespeed. I increased pagespeed's ModPagespeedFileCacheSizeKb configuration from 100KB to 512KB. After doing this the cleanup frequency reduces (once in every 5 hrs). Below is the pagespeed log:
[Wed Apr 30 16:06:37 2014] [info] [mod_pagespeed 220.127.116.11-2941 @25845] File cache size is 526295040 and contains 62559 inodes; no cleanup needed.
[Wed Apr 30 17:11:56 2014] [info] [mod_pagespeed 22.214.171.124-2941 @4420] File cache size is 553115648 and contains 65117 inodes; beginning cleanup.
[Wed Apr 30 17:12:02 2014] [info] [mod_pagespeed 18.104.22.168-2941 @4420] File cache cleanup complete; freed 150609920 bytes
[Wed Apr 30 18:12:19 2014] [info] [mod_pagespeed 18.104.22.168-2941 @14154] File cache size is 448905216 and contains 54087 inodes; no cleanup needed.

My question is how to measure the correct cache size so that no cleanup from the pagespeed is needed ??
Why there is incremental cache and inode size on every cleanup call? what does it signify?
Answer: Look in your pagespeed.conf file, there are some control/monitoring panels built in that you can enable and access. It gives you usage statistics which you'll find useful for tuning those parameters.
See these around line 286 onwards;
    # This page lets you view statistics about the mod_pagespeed module.
<Location /mod_pagespeed_statistics>
    Order allow,deny
    # You may insert other "Allow from" lines to add hosts you want to
    # allow to look at generated statistics.  Another possibility is
    # to comment out the "Order" and "Allow" options from the config
    # file, to allow any client that can reach your server to examine
    # statistics.  This might be appropriate in an experimental setup or
    # if the Apache server is protected by a reverse proxy that will
    # filter URLs in some fashion.
    Allow from all
    #Allow from 127.0.0.1
    SetHandler mod_pagespeed_statistics
</Location>

# Enable logging of mod_pagespeed statistics, needed for the console.
ModPagespeedStatisticsLogging off

<Location /pagespeed_console>
    Order allow,deny
    Allow from all
    #Allow from 127.0.0.1
    SetHandler pagespeed_console
</Location>

Also, if you're tuning server performance, using file based caching is slow as the filesystem is by far the biggest bottleneck in performance. Instead, install Memcached server if you can, as Pagespeed has built in support for it and will give you an instant and fairly massive performance boost.
    ModPagespeedMemcachedServers localhost:11211

pagespeed cleanup performance issue


Calculating simple conditional probabilities

Question: If the probability of living past 60 is 0.8, and the probability of living past 70 is 0.5, how do i calculate the probability of living past 70, given that the person has currently lived to 60 years of age? thanks.
Answer: I assume the given probabilities are for a newborn.
Of every $1000$ babies born, on average $800$ will live to $60$ and $500$ will live to $70$.
Now of those $800$ sixty-year-olds, what percentage will live to $70$?
Answer: From Wikipedia, the conditional probability is given by:
$$P(A|B) = \frac{P(A \cap B)}{P(B)}$$
Subbing in the values you give results in:
$$P(\textrm{live past 70} | \textrm{live past 60}) = \frac{P(\textrm{live past 60} \cap \textrm{live past 70} )}{P(\textrm{live past 60})} \\
= \frac{0.5}{0.8} \\
= 0.625$$
Note that $P(\textrm{live past 60} \cap \textrm{live past 70}) = P(\textrm{live past 70})$ since you have to live past 60 to live past 70.


Ping between dockers by hostname

Question: I want to know how to ping between dockers containers by hostname. I create a network with network create command. I'm running bot containers with these commands:
docker run --hostname=app --net=custom container1

docker run --hostname=web --net=custom container2

But when I enter to the first container with
docker exec -it name /bin/bash

and then run
ping web, the response is

ping: web: Name or service not known
Answer: Hostname is not used with docker's built-in DNS resolution. You can resolve container name, service name (in a compose file), and any network aliases you provide. All of these values are controlled by docker outside of the container, where the hostname could potentially be modified inside of the container outside of the view of docker.
To use container name, all you need is:
docker run --name=app --net=custom container1

docker run --name=web --net=custom container2

Or for network alias, you can try:
docker run --network-alias=app --net=custom container1

docker run --network-alias=web --net=custom container2

Comment: Apart from answer my question, you helped me understanding those terms, thanks for your time.
Comment: thanks for your answer, since I'm very new to docker I don't know how to "reuse" the same name everytime I run the container. The first time it runs ok, but on the second time it says "ocker: Error response from daemon: Conflict. The container name "/web" is already in use by container "xxxxx". You have to remove (or rename) that container to be able to reuse that name.". When I run docker image ls I can't see the "web" image to "docker rmi -f" it and run again with the same name.
Comment: @NicolásSantisteban Delete your old container with `docker rm web` or run it so that it deletes as soon as it stops with `docker run --rm --name=web --net=custom container2`
Comment: You can see all containers (not just the running ones) with `docker container ls -a` (or `docker ps -a` for the old syntax).
Comment: Keep in mind the image is a spec to create containers. You build an image, and then you run that image as one or more containers. So when looking for containers, use the `docker container` commands rather than `docker image` commands.
Answer: Giving a hostname to a system or container is one thing, but having it actually resolve from other systems/containers is another.
Take a look at the Oracle Documentation on making docker containers communicate with each other.
Long story short, you can take one of two approaches:
Add a Link to The Run Command
For this approach, simply change --hostname to --name, and add the link option as follows:
docker run --name=web --net=custom container1
docker run --name=app --net=custom container2 --link web:web

This will modify the hosts file in the second container to link the hostname "web" to its containers ip.
Change The Hosts File Directly
In /etc/hosts, add the following lines in the appropriate containers
in app container: <IP_WEB_CONTAINER>  web
in web container: <IP_APP_CONTAINER>  app

the hostnames should now resolve properly.
Comment: I don't know if use Link is a good idea since is a deprecated option
Comment: Links are deprecated and don't handle replacing containers well since the link is hardcoded in the /etc/host file of the container rather than being dynamically updated with docker's DNS.

Ping between dockers by hostname


Can we ignore higher dimensional information when computing the geometric realisation of an $n$-dimensional simplicial set?

Question: $\newcommand{\lan}{\operatorname{Lan}}\newcommand{\tr}{\operatorname{tr}}\newcommand{\H}{\mathsf{H}}\newcommand{\set}{\mathsf{Set}}\newcommand{\T}{\mathsf{Top}}\newcommand{\C}{\mathsf{C}}\newcommand{\psh}{\mathsf{Psh}}\newcommand{\op}{{^\mathsf{op}}}\newcommand{\sk}{\operatorname{sk}}\newcommand{\nat}{\mathsf{Nat}}$I don't know much about geometric realisation other than its very definition. The definition varies, but I prefer the 'clean' description in terms of Kan extension.
Notation: Let $\Delta$ be the simplicial category with objects indexed by the convention $n\sim\{0,1,2,\cdots,n\}$ for $n\in\Bbb N_0$. For any locally small category $\C$, let $\H:\C\to\psh_\C$ be the Yoneda embedding, with $\psh_\C$ the functor category $[\C\op,\set]$. Let $\Delta_\T:\H(\Delta)\to\T$ be the functor assigning to a standard $n$-simplex $\H(n)=\Delta(-,n)$ the standard affine $n$-simplex, and let it act on maps in the usual way. For any $n\in\Bbb N_0$, let $\Delta_{\le n}$ denote the full subcategory of $\Delta$ with objects $0,1,\cdots,n$, and let $\iota_n:\Delta_{\le n}\hookrightarrow\Delta$ be its inclusion functor. Let $\tr_n:\psh_\Delta\to\psh_{\Delta_{\le n}}$ be the $n$-truncation mapping $X\mapsto X\circ\iota_n$.
With that out of the way, we can describe the geometric realisation functor as follows: $$|\cdot|=\lan_{\H(\Delta)\hookrightarrow\psh_\Delta}(\Delta_\T):\psh_\Delta\to\T$$Where $\lan_\bullet$ is the left Kan extension. We can also define the $n$-geometric realisation (I 'made this up' myself, so it's possible this has a more standard name): $$|\cdot|_n:=\lan_{\H(\Delta_{\le n})\hookrightarrow\psh_{\Delta_{\le n}}}(\tr_n(\Delta_\T)):\psh_{\Delta_{\le n}}\to\T$$
My question: If $X$ is an $\le n$-dimensional simplicial set (that is, $X\cong\sk_n(X)$ - all $(m>n)$-simplices of $X$ are in the image of some $(k\le n)$-simplex) then is it true that: $$|X|\cong|\tr_n(X)|_n$$
Motivation: If this were true, it'd fit with my intuition and would make visualising simple examples of $|\cdot|$ much easier. For instance, to compute the geometric realisation of a two-dimensional simplicial set it'd suffice to examine only its triangles, edges and vertices (loosely speaking) - I wouldn't need to examine its higher order relations.
It is true that if $X'$ is another $\le n$-dimensional simplicial set with $\tr_n(X)\cong\tr_n(X')$ then $X\cong X'$. This is a simple corollary of the identity $\nat(\tr_nY,\tr_n Z)\cong\nat(\sk_n Y,Z)$, where the right-to-left direction of the isomorphism simply assigns $\varphi\mapsto\tr_n(\varphi)$. So, in particular, if two $\le n$-dimensional simplicial sets $X,X'$ share the same $n$-truncation, then $|X|\cong|X'|$.
This would suggest that the 'higher dimensional information' of $X$ is irrelevant and gets lost in the process of geometric realisation. This is almost obvious:
Stepping through the colimit formula for the left Kan extension, we find: $$|X|=\bigsqcup_{m=0}^\infty\bigsqcup_{\sigma\in X_m}|\Delta^m|/\sim$$Where $\sim$ is the smallest equivalence relation containing the identification: $$(x,X_f(\sigma))\sim(|f|(x),\sigma)$$For all $m,m'\in\Bbb N_0,\,f\in\Delta(m',m),\,\sigma\in X_m$ and $x\in|\Delta^{m'}|$.
As $X$ is $\le n$-dimensional, if $m>n$ and $\sigma\in X_m$, we have $\sigma=X_f(\tau)$ for some $\tau\in X_k$ and $k\le n$, $f\in\Delta(m,k)$ a surjection. Then for any $x\in|\Delta^m|$: $$(x,\sigma)\sim(|f|(x),\tau)$$And $|f|$ is also a surjection, so here the entire $m$-simplex $|\Delta^m|$ is collapsed onto $|\Delta^k|$. So it would seem that the higher dimensional simplices of $X$ do not contribute anything new to the colimit. By 'new', I mean the introducing of new points or a different topology as opposed to that found in $|\tr_n X|_n$.
However, there is one detail I can't figure out at the moment. Suppose $m,m'>n$ and $f\in\Delta(m,m')$, $\sigma,\sigma'\in X_m,X_{m'}$ have $X(f)(\sigma')=\sigma$. So there is an identification $(x,\sigma)\sim(|f|(x),\sigma')$. It is also true that $\sigma,\sigma'=X_{\alpha,\alpha'}(\tau,\tau')$ for some surjections $\alpha,\alpha'$ and $\le n$-dimensional simplices $\tau,\tau'$, so we have: $(x,\sigma)\sim(|\alpha|(x),\tau)$ and $(x,\sigma')\sim(|\alpha'|(x),\tau')$. Since an equivalence relation must be transitive, we deduce for all $x\in X_m$: $$(|\alpha|(x),\tau)\sim(|\alpha'f|(x),\tau')$$As a relation among the low-dimensional simplices. Perhaps this relation is lost in the quotient in $|\tr_n(X)|_n$ because the arrows $\alpha,\alpha'f$ are not present in $\Delta_{\le n}$. If so, then $|X|\cong|\tr_n(X)|_n$ would fail!
Can we prove that such relations are never lost? That is, is $|X|\cong|\tr_n(X)|_n$ always true?
Many thanks, and apologies in advance if this is trivial.
Comment: The answer is yes. The proof is basically that left adjoints compose.
Comment: @SamuelAdrianAntz Thank you, I'll check that in detail. Your approach seems very clean.
Comment: Isn't the extension by colimits just given by $|X|_n=\varinjlim_{\Delta^k\rightarrow X,k\leq n}|\Delta^k|
=|\varinjlim_{\Delta^k\rightarrow X,k\leq n}\Delta^k|=|\operatorname{sk}_n(X)|$, so that we simply have $|\operatorname{tr}_n(X)|_n=|\operatorname{sk}_n(\operatorname{tr}_n(X))|=|\mathbf{sk}_n(X)|\cong|X|$?
Answer: You're trying for an extremely manual argument, which is good for motivation, but not the most efficient for proving things. To flesh out Zhen's comment: a simplicial set is $n$-dimensional if and only if it's the left Kan extension of its restriction to the full subcategory $\Delta_{\le n}$ of $\Delta$ on objects no larger than $n.$ Your $n$-geometric realization is the left Kan extension of the geometric realization of $\le n$-dimensional simplices along Yoneda, so the point is that you can left Kan extend along $i_n:\Delta_{\le n}\to \Delta$ and then along the Yoneda embedding $y_\Delta$ of $\Delta,$ or just along $y_{\Delta_{\le n}},$ and you end up in naturally isomorphic places, since $y_\Delta\circ i_n=y_{\Delta_{\le n}}.$
Comment: @KevinArlin I've figured this out, or something similar. Thank you for elaborating
Comment: The natural isomorphism makes sense to me, but I yet don't quite get the last part. Both $|-|_n$ and $|-|$ are left Kan extensions along the Yoneda embeddings of $\Delta_{\leq n}$ and $\Delta$ respectively, just like you mention. How are the left Kan extensions along $i_n$, $|-|$ and $|-|_n$ (which have to be those of the Yoneda embeddings) helpful?
Comment: @SamuelAdrianAntz Oh, sorry, that was an error.
Comment: Thank you for responding (and for helping me understand the definition of geometric realisation a few days ago!), +1. There are a few details I think I need to check in your post. First of all, when Zhen spoke of 'adjoints', they referred to: $|\cdot|\dashv\mathrm{Sing}$, right? So do I need to also check that: $|\cdot|_n\dashv\operatorname{tr}_n\circ\,\mathrm{Sing}$? Really, I'm not sure how the Kan extensions are supposed to compose in your post - but I haven't fully thought about it yet, and I won't have the time today. I'll get back to this tomorrow!
Comment: @FShrike If $u:C\to D$ is any functor and $E$ is a third category then, if it exists, the left-Kan-extension-by-$u$ functor $u_!:E^C\to E^D$ is left adjoint to the compose-with-$u$ functor $u^*:E^D\to E^C.$ Then if $w=u\circ v,$ we have $w^*=v^*\circ u^*,$ which means, since "left adjoints compose," $w_!\cong u_!\circ v_!.$ We're applying this result to show $y_{\Delta,!}\circ i_{n,!}\cong y_{\Delta_{\le n},!}$ as functors $\mathsf{Top}^{\Delta_{\le n}}\to \mathsf{Top}^{\mathsf{SSet}}.$ Then, we evaluate at the tautological functor $\Delta_{\le n}\to \mathsf{Top}.$ Hope that helps.


inverse gamma (0.001,0.001) prior on the variance in the Bayesian hierarchical model

Question: This 8 schools data is from Gelman 2006 paper: http://www.stat.columbia.edu/~gelman/research/published/taumain.pdf. In Figure 1 (c), the prior density of inverse gamma (0.001,0.001) was overlain on the posterior histogram. The author claims that "This prior distribution is even more sharply peaked near zero and further distorts posterior inferences", which I find difficult to understand because inverse gamma (0.001,0.001) only has a very small probability near 0, e.g., $P(\sigma < 1 | \alpha =\beta=.001) = 0.006$ for the prior but the posterior $P(\sigma < 1) = .487$. So how does this prior distort the posterior towards 0?

UPDATE: Thanks so much for your reproducible code. I have accepted it as an answer.  It appears that the prior density in the plot has been scaled to the range (0,30), that's why we see a spike of inv-Gamma(0.001, 0.001) near 0. But the issue is that if you draw samples from inv-Gamma(0.001, 0.001), you are going to see the probability $\sigma < 1$ is quite small and most values would be very large, so I do not understand how this prior can still distort the posterior to have a spike near 0. PS: the CDF of the inverse gamma distribution on Wiki page is defined using UPPER incomplete gamma function, so you should look at the "uppinc" when you run pracma::gammainc(shape, scale / 1) / gamma(shape)
Comment: This is a good question. It's deceptively difficult. The answer seems obvious to me from working with Bayesian models, but I'm having trouble explaining *why* it's true.
Answer: The point here is that the posterior for a invgamma(1, 1) prior has greater density near zero than that for a Uniform prior, and invgamma(.001, .001) has even more density near zero than invgamma(1, 1). In other words, you should compare the posterior distribution for each plot, and compare the prior distributions for each plot, but not necessarily compare the prior to the posterior within each plot.
Answer: Figure 1 in the "Priors for variances" paper compares three prior distributions for the hierarchical standard deviation, $\sigma_\alpha$, in a two-level normal hierarchical model. It illustrates the drawbacks of the supposedly non-informative inverse gamma prior on the eight schools example.
As the answers by @Eoin and @Eli point out, the three priors are ordered so that, from left to right, each prior puts more probability mass near zero. In practice the inverse gamma priors suggest that we expect the school effects $\alpha_j$ shrink towards 0 even before looking at the data. In other words, the uniform prior is the least informative and the inverse-gamma($\epsilon$, $\epsilon$) prior is the most informative.
The informativeness of priors is to some extent defined with respect to the likelihood: a prior is strongly informative if it doesn't support values that are consistent with the data. For the eight schools, the likelihood is close to flat in the range [0,10], so any prior that concentrates only on a part of this range ends up being much more informative than the likelihood and the data.
This is perhaps easier to see in the plots below which show the prior (red curve), the likelihood (blue curve) and the posterior (histogram) because
$$
posterior \propto prior \times likelihood
$$
With the uniform prior, the posterior is informed mostly by the likelihood, ie, by the data. But with the inverse gamma prior, the posterior doesn't look like much different from the prior even after observing the data from the eight schools. Why bother with collecting data if we are not prepared to update our prior in the face of evidence?
Note: The likelihood for eight schools is a function of both the overall effect $\mu$ and the hierarchical standard deviation $\sigma_\alpha$. I picked $\mu$ = 10 to plot the likelihood as a function of $\sigma_\alpha$ but the choice doesn't matter: for any value of $\mu$ in [0,15] the likelihood supports values for $\sigma_\alpha$ in the range [0,10].

Finally, the inverse-gamma($\epsilon$, $\epsilon$) has most of its probability mass close to zero. It seems you have inadvertently computed the upper-tail probability P{X > x} instead of the lower-tail probability P{X ≤ x}.
I'm sure you've looked up the definition: The CDF of the inverse gamma distribution with parameters shape $\alpha$ and scale $\beta$ is $F(x;\alpha,\beta) = \Gamma(\alpha,\beta/x) / \Gamma(\alpha)$. The numerator is the incomplete gamma function, the numerator is the (complete) gamma function.
Let's do the computation in R; we will use the pracma::gammainc function which helpfully returns both the upper and lower incomplete gammas, so any confusion is avoided.
shape <- scale <- 0.001

# lowinc = P{X ≤ x}; uppinc = P{X > x} for x = 0.1 and x = 1

pracma::gammainc(shape, scale / 0.1) / gamma(shape)
#>       lowinc       uppinc       reginc
#> 0.0933783135 0.0061116005 0.0009391118
pracma::gammainc(shape, scale / 1) / gamma(shape)
#>       lowinc       uppinc       reginc
#> 0.9936876467 0.0063123533 0.0009942606

The code to reproduce the figures, in all its gory details:
library("tidyverse")
library("brms")

set.seed(2022)

y_j <- c(28, 8, -3, 7, -1, 1, 18, 12)
sigma_j <- c(15, 10, 16, 11, 9, 11, 10, 18)

schools <- tibble(
  school = letters[1:8], y_j, sigma_j
)

log_likelihood <- function(mu, sigma_a) {
  sum(dnorm(y_j, mean = mu, sd = sqrt(sigma_j^2 + sigma_a^2), log = TRUE))
}
likelihood <- function(mu, sigma_a) {
  exp(log_likelihood(mu, sigma_a))
}

scaled_curve <- function(func, from = 0, to = 1, n = 1001, ...) {
  x <- seq(from = from, to = to, length.out = n)
  y <- eval(substitute(func), envir = list(x = x))
  # Scale to match a density histogram
  y <- y / sum(y, na.rm = TRUE) / ((to - from) / n) * .95
  lines(x, y, ...)
}

schools_posterior <- function(sigma_a_prior) {
  fit <- brm(
    y_j | se(sigma_j) ~ 1 + (1 | school),
    family = gaussian,
    prior = prior_string(sigma_a_prior, class = "sd"),
    data = schools
  )
  hist(
    as_draws_array(fit, variable = "sd_school__Intercept"),
    breaks = 60, probability = TRUE, col = NULL,
    xlim = c(0, 30), xlab = expression(sigma[alpha]),
    yaxt = "n", ylab = NULL,
    main = paste("The prior is", sigma_a_prior)
  )
  scaled_curve(
    sapply(x, function(x) likelihood(10, x)),
    from = 0, to = 30, col = "blue", lwd = 2
  )
}

schools_posterior(
  "uniform(0,100)"
)
scaled_curve(
  dunif(x, min = 0, max = 100),
  from = 0, to = 30, col = "red", lwd = 2
)

schools_posterior(
  "inv_gamma(1,1)"
)
scaled_curve(
  MCMCpack::dinvgamma(x, 1, 1),
  from = 0, to = 30, col = "red", lwd = 2
)

schools_posterior(
  "inv_gamma(0.001,0.001)"
)
scaled_curve(
  MCMCpack::dinvgamma(x, 0.001, 0.001),
  from = 0, to = 30, col = "red", lwd = 2
)

Answer: You're right that the $\text{inverse-gamma}(0.001, 0.001)$ prior assigns a small probability to values of $\sigma$ near $0$. As you noted, $P(\sigma < 1 | \alpha =\beta=.001) = 0.006$. However, relative to other values of $\sigma$, the most likely value of $\sigma$ is near $0$. The density near 0 is high relative to other regions. While the density assigns low absolute probability to $\sigma$ near 0, the most likely value is $\sigma$ is still near 0.
Contrast this to the $\text{inverse-gamma}(1, 1)$ prior. This prior still says that $\sigma$ should be close to 0. However, the tails of this prior drop more slowly. This means larger values of $\sigma$ are still considered plausible. Contrast both inverse-gamma priors to the $\text{Unif}[0, A]$ prior which gives equal likelihood to small and large values of $\sigma$.
The author is arguing that the inverse-gamma distribution is a bad choice for a noninformative prior. It puts most of it's density near 0, and therefore pulls the posterior distribution close to 0. Using this class of priors is like saying you expect a small standard deviation before you see any data. This is not the behavior people usually associate with non-informative priors. You're right that the posterior isn't as peaked near 0 as the prior. However, it would be even further from 0 if the prior didn't assign so much mass at 0. The $Unif[0, A]$ prior doesn't pull the posterior to 0, and, instead, let's it spread out further of the real number line.


Shopify Pixel Extension - exit code 1

Question: I wanted to create a web pixel extension for my shopify app, so I followed the instructions on the official shopify pixel extension creation guide: https://shopify.dev/apps/pixels/pixels-getting-started
When I'm trying to build the app, it outputs the following error:
extensions | my-app-pixel (C:\projects\shopify\my-app-pixel\node_modules\.bin\shopify-cli-extensions:2
extensions | basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
extensions | ^^^^^^^
extensions |
extensions | SyntaxError: missing ) after argument list
extensions | at Object.compileFunction (node:vm:352:18)
extensions | at wrapSafe (node:internal/modules/cjs/loader:1033:15)
extensions | at Module._compile (node:internal/modules/cjs/loader:1069:27)
extensions | at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
extensions | at Module.load (node:internal/modules/cjs/loader:981:32)
extensions | at Function.Module._load (node:internal/modules/cjs/loader:822:12)
extensions | at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
extensions | at node:internal/main/run_main_module:17:47)

━━━━━━ Error ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Command failed with exit code 1: C:/Users/user/AppData/Local/shopify-cli-nodejs/Cache/vendor/binaries/extensions/3.9.0-windows-amd64.exe build -
my-app-pixel (C:\projects\shopify\flaminjoy-galleries-pixel\node_modules\.bin\shopify-cli-extensions:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
^^^^^^^

SyntaxError: missing ) after argument list
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47)

Tried to create a blank app node template, run scaffold script but it didn't work, tried to change different terminals, cmd, powershell, I think the script is broken
How to fix this line of script to work for Shopify?
I just run build for shopify and it outputs the above error.
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")

Windows 10
Bash
Shopify CLI 3.9.0
Thanks,
Awaitin some responses/thoughts
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Solution: Shopify version @3.9.2 helped to solve this problem.
Comment: I guess you mean that you've upgraded to this version?
Comment: Yes, I've updated both cli and app packages to the 3.9.2 version

Shopify Pixel Extension - exit code 1


Why is the spectrum of an operator with compact resolvent countable and consists only of eigenvalues?

Question: I'm trying to prove the following statement.
Let $\mathcal H$ be a Hilbert space and $T: D \rightarrow \mathcal H$, $D \subset \mathcal H$, a linear operator. Let $\lambda_0 \in \rho(T)$ such that $(T - \lambda_0)^{-1}$ is a compact operator.
Then $(T-\lambda)^{-1}$ is compact for each $\lambda \in \rho(T)$, $\sigma(T)$ consists only of a countable number of eigenvalues and doesn't have a limit point in $\mathbb C$.
It was said that this follows from well known facts about the spectral theory of compact operators.
Now, the notable facts that I recall are: (let $K$ be a compact operator)

each non-zero spectral value of $K$ is also an eigenvalue,
for non-zero eigenvalues of $K$, the dimension of their eigenspace is finite,
$\sigma(K)$ is countable and its only limit point is 0.

Unfortunately, I'm unable to cook up the desired conclusion from those properties alone. So I guess there is some missing link here.
Can someone point me into the right direction?
Answer: You didn't say that but I'm assuming you also want $T$ to be densely defined.
Let us write $R_\lambda=(T-\lambda)^{-1}$ for $\lambda\in\rho(T)$ to denote the resolvent. If $R_\lambda$ is compact for some $\lambda$, then $T$ is said to have compact resolvent (just to give you a term to search for more information).
The statements that you make are very well-known facts about operators with compact resolvent.
For your convenience I will prove them below.
Assume that $R_{\lambda_0}$ is compact for some $\lambda_0\in\rho(T)$.

Claim 1. $R_\lambda=(T-\lambda)^{-1}$ is compact for every $\lambda\in\rho(T)$.

Proof. Recall the resolvent relation:
$$R_\lambda-R_{\lambda_0} = (\lambda-\lambda_0)R_\lambda R_{\lambda_0}$$
Adding $R_{\lambda_0}$ on both sides we get
$$R_\lambda = ( (\lambda-\lambda_0)R_\lambda + I) R_{\lambda_0}.$$
Thus, we have written $R_\lambda$ as composition of a bounded operator and a compact operator and therefore it is compact. $\square$

Claim 2. $\sigma(T)$ is a discrete set (countable and no accumulation points) and consists only of eigenvalues.

Proof. Set $S=R_{\lambda_0}$.
The assumptions is that $S$ is compact. We claim that this implies that $\sigma(S^{-1})$ is a discrete set of eigenvalues (which immediately implies the same for $\sigma(T)$ since $S^{-1}=T-\lambda$).
Because $S^{-1}$ is invertible, we have $0\not\in\sigma(S^{-1})$. Furthermore, by the spectral theorem, $\sigma(S)$ consists of countably many non-zero eigenvalues with the only possible accumulation point being $0$.
Observe that $\lambda\not=0$ is an eigenvalue of $S$ if and only if $\lambda^{-1}$ is an eigenvalue of $S^{-1}$ (check that!).
Next, observe that $\sigma(S^{-1})$ consists only of eigenvalues. To see this, say $0\not=\lambda$ is not an eigenvalue of $S$. Then $\lambda\in\rho(S)$. So $S-\lambda$ is bounded and invertible. This implies that $S^{-1}-\lambda^{-1}$ is also bounded and invertible:
$$S-\lambda = \lambda S(\lambda^{-1}-S^{-1})$$
$$(S^{-1}-\lambda^{-1})^{-1} = -\lambda (S-\lambda)^{-1}S$$
Thus $\lambda^{-1}\in \rho(S^{-1})$.
Putting these observations together we have proved that $$\sigma(S^{-1})=\sigma_p(S^{-1}) = \{\lambda^{-1}\,:\,\lambda\in\sigma(S)\setminus\{0\}\}$$
which is a discrete set. $\square$


First ever transfer in football

Question: What was the first ever recorded in transfer in football, by transfer I mean the first time a club bought another player's contract from a club?
Answer: The first ever transfer was Willie Groves to Aston Villa in 1893 for £100. This was after player registration was introduced in 1885 by the FA making it possible for a player to play for a club only after he had been registered with them.
Just out of interest that sum of £100 would now be worth £10881.81 taking inflation into account.

First ever transfer in football


Set default frontpage to Front Page view

Question: I've setted the Default front page to the View Front Page, but when I go to www.mydomain.com the page don't redirects to www.mydomain.com/frontpage.
When I go and write www.mydomain.com/frontpage the Front Page view is displayed.
What is going wrong?
Answer: you need to set it here:
http://www.DOMAIN.com/admin/config/system/site-information
You set the "Default Front Page Link" there.
When you hit your root (/) url, it will not "redirect" to that custom url you set, but it will auto render the url you inputted.
If you want to do a true redirect when hitting the frontpage you might have to do it via the .htaccess file as I'm not sure if there is module that can do a redirect from the frontpage.
Comment: Thanks for reply. That was exact what I did. I expected don't "really" redirect to /frontpage but rather only render /frontpage as you mentioned. But the page is not rendered, although www.mydomain.com/frontpage is working.


Buscar frase dentro de arquivos .cs de uma pasta especifica usando C#

Question: Gostaria de saber como eu consigo buscar uma frase dentro de arquivos .cs de uma pasta específica.
Não precisa desenvolver código, só gostaria de saber qual/quais funções usar e como usá-las. Não consegui achar nada relacionado no Google.
Comment: Você usa alguma IDE?
Comment: Tô usando o Visual Studio 2015.
Answer: Pode usar as classes DirectoryInfo e FileInfo, da seguinte maneira:
<code> DirectoryInfo dirInfo = new DirectoryInfo(@"C:\projetos\projeto\src");
 foreach (FileInfo arquivo in dirInfo.GetFiles("*.cs", SearchOption.AllDirectories))
 {
    string codigoCSharp = File.ReadAllText(arquivo.FullName);
    if (codigoCSharp.Contains("Minha Frase"))
        Console.WriteLine("Encontrado");
 }
</code>
Comment: Utilize `SearchOption.AllDirectories` no segundo parâmetro do método `GetFiles` . Editei a resposta.
Comment: E como ficaria se dentro desta pasta "C:\projetos\projeto\src" eu tivesse subpastas das quais quisesse adicionar à pesquisa?
Comment: Era isso que eu procurava! Obrigado pela resposta, foi de grande ajuda.


Why do we "play" an instrument rather than "work" an instrument?

Question: There's a line in the Steely Dan song Deacon Blues that mentions "working" a saxophone rather than "playing" one. But why do we say "play" rather than "work"? Is it just something that we've all got used to and don't think about it any more? Or is there a good reason?
Comment: I'm voting to close this question because this is a question about linguistics rather than musical practice. Yes, it's about a term *for* a musical practice, but it's not specialized musical jargon; the question is about the evolution of language. Note, languages differ. French uses *jouer*, the same word as to "play" a game, but Spanish uses *tocar*, the same as "to touch" (I think Italian is similar).
Comment: Also, did you try https://www.etymonline.com/word/play? It seems, from OE times at least, it was making a point about fluency and facility.
Comment: Well, why do we say "write a book" and not "work a book"? Why do we say "cook some food" rather than "work some food"? Why do we say "ride a bike" rather than "work a bike"? Why do we say "answer a question" rather than "work a question"?
Comment: @MichaelCurtis The way I see it, "What does 'fugue' mean" is on-topic. For "Why do we use the word 'fugue,'" the answer is "well, you see, *fuga* means "flee," as in a chase, and the imitative parts are chasing after each other etc etc" is an etymology question. Very on-topic on English Language and Usage SE (if the poster shows that they've looked it up and how their research fails to answer their question); it wouldn't be off-topic there just because the word is musical. I don't see a musical application to this question.
Comment: With musical terms like toccata, sonata, ricercare, etc. etc. should we really close a question that looks to connect a particular word to music theory usage?
Comment: I think it's as much a neuroscience question as it is linguistics.
Comment: To expand what I found at etymonline: It seems, from way back in Old English, that "play" had some of the same meanings it does now: child's play, play an instrument, but also a sense of rapid, easy movement, as in "the light *played* across the water," and it was this that led to both the "child's play" and "play an instrument" meanings.
Answer: This is really a language, rather than music, question. I think it's all about idiom and connotation.
I don't know the Steely Dan song, but using the word "work" in a "blues" context certainly makes sense to connote "working class" or other low brow versus high brow ideas associated with the blues.
"Playing" an instrument is an idiomatic usage, it's just the particular verb chosen in English. You could say "operate" an instrument. It would sound strange, unidiomatic, but the meaning would be understood. Compare this to something like "suonare" in Italian. That is the idiomatic word for playing an instrument, but its broader meaning is "to sound." More literally translated into English you might say "sound the saxophone."
A personal anecdote: one time I was talking to a friend who was an English professor and who I would sometimes jam with (he sang, I operated the guitar.) The conversation got onto the word "play" and music. I suggested that the word "play" connotated children's play and a sense of exploration and "no rules", or at least rules you can change at will, like "Calvinball." Music, while usually following style conventions, is less like a strict recipe or work procedure, and is more like an exploration of the "infinite variety of music" (that's a Leonard Bernstein quote.) Music really flowers when you freely explore - "play" - with the possibilities.
If this wiki page is correct, the etymology of "play" includes meanings "move" and "exercise", which make sense when applied to a musical instrument. The historic meaning of the word isn't so much about games but instead about movement.
Comment: 'I operated the guitar' - I like it! Used to be in a band where we had a 'bass guitar holder'.
Answer: I don't know the origin of the use of "play" but it predates any of our existences in this world. I also think most would agree that it is very difficult to think of any other word that we would naturally use to describe the act of getting sound from an instrument. The word "work" is really not associated with the act of playing a musical instrument. Perhaps "play" is used to encourage people to learn music by making it sound fun and not like a job. However the word "play" is not used in all languages. In Spanish it is "tocar", meaning "to touch". Italian it is "suonare", loosely "to make sound". In other languages it may the the specific act that determines the name of the act, such as blow, pluck or strike.
In the case of "Deacon Blues" it is a lyrical choice. If you look to the following line he says "I play just what I feel". It would have been less poetic and bit awkward to use "play" instead of "work" in the first line so Fagen made an artistic choice in picking the word "work". He learns to work the saxophone and plays what he feels. Interesting choice since learning how to play a musical instrument can feel like work but actually playing it can be very fun.
Answer: Deacon Blues was written by Walter Becker and Donald Fagen in 1976.
The protagonist in the song was a sort of loser anti-hero who dreamed of being a jazz musician.
When writing songs, certain words either fit with the flow and the writer's ear and vision, or they don't.  "Play" the saxophone didn't work for Donald and Walter, nor did "blow" the saxophone. But "work" seemed right.
And considering how the odd mechanisms on a saxophone appear to function (to the admittedly accomplished pianists, bass players, and guitar players that Donald and Walter were) in such a complicated fashion, it seems as though learning to "work" a saxophone would be a daunting task.
"Working it" has since become a popular enough expression for encouraging a player of any instrument to go for it, and to keep doing something really good that they are onto.
A guy or gal rolls into an earnest and tasty solo, and band-mates are known to exclaim, "Work it, yeah boy, work it!".
Comment: This seems to answer the opposite question to the one that was asked, "why'd he say 'work'" rather than "how did we come to say 'play.'" Though the question you answered was *maybe* a better fit for this site.


Problem with login/logout operations while using drupal for facebook

Question: I'm using drupal 6 and the module drupal for facebook v6.x-3.3 and I have a problem with the logout functionality.
Strangely when I try to logout of the website, it automatically redirects me to my facebook profile. If you return to the site, I am still logged out of it.
I don't know if is a issue of javascript or module.
I had a problem with the login, because if I tried to enter the site, the site would freeze in front page and on reloading by pressing f5, it shows up in logged in state.
Now, have a delay (the typical module) and you enter. Is there any way to remove the delay that has to quickly enter the website?
Answer: You can try FBOAUTH module. This module is simple and straight forward. It works out of the box with out any glitches.
Check readme file to configure Facebook Login button. Hope it resolves all your issues !


What is the best way to keep data between actions in zend framework 2?

Question: I have a form and it is subdivided in multiple steps, and i would like to know what is the best way to keep the data.
I'm using php with zend framework 2
Answer: Store the data in a session. This would be true in any application.


Session ID regeneration not working for concurrent requests

Question: I had posted this question to the CI forum but without any answer so I am trying it here.
I am using CI for a REST API serving JSON calls from a single page app.
With CI 2.x I had a problem with session ID regeneration in a case of "chain" of requests in a short time while some of them changed session ID. I hoped that CI 3 with its brand new session library will fix it.
I upgraded to 3.0, read carefully session docs and did some tests. From my point of view the problem which occured in CI 2.x is still persisting in 3.0.
Let me explain it on an example of http requests (actually observed from a real app):
Session ID is not changing:
GET ... Request cookies: ci_session=123,
        Response cookies:
GET ... Request cookies: ci_session=123,
        Response cookies:
...

Session ID is to be regenerated:
GET ... Request cookies: ci_session=123,
        Response cookies: ci_session: <deleted>, ci_session: 456

This request had started sooner than the previous one returned, so it is carrying the old session ID:
GET ... Request cookies: ci_session=123,
        Response cookies:

But the session ID 123 is not valid anymore so the request is regarded not authenticated.
It seems, that the locking, which was added to the new session library does not prevent this.
My session config is:
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = <some path>
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 60;
$config['sess_regenerate_destroy'] = TRUE;

I am using session_write_close() after initial request authentication.
Is there a way how to use CI 3 for this king of requests? Am I doing something wrong?
Any help is appreciated.
Thank you
Answer: Well, first of all - if you're using sessions, it's not a RESTful API, because the whole point of using a session is to maintain state, while a REST service must be stateless.
That being said, the sess_regenerate_destroy setting was created exactly for a use case like yours. Set it to boolean FALSE and the old session ID will be deleted later by the garbage collector instead of immediately upon regeneration. That leaves a time window during which both the old and the new session IDs are usable, and the queued request won't be rejected.
Comment: Uauu, what a speed :) I want to use long sessions (nice user experience) and frequent session ID regeneration (session fixation attack prevention). However when I use `sess_regenerate_destroy=FALSE` and a user will log out only one session will be destroyed but many opened sessions will be left waiting for GC a few hours maybe more. That's not safe.
That leaves me with two choices:
1. Short `session_expiration` and no session ID regeneration (less user friendly but more safe),
2. Some kind of other authorization (e.g. OAuth2)
Thank you anyway for your response and your work for the CI !
Comment: Thank you Narf. I was hoping my question would find you and it did. The `sess_regenerate_destroy` was probably the only setting of the session library I did not understand very much. I tested your suggestion and it seems to be working. I was wondering what is the length of the time window when both the old and the new session IDs are usable. Is it the same value as `sess_expiration` (session.php line 303)?. Does it mean that all session files which are not deleted by the GC contain still usable sess ID? In my case it would be a few days old files/IDs. I am a little confused here. Thank you!


Want to develop a WYSIWYG editor for GUI in eclipse

Question: I want to develop a WYSIWYG editor for developing Mobile Apps (Hybrid). Looked into the following link. Develop a WYSIWYG editor in eclipse plugin
I have read about GEF. But some of my friends told me that GEF is outdated and there are some alternative frameworks coming up. I couldn't find any such framework.
Kindly let me know whether GEF is the best bet or is there any other framework which I can use to develop screens for Mobile Apps
Thanks
Answer: I did some searching about a year+ ago (see here), and GEF came out as the best choice. If there are other frameworks out there that I don't know of, please ask your friends to tell, but from my knowledge there aren't many. GEF is VERY complex, but at the same time provides the best abstraction to develop editors, with a lot of built-in capabilities. There is also a plan for GEF4, but that is long range.
In short, ask your friends for concrete examples, and if they can't provide you good ones, go with GEF. The future is always more promising than the present because it is not yet here :-)
Comment: Grahiti is one of them said by my friend. Your blog provides a lot of input. Thanks for the answer. I am doing some analysis on Graphiti and then will decide on it.
Comment: I tried Graphiti also. Maybe it has improved since then. If so, please tell :-).
Comment: Graphiti is also good. The advantage with Graphiti is I dont have to know abt GEF or Draw2D. I feel it is better to use GEF it has lot of capabilities


Converting HttpFileCollection to byte and stream the data to Image Control in asp.net

Question:     HttpFileCollection oHttpFileCollection = e.PostedFiles;
    HttpPostedFile oHttpPostedFile = null;
    if (e.HasFiles)
    {
        for (int n = 0; n < e.Count; n++)
        {
            oHttpPostedFile = oHttpFileCollection[n];
            if (oHttpPostedFile.ContentLength <= 0)
                continue;
            else
                oHttpPostedFile.SaveAs(Server.MapPath("Files") + "\\" + System.IO.Path.GetFileName(oHttpPostedFile.FileName));
    }

How can I convert HttpFileCollection to byte and read the stream and then display the image to Image Control in asp.net
Thanks
Answer: HttpFileCollection oHttpFileCollection = e.PostedFiles;
HttpPostedFile oHttpPostedFile = null;
if (e.HasFiles)
{
    for (int n = 0; n < e.Count; n++)
    {
        oHttpPostedFile = oHttpFileCollection[n];
        if (oHttpPostedFile.ContentLength <= 0)
        {
            continue;
        }
        else
        {
            var filename = Path.GetFileName(oHttpPostedFile.FileName);
            var path = Path.Combine(Server.MapPath("~/Files/"), filename);
            oHttpPostedFile.SaveAs(path);

            // Now you could display each image in a dynamically added Image
            // control to the page:
            Image image = new Image();
            image.ImageUrl = "~/Files/" + filename;

            // I assume that you have a reference to the current page
            // so that you could append image controls to it.
            // You could also append the images to a placeholder or a Panel
            // on your WebForm
            this.Controls.Add(image);
        }
}


How to replace type bool in pandas dataframe with strings

Question: I have a dataframe with values:
  Name      Enrolled
JarJar          TRUE
  Boba         FALSE

I want to replace instances of TRUE/FALSE (regardless of case) with TRUE_/FALSE_.
I tried using this code snippet here:
df_to_add = df_to_add.replace('(?i)true', 'TRUE_', regex=True)
df_to_add = df_to_add.replace('(?i)false', 'FALSE_', regex=True)

but nothing happens since the TRUE/FALSE values in the dataframe are currently numpy.bool. How can I work around this?
Answer: import pandas as pd

df = pd.DataFrame.from_dict({'Name' : ['JarJar', 'Boba', 'Foo', 'bar', 'foobar', 'foobaaz'], 'Enrolled' : ['TRUE', 'FALSE', 'true', 'false', 'True', 'False']})
df = df.replace({r"TRUE(?i)": "_TRUE", r"False(?i)": "_FALSE"}, regex=True)

print(df)

Output :
      Name Enrolled
0   JarJar    _TRUE
1     Boba   _FALSE
2      Foo    _TRUE
3      bar   _FALSE
4   foobar    _TRUE
5  foobaaz   _FALSE

Comment: this does not work as the booleans in my dataframe are of type bool so it's not a simple str replacement
Comment: Well you tell us "regardless of the case" which basically means it's a string
Comment: sorry for the confusion
Answer: df_to_add.replace({True: 'TRUE_', False: 'FALSE_'}, inplace=True)


jQuery X-Ray Effect to Reveal Data Points

Question: I have a client who wants to have an X-Ray effect that reveals clickable data points. A slider would be used to move a viewing window over an image, that would reveal an x-ray, or secondary image as the slider is moved. I've adapted Eli Kirk's X-Ray effect (http://elikirk.com/2013/12/02/draggable-x-ray-effect-using-css-javascript/) to get what I have so far: http://jsfiddle.net/xfxLx/3/. The jQuery UI portion of it is easy enough:
var artWidth = 300;
$(document).ready(function() {
  $('.xraySlider').slider({
    slide: function(e, ui) {
      var newLeft = (ui.value / 100) * (artWidth - 100);
      $('.xrayWindow').css({'background-position': (newLeft * -1) + 'px 0px', "left": newLeft + "px" });
}
   });
 });

The problem I'm having is making clickable data points that would be revealed by the window as it is slid across the main image. The data points would be fairly simple shapes (like, say, a black circle), that the user could click on once revealed by the x-ray window, to reveal a popup with more info. I've beat my head against the wall trying to come up with a workable solution (if this wasn't bad enough, it all has to work in IE7, so I've ruled out canvas as well).
If this effect won't work under the confines listed (which I've told them might be the case, since I have yet to come up with a viable solution), that's fine, but I just want to make sure I'm not missing anything.
Answer: I have changed yoput HTML, setting an inner element to the xray, that will hold the points

Then, the JavaScript changes slightly
  var artWidth = 300;
  $(document).ready(function() {
    $('.xraySlider').slider({
            slide: function(e, ui) {
                var newLeft = (ui.value / 100) * (artWidth - 100);

        $('.xrayWindow').css({"left": newLeft + "px" });
        $('.innerXray').css({"left": -newLeft + "px" });
            }
        });
  });

And CSS is changed to make the xray clip the contents (with overflow hidden), and the inner has the background image instead of the xraywindow. also, some styling to the points.
.innerXray {
      width: 300px;
      height: 490px;
      position: absolute;
      background: url(http://s21.postimg.org/tpg6me1vb/bones.jpg) no-repeat;
      background-position: 0px 0px;
    }
.point {
    position: absolute;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: red;
}
#heart {
    left: 150px;
    top: 130px;
}
#brain {
    left: 150px;
    top: 30px;
}
.xrayWindow {
    width: 100px;
    height: 490px;
    border: 2px solid rgba(255,255,255,0.5);
    position: absolute;
    top: 0px;
    left: 0px;
    overflow: hidden;
}

result
Comment: I tried it, editing the original JSFiddle link I provided, but this doesn't seem to work. Did I miss something? http://jsfiddle.net/vrEeF/
Comment: Sorry, I miss the .xrayWindow when I post the CSS. The key is to delete the bacjground from it (it is now in the inner, and to set overflow: hidden. (I have added also more comment about that)
Comment: I added cursor:pointer; to the point class just to make sure they'd be clickable, and it works. I guess I was just overthinking it. Thanks for your help! Here's the final item in action: http://jsfiddle.net/vrEeF/1/


Usefulness of coherence in coherence spaces-based interpretations of type systems

Question: I'm going through "Proofs and Types", and I'm trying to internalize the notion of coherence spaces. In particular, I'm trying to understand what additional information is given by the fact that two tokens $\alpha_1, \alpha_2$ of a coherence space $\mathcal{A}$ are, well, coherent.
Sure, that means that there exists a point of $\mathcal{A}$ such that both tokens belong to it (in particular, $\{ \alpha_1, \alpha_2 \}$ will do). But what does it give us if we are to analyze and interpret a particular type system?
The only use of the notion of coherence I've seen so far is basically in prove certain tokens of "composite" (product or arrow) coherent spaces are coherent.
Answer: You might find this article useful.
To distill what it says down a bit, tokens represent individual pieces of information you can have about a value of the type. Tokens are coherent if there is a value of the type about which it would make sense to learn both pieces of information (i.e. they are actually "coherent" pieces of information).
So in the $\mathsf{Bool} × \mathsf{Bool}$ example from the article, the pieces of information are:

The first part of the pair is $\mathsf{false}$
The first part of the pair is $\mathsf{true}$
The second part of the pair is $\mathsf{false}$
The second part of the pair is $\mathsf{true}$

1 is coherent with 3 and 4, because $(\mathsf{false},\mathsf{true})$ and $(\mathsf{false},\mathsf{false})$ are values. 1 is not coherent with 2 because it's impossible for the first part of the pair to be both $\mathsf{true}$ and $\mathsf{false}$.


Why is the hexatonic scale that can be derived via a chain of perfect fifths so little-known?

Question: When learning about European classical music, it's heptatonic scales. The pentatonic scale is also very well known and widely used in folk music in different parts of the world. However, before I started reading in Wikipedia about hexatonic scales, the only hexatonic scale I had heard about was the whole-tone scale. The hexatonic scale that you get by throwing out one of the notes from the diatonic scale so that it becomes atritonic (or by adding one note to the pentatonic scale) seems to be less well known than its neighbors. Although, just like those other two, it can be derived from a chain of perfect fifths.
What I mean is the scale which has the following intervals between notes: 1 semitone, 2 semitones, 2 semitones, 3 semitones, 2 semitones, 2 semitones.
I started thinking about it in the context of algorithmic composition. This 122322 scale is much more flexible and rich than the 22323 pentatonic scale. There is this semitone and you can get more interesting melodies out of it. But, unlike with the 1221222 heptatonic scale, you do not have tritones anywhere. If I want to avoid tritones in melody and harmony, this is a very good thing since it ensures that any random bunch of notes that my algorithm outputs is guaranteed to not contain a tritone.
There are of course some disadvantages... The one that I notice is that it's not possible to play two major or minor chords that are two semitones apart. However, for example, if we want to play F major and G major chords, we can just play A-C interval and G major chord, or F major chord and G-D interval, and to my musically untrained ears, those compromises sound almost as good as the two full chords. And, whatever the disadvantages are harmony-wise, in pentatonic it's even worse, right?
Are there any practical or historical reasons why the 122322 scale is so little-known, while the two nearest neighbors 22323 and 1221222 are in wide use? Does it have something to do with the fact that 5 and 7 are prime numbers while 6 is not? Does it have something to do with the history of musical instruments?
Or IS hexatonic little-known? I do not have much music background, only took a couple of music theory and harmony classes at the uni, so maybe I am mistaken and the hexatonic scale is actually more widely used than I think? Do you know any pieces that use this scale? (Especially folk melodies, early music or classical compositions.)
Comment: I've often wondered this myself. I get the impression that hexatonic tunes are sometimes justviewed as diatonic tunes that just happen to not be using one of the notes.
Comment: I did not mean just any hexatonic scale. The title was not very good or precise; however, in the second paragraph of the post I explain which hexatonic scale I mean. (The one that can be generated with a chain of perfect fifths.) I edited the title to be more specific now.
Comment: Interesting that you consider not having tritones in the music as an advantage. I know plenty of jazz musicians who'd balk at that. But seriously, a lot of the beauty of harmony comes from the use of tritones in various forms.
Comment: The blues scale is a hexatonic scale, isn't it?
Answer: The premise isn't really true, since such hexatonic scales are actually very common in folk and country music. In particular, the "missing ⅶ scale" 221223. An important source are Scottish tunes, e.g.
X:1
T:The Athole Highlanders
L:1/16
M:6/8
K:D
V:2 clef=treble
|: A6 A3FD2 | A3FD2 E3FG2 | A6 A3FD2 | E3FG2 F3ED2 |
A6 A3FD2 | A3FD2 E3FG2 | Ad3A2 B3AG2 | F3GE2 D6 :|
%

Celtic music is strongly dominated by a single melody, which is often mostly pentatonic but adds in the remaining diatonic notes occasionally.
This tendency to keep a lot to the major pentatonic (as well as the Blues one, though that is actually quite different) has had a lot of influence on American Folk and through that on country, rock and pop music. However, those genres have much more emphasis on a chordal accompaniment, using the Ⅰ and Ⅳ chords most often, so country can hardly be called pentatonic. Hexatonic it is.
The situation is very different in classical music. This too is dominated by melodies, but there is a fundamentally different approach. Whereas Celtic music likes a "constant floating feeling", classical music is all about building up, constructing cadences that have clear resolutions. And the most powerful melodic resolution is the ⅶ-Ⅰ step, which is therefore all over classical music.
But even classical music may use hexatonic scales, in particular when going for a folky feel. But it's usually limited to short motifs:
X:1
T:Sinfonie No. 6, "Pastorale"
C:Ludwig van Beethoven
Q:"1: All. ma non troppo"
L:1/8
M:2/4
K:F
V:2 clef=treble
z .A.B.d | (cB/2A/2 .G).C | .F.G (AB/2A/2) | .G.A (Bc/2B/2) | Accc | c2
%

A bit longer:
X:1
T:Finlandia
C:Jean Sibelius
L:1/4
M:C
K:Ab
V:2 clef=treble
z (c B c) | (d3 c) | (B c A z/2 B/2) | B (c3 | c) (c B c) | (d3 c) |
(B c A z/2 B/2) | (c4 | c) ( !tenuto! e !tenuto! e !tenuto! e) |
(f3 c) | (c e) (e3/2 B) | B (d3 | d) ( !tenuto! d !tenuto! c !tenuto! B) |
(c3 A) | A (B2 z/2 A/2) | A
%

I'm a little hesitant about that example, because the theme doesn't span an entire octave, and it's homophonically harmonised with voices that do include the G note. So it might well be argued that it's actually heptatonic but simply keeps in a small range of the scale.
A hexatonic mode that's rather more natural for classical music is the "missing Ⅳ" 223221 scale. A prime example of this is the gorgeous Andante Maestoso from Holst's Planets:
X:1
T:Jupiter, the Bringer of Jollity
C:Gustav Holst
L:1/8
M:3/4
K:Eb
V:2 clef=treble
z4 G,B, | C2 (CE) (D3/2B,/2) | EF E2 D2 | CD C2 B,2 | G,4 G,B, |
C (CE) (D3/2B,/2) | EF G2 G2 | (GF E2) F2 | E4 (BG) |
F2 F2 EG | (F2 B,2) BG | F2 F2 GB | c4 cd | e2 d2 c2 | B2 e2 G2 |
FE F2 G2 | B4
%

Comment: Wonderful answer; I'd never caught that the Holst here is missing that fourth scale degree. Can you think of any other examples?
Comment: Thank you for the thorough answer and the examples! "Finlandia" really sounds so... special and different. I'd never looked at the sheet music before, only listened. Maybe the hexatonic scale is one of the reasons why this tune is so fascinating... By the way, in the meantime I looked around for examples and found another one. "Oh Susanna" begins as a pentatonic tune but the beginning of the chorus throws in the sixth note. It turns out that this hexatonic scale is around more than I suspected :D
Comment: @Liisi yeah, in country stuff like Oh Susanna it really is the go-to scale.
Comment: Maybe that's why those hexatonic scales are so little-known (or so rarely acknowledged as such)--I've always thought that Andante Maestoso from Jupiter from The Planets was in E flat major with no bells and no whistles.
Comment: @Dekkadeci then you clearly haven't heard [this version yet](https://www.youtube.com/watch?v=lraMso3qa5g)!
Answer: It should also perhaps be mentioned that the hexatonic scale derived from a chain of perfect fifths is probably not often found, because Pythagorean thirds sound so bad.  And in the hexatonic scales derived from removing the second note of the major scale (CEFGAB), you can have two chains of perfect fifths, F C G and A E B, with A and G separated by 10/9 (rather than the 9/8 demanded by a continual single chain), and all thirds are also perfect. Sounds much better.
(this is just a parenthetical answer for just intonation freaks)


How to set up a p-value based significance testing (example experiment is given)

Question: I am a software engineer performing a real-life A/B test, and I wanted to use conventional statistical tools to make sure my results were statistically significant. I have some basic textbook knowledge of p-values but have rarely used them in real world applications.
Let's say I have two different blackbox methods of creating a cookie, namely Method A and Method B. Both methods produce cookies at a rate of 1 cookie / 1 second. In both methods, the baked cookie can be either Acceptable quality or Defective quality.
I let Method A and Method B running for 1 week.
For Method A, out of 25200 cookies, 10000 were Acceptable, which means the success ratio for this method is 10000/25200 = 39.68%.
For Method B, out of 25200 cookies, 9000 were Acceptable, which would yield success ratio of 9000/25200=35.71%.
It seems like Method A is better than Method B by a whooping 3.97%, but before I rush to conclusions, how would I compute my p-value?
Answer: You are comparing two proportions. A basic test of difference between two proportions should work.
https://www.statisticshowto.com/probability-and-statistics/hypothesis-testing/z-test/
Answer: There are several versions of this test, essentially using
a normal approximation. Some use a continuity correction
(declined below on account of large sample sizes), and
some use a pooled standard error for the difference in
the two estimates of proportions (others find standard errors
separately). The version implemented in R (shown below)
is equivalent to doing a chi-squared test on a $2 \times 2$
table of successes and failures for the two methods.
For your suggested data the P-value of the two-sided test
is $0.029,$ so you could claim significance at level $2\%.$
<code>prop.test(c(1000,900), c(25200, 25200), cor=F)

    2-sample test for equality of proportions
    without continuity correction

data:  c(1000, 900) out of c(25200, 25200)
X-squared = 5.4693, df = 1, p-value = 0.01935
alternative hypothesis: two.sided
95 percent confidence interval:
  0.0006427583 0.0072937496
sample estimates:
    prop 1     prop 2
0.03968254 0.03571429
</code>


How do you get equals() working with Hibernate entities when lazy=true?

Question: For some reason when lazy=true on all my entities, the equals() method does not work correctly when one side is a lazily-loaded entity and the other side is a normal entity. Here's an example:
if(activeTask.getTask().equals(task)) {...}

In this case, the activeTask's task will be a proxy while the right side will be a regular one. The equals() will fail. To fix this problem, I often do things like this:
if(activeTask.getTask().getId() == task.getId()) {...}

This works, but it's not ideal. I'd rather use my equals() method.
Does anyone have a nice solution to this problem? It really adds to the application's level of noise to have to think about stuff like this.
If I say lazy=false, I don't have to deal with proxy's, and so equals() will work. But this has a very negative impact on performance.
It is just not cool to have to say, "equals() works in all cases, except when you use proxies... then equals() is not reliable."
Comment: It is 2018. I'm using Hibernate 5.2 and still seeing the same error. I solved it by disabling lazy as you mentioned. The other workarounds seem a bit fragile. Also, I don't want to overload .equals() with a ton of logic.
Comment: Hava a look here: https://jpa-buddy.com/blog/hopefully-the-final-article-about-equals-and-hashcode-for-jpa-entities-with-db-generated-ids/
Answer: I realize this is an old question, but it's still unanswered and people might stumble upon it.
I had the same problem a few days ago. In the project we use an abstract base class BasicEntityType, which has just an ID and equals is implemented in said base class:
@Override
public final boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }

    if (obj == null) {
        return false;
    }

    Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
    if (this.getClass() != objClass) {
        return false;
    }

    if (id == null) {
        return false;
    }

    return id.equals(((BasicEntityType) obj).getId());
}

There are two critical parts in this code:

First: Do not check directly for class equality, it might not work with the given object.
Second: All properties of the given object have to be accessed by using methods. Or you could unwrap the actual object.
Comment: You should not use the database ID in equals and hashcode when using hibernate. See http://docs.jboss.org/hibernate/core/4.0/manual/en-US/html/persistent-classes.html#persistent-classes-equalshashcode
Comment: HibernateProxyHelper.getClassWithoutInitializingProxy(obj) doesn't work with inheritance because it calls to org.hibernate.proxy.LazyInitializer.getPersistentClass() instead of org.hibernate.proxy.LazyInitializer.getImplementation()


Memory Issues in developing Android App

Question: I am presently trying to develop an Image Processing based app for android mobiles using Eclipse. My app consists of several buttons and sub-menu buttons as well. I am trying to make it universal(so that it can run on any resolutions) using switch case for the different resolutions, and thereby different resources for different resolutions. The problem is, I am encountering memory overload problems. It runs fine on Xperia U, but not on Galaxy S, and also crashes in the Emulator. I haven't used XMl for my app, and have designed the entire UI programmatically. Please advice me on how to solve this problem. Any help will be highly appreciated. Thanks in advance!
Answer: Well, the question sis very general but here are some points that might help:

Designing everything programmatically means your app will be slow and will create everything on runtime. It is not using the design optimization of Android UI by not using XML.
What context are you using in order to create UI objects. If you are tying the UI objects to the apps context rather than activities' context, all the components of UI will remain in memory unless the app is killed. Unlike in activity as soon as the activity is destroyed all its UI components are killed.
You could use XMl inflator in order to reduce work in Java, by reusing components created in XML . This will help you optimize some sub components that you are using repetitively.

Memory Issues in developing Android App


Google+ Plus API for Insights

Question: I am wanting to get via the Google API the details on the insights for my google+ page. As it stands, I can't seem to find anything on it.
Cheers
Comment: The google+ API doesn't support pages.
Answer: There is an open feature request: Read insights data from Google+ Dashboard. Star the issue to get updates.

Google+ Plus API for Insights


BIND split-view DNS config problem

Question: We have two DNS servers: one external server controlled by our ISP and one internal server controlled by us. I'd like internal requests for foo.example.com to map to 192.168.100.5 and external requests continue to map to 126.96.36.199, so I'm trying to configure a view in bind. Unfortunately, bind fails when I attempt to reload the configuration. I'm sure I'm missing something simple, but I can't figure out what it is.
options {
        directory "/var/cache/bind";
        forwarders {
         188.8.131.52;
         220.127.116.11;
        };
        auth-nxdomain no;    # conform to RFC1035
        listen-on-v6 { any; };
};
zone "." {
        type hint;
        file "/etc/bind/db.root";
};
zone "localhost" {
        type master;
        file "/etc/bind/db.local";
};
zone "127.in-addr.arpa" {
        type master;
        file "/etc/bind/db.127";
};
zone "0.in-addr.arpa" {
        type master;
        file "/etc/bind/db.0";
};
zone "255.in-addr.arpa" {
        type master;
        file "/etc/bind/db.255";
};
view "internal" {
      zone "example.com" {
              type master;
              notify no;
              file "/etc/bind/db.example.com";
      };
};
zone "example.corp" {
        type master;
        file "/etc/bind/db.example.corp";
};
zone "100.168.192.in-addr.arpa" {
        type master;
        notify no;
        file "/etc/bind/db.192";
};

I have excluded the entries in the view for allow-recursion and recursion in an attempt to simplify the configuration. If I remove the view and just load the example.com zone directly, it works fine.
Any advice on what I might be missing?
Answer: First, check your logs, but I think you forget
acl "lan_hosts" {
    192.168.0.0/24;             # network address of your local LAN
    127.0.0.1;              # allow loop back
};
view "internal" {
        match-clients { lan_hosts; };
[...]
};

Comment: In that case how are you differentiating who views what?
Comment: Actually, match-clients is not required. From http://www.zytrax.com/books/dns/ch7/view.html, "If either or both of match-clients and match-destinations are missing they default to any (all hosts match)."
Answer: Post the results of named.
Comment: Huh. Didn't know about "named-checkconf" until now:

# named-checkconf
/etc/bind/named.conf:12: when using 'view' statements, all zones must be in views

BIND split-view DNS config problem


use implicit differentiation to find $\partial z/\partial x$, $\partial z/\partial y$

Question:
I can't find the word implicit differentiation anywhere in the book, but I'm assuming it means solve for $z$ in this case and differentiate with respect to $x$, then $y$ in this problem. But when I took the derivative with respect to $x$ of 47 after solving for $z$, i get a different answer.
I got $$z = \dfrac{\sqrt{-x^2-2y^2+1}}{\sqrt{3}}$$
and for the derivative of that:
$$-\dfrac{x}{\sqrt{3}\sqrt{-x^2-2y^2+1}}$$
(i got these results on https://www.derivative-calculator.net/)
this is different than the answer in the book. am i not supposed to solve for $z$ and differentiate with respect to $x$ then $y$? Is this another form of the answer? help..
the answer is $-x/3z$ ... which I don't get..
Comment: In the future, @2316354654, you need to enclose your LaTeX commands in \$ for inline maths, and \$\$ for inset equations. Cheers!
Comment: `I can't find the word implicit differentiation anywhere in the book.` I'm afraid you also need to work on your reading skills. These exercises come from page 925 of Stewart's "Calculus: Early Transcendentals", 8th edition. Now check Example 5 on page 917... (Not to mention the entire section 3.5 titled "Implicit Differentiation".)
Answer: I am afraid that this is not the way to do it.
Consider the implicit function $$F=x^2+2y^2+3z^2-1=0$$ and consider the partial derivatives $$\frac{\partial F}{\partial x}=2x\qquad \frac{\partial F}{\partial y}=4y\qquad\frac{\partial F}{\partial z}=6z\qquad $$ and now use, from the implicit function theorem, $$\frac{\partial z}{\partial x}=-\frac{\frac{\partial F}{\partial x}}{\frac{\partial F}{\partial z} }\qquad\qquad \frac{\partial z}{\partial y}=-\frac{\frac{\partial F}{\partial y}}{\frac{\partial F}{\partial z} }$$
Comment: im not afraid.. because that way is much easier! :D
Answer: Solving for $z$ and then differentiating would be an explicit method.  Instead, you can differentiate a function of three variables while treating $z$ to be a function of $x$ and $y$, then solving for $\frac{\partial z}{\partial x}$ and $\frac{\partial z}{\partial y}$.
For instance, if $x+y^2 + z^3 = 0$, then the derivative of the left-hand side with respect to $x$ would be $1 + 3z^2 \frac{\partial z}{\partial x} = 0$.  Thus $\frac{\partial z}{\partial x} = -\frac{1}{3z^2}$.
In general, given $f(x,y,z) = c$, the derivative of the left-hand side with respect to $x$, treating $z$ as if it were a function of $x$ and $y$, would be
$\frac{\partial f}{\partial x} + \frac{\partial f}{\partial z} \frac{\partial z}{\partial x}$.  Thus
$$
    \frac{\partial z}{\partial x} = - \frac{\partial f/\partial x}{\partial f/\partial z}
$$


How does one show that $\sum_{n=0}^{\infty}\left(-{1\over x}\right)^n\cdot{\Gamma\left({2n+1\over 2}\right)\over n!}=\sqrt{{x\pi\over x+1}}?$

Question: Consider $(1)$

$$\sum_{n=0}^{\infty}\left(-{1\over x}\right)^n\cdot{\Gamma\left({2n+1\over 2}\right)\over n!}=S\tag1$$
  $x>0$
How does one show that $S=\sqrt{{x\pi\over x+1}}$

An attempt:
$$\Gamma\left({1\over 2}+n\right)={(2n-1)!!\sqrt{\pi}\over 2^n}$$
$(1)$ becomes
$$\sum_{n=0}^{\infty}\left(-{1\over x}\right)^n\cdot{(2n-1)!!\over 2^n}\cdot{1\over n!}=\sqrt{x\over x+1}\tag2$$
further to
$$\sum_{n=0}^{\infty}\left(-{1\over x}\right)^n\cdot{1\over 2^n(2n-2)!!}=\sqrt{x\over x+1}\tag3$$
Answer: We wish to calculate ($x>1$)

$$
S=\sum_{n\geq0}\frac{(-1/x)^n}{n!}\Gamma(n+1/2)
$$

we have that $\Gamma(n+1/2)=\int_0^{\infty} t^{n-1/2}e^{-t}dt$
so

$$
S=\int_0^{\infty}dte^{-t}t^{-1/2}\sum_{n\geq 0}\frac{(-t/x)^n}{n!}=\int_0^{\infty}dte^{-t(1+1/x)}t^{-1/2}=\frac{\sqrt{\pi x}}{\sqrt{1+x}}
$$

the interchange of sum and integral is justified since $\int_0^{\infty}e^{-t}t^z$ converges absolutly for any $z>-1$ and the last integral can be turned into a simple Gaussian one via $t\rightarrow t^2$

note the non obvious limit $\lim_{x\rightarrow\infty} S(x)=\sqrt{\pi}$
Comment: Succinct and complete!  Well done.  (+1)
Comment: Great approach!
Comment: "Succinct" i learned a new english word...thanks!
Comment: .... Prego!  ...
Answer: We note that
$$\frac{\Gamma \left ( n+\frac12 \right )}{\Gamma \left ( n+1 \right )} = \frac1{\sqrt{\pi}} \int_0^1 dy \, y^{-1/2} (1-y)^{n-1/2} $$
Then
$$\begin{align}\sum_{n=0}^{\infty} \frac{\Gamma \left ( n+\frac12 \right )}{\Gamma \left ( n+1 \right )} w^n &= \frac1{\sqrt{\pi}} \int_0^1 dy \, y^{-1/2} (1-y)^{-1/2} \sum_{n=0}^{\infty} [(1-y) w]^n \\ &= \frac1{\sqrt{\pi}} \int_0^1 dy \, \frac{y^{-1/2} (1-y)^{-1/2}}{1-w (1-y)} \\ &= \frac{2}{\sqrt{\pi}} \int_0^1 dy \frac{(1-y^2)^{-1/2}}{1-w (1-y^2)} \\ &= \frac1{2 \sqrt{\pi}} \int_0^{2 \pi} \frac{d\theta}{1-w \sin^2{\theta}} \end{align}$$
where we assume that $|w| \lt 1$.  That last integral may be performed any number of ways, e.g., extension to the complex plane and the residue theorem.  The result is $2 \pi/\sqrt{1-w}$.  Thus,
$$S = \sqrt{\frac{\pi}{1+\frac1{x}}} = \sqrt{\frac{\pi x}{x+1}} $$
ADDENDUM
Let's illustrate how to do that last integral.
$$\int_0^{2 \pi} \frac{d\theta}{1-w \sin^2{\theta}} = 2 \int_0^{\pi} \frac{d\theta}{1-w \sin^2{\theta}} =  2 \int_0^{\pi} \frac{d\theta}{1-w/2 + (w/2) \cos{2 \theta}} = \int_0^{2 \pi}\frac{d\theta}{1-w/2+(w/2) \cos{\theta}}$$
The above manipulations serve to show how to reduce a potentially messy problem into one a lot less messy.  In this case, we have reduced the number of poles in the complex plane from four to two.
Now express as a complex integral using $z=e^{i \theta}$; the integral is equal to
$$-i 2 \oint_{|z|=1} \frac{dz}{(w/2) z^2 + (2-w) z+(w/2)} $$
The poles of the integrand are at $z_{\pm}=[-(2-w) \pm 2 \sqrt{1-w}]/w$, and the only pole inside the unit circle is $z_+$.  Thus, by the residue theorem, the integral is equal to $i 2 \pi$ times the residue at that pole, the residue being equal to $1/(2 \sqrt{1-w})$.  Thus the integral is equal to $2 \pi/\sqrt{1-w}$ as asserted.
Comment: well done! (+1) nice use of the beta integral
Comment: Ron, nice use of the Beta function and successive substitutions.  (+1) And nice to see you're still here!  -Mark
Comment: @Dr.MV: Thanks Mark. I never left.   I still lurk but I am hardly in a place to keep my former pace.  Nice to see you guys producing quality answers.
Comment: Thanks Ron ... still trying to fill your large shoes from time to time.
Answer: $$
\sum_{n=0}^\infty \left(-\frac{1}{x}\right)^n\frac{1}{n!}\frac{1}{4^n}\frac{(2n)!}{n!}\sqrt{\pi} = \sum_{n=0}^\infty \left(-\frac{1}{4x}\right)^n\frac{(2n)!}{(n!)^2}\sqrt{\pi} = \sum_{n=0}^\infty \left(-\frac{1}{4x}\right)^n\left(\matrix{2n\\n}\right)\sqrt{\pi}
$$
the final is of the form
$$
\sum_{k=0}^\infty \left(\matrix{2k\\k}\right)z^k = \frac{1}{\sqrt{1-4z}}\;\;\text{iff}\;\; |z| <1/4
$$
(see wiki)
if we have
$$
\left|\frac{1}{-4x}\right| =\left|\frac{1}{4x}\right|  < \frac{1}{4}
$$
then we have
$$
\sum_{n=0}^\infty \left(-\frac{1}{4x}\right)^n\left(\matrix{2n\\n}\right)\sqrt{\pi} = \frac{1}{\sqrt{1-4\frac{1}{-4x}}}\sqrt{\pi}= \sqrt{\frac{x\pi}{1+x}}
$$
Comment: @Dr.MV Cheers Mark!
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\sum_{n = 0}^{\infty}\pars{-\,{1 \over x}}^{n}\,
{\Gamma\pars{\bracks{2n + 1}/2}\over n!} =
\pars{-\,{1 \over 2}}!\sum_{n = 0}^{\infty}
{n - 1/2 \choose n}\pars{-\,{1 \over x}}^{n}
\\[5mm] = &\
\root{\pi}\sum_{n = 0}^{\infty}\underbrace{\bracks{{- 1/2 \choose n}\pars{-1}^{n}}}_{\ds{\underbrace{=\ {n - 1/2 \choose n}}_{\ds{\mbox{Negating Property}}}}}\ \pars{-\,{1 \over x}}^{n} =
\root{\pi}\sum_{n = 0}^{\infty}{-1/2 \choose n}\pars{1 \over x}^{n}
\\[5mm] = &\
\root{\pi}\pars{1 + {1 \over x}}^{-1/2} =
\bbx{\ds{\root{\pi x \over x + 1}}}\,,\qquad\qquad \verts{x} > 1.
\end{align}
Answer: We may also prove this by working backwards from the integral $\int_0^\infty\frac{t^{x-1}}{(1+t)^{x+y}}dt=\frac{\Gamma(x)\Gamma(y)}{\Gamma(x+y)}$ and applying Ramanujan's master theorem.
We start with the following integral:
$$\begin{align*}
\int_0^\infty\sqrt{\frac{\pi/t}{1+1/t}}t^{s-1}dt &=\sqrt{\pi}\int_0^\infty\frac{u^{-s-1/2}}{(1+u)^{1/2}}du,\;\;t=u^{-1} \\
 &=\sqrt{\pi}\int_0^\infty\frac{u^{1/2-s-1}}{(1+u)^{1/2-s+s}}du \\
 &=\Gamma(1/2-s)\Gamma(s),\;\;0<\Re [s]<1/2.
\end{align*}$$
Which implies that $\phi(s)=\Gamma(1/2+s)$. So we then have
$$\begin{align*}\sqrt{\frac{\pi/t}{1+1/t}}&=\sum_{n=0}^\infty\frac{\phi(n)}{n!}(-t)^n\\
&=\sum_{n=0}^\infty\frac{\Gamma(1/2+n)}{n!}(-t)^n,\;\;|t|<1.
\end{align*}
$$
Replacing $t$ with $1/t$ yields your sum.


Conventions for defining inductive base case

Question: I was reading a problem that stated:

There are a certain number of objects all of which have the same
weight except for one which has a different weight. In all other
aspects the objects are identical. Determine the unique one that has
the different weight using a pair of scales optimally. Show by induction on $n$ that at most $2*n$ comparisons are needed to identify the object when the total number of objects is $3^n$

My original thought was that the base case has to be $n = 1$ where we have a total of $3^1$ objects which we can figure out the one we are searching for with 2 comparisons.
But the solution uses as base case $n = 0$ considering in that case that the $3^0 = 1$ object is the one we are searching for. I originally rejected $n = 0 $ as base case because with $1$ object we can't do any comparison so we can't know if it is the one we search for or not.
So my question is: how do we determine in such cases how do we treat the base case? Could we also not have considered that for $n = 0$ the $1$ coin can not be the one we are searching for? Or even that as I originally thought that it is not meaningful to use $n = 0$ as base case?
Is there something in the problems we need to be cautious of, or some convention that exists that helps define the base case?
In this particular problem, it makes me think that there is some subtle implication that the specific unique object under search must be part of the set even if all the rest are missing which I did not pick up.
Is that so? Is there some convention for inductive approaches?
Answer: You use whatever works for your base case, then carefully state what you have proved.  If you use $n=1$ as your base case, you have not proved the $n=0$ case.  You would have to state your result as "For all numbers of objects $n \ge 1$, it takes at most $2n$ comparisons ..."
If I were doing the proof, I would probably start with $n=1$.  Having done it, I would think about $n=0$ for completeness and prove the $n=0$ case separately.  I would wind up proving $n=0$ and $n=1$ directly, then using induction for everything above $1$.  The case of $n=0$ is often different and it can be easier to make the induction work starting from $n=1$.
The base case can be higher yet.  One we see here is to prove $n! \gt n^2$ for $n \ge 4$.  We can note that the statement is not true for $n=3$ as $3!=6 \not \gt 3^2=9$.  You use $4$ as the base case and the induction goes through nicely.
Comment: Yes, an English question refers to one where the important thing is how you interpret the problem statement.  You raised the possibility that the question does not make sense for less than $3$ coins and on rereading the question I agree.  Often problems are not clear about edge cases like this.  In this case I suspect the problem writer was only thinking about large enough $n$, which turns out to be $3$ or more, and did not specify what happens for the smallest $n$.
Comment: What about the statement that if there is only $1$ object in the set it is considered as the one we are searching for? Couldn't we equally claim that it is *not* the one we are looking for? The confusing part to me here is where the confidence for the claim comes from.
Comment: From that point of view you could refuse to do the $n=0,1,2$ cases as the answer is not defined.  You could then use $n=3$ for your base case and show that you can succeed with $2$ comparisons.
Comment: So is it a matter of how we define it and both approaches (base case is $n = 0$ or base case $n > 2$) are considered correct as long as they explicitly state the logic? I am trying to think of the problem also in terms of a computer program where we would have a collection with 1 element. Is there any kind of hint or math convention that would bias returning as found the element having as input a collection with 1 item (same as the problem solution is treating it)?
Comment: Yes.  It is more an English question whether you accept the cases $0$ through $2$.
Comment: By an "English question" is how one understand the problem statement? In this specific problem statement in the post, does the way that it is phrased gives hint about one approach or another for the base case?
Comment: I just want to make sure that I am not missing something in the way to read the problem(s)
Comment: I have another question about induction if by any chance you have some spare time to check. Any help is highly appreciated https://math.stackexchange.com/questions/3987470/wrong-naive-inductive-hypothesis-and-tower-of-hanoi-as-an-example