Did I solve $z^{n-1}=\overline{z}$ correctly?

Question:
Please could someone tell me if my solution of $z^{n-1}=\overline{z}$
  is correct?

My solution:
We have $z^{n-1} =\overline{z}$ if and only if $z^{n-1}z =\overline{z}z$, so
$z^n = |z|^2$
In polar coordinates,
$$ r^n e^{i n \varphi}  = r^2$$
or, equivalently,
$$ r^{n-2} e^{i n \varphi}  = 1$$
This equation implies that $r=1$. Hence we are taking $n$-th roots of $1$:
$$e^{i n \varphi}  = 1$$
So the resulting set is a discrete and finite subset of the unit circle (consisting of the $n$-th roots of $1$).
Comment: What about  $n=2$?
Comment: What about $z=0$?
Comment: could you please add more information, like where is n?
Comment: @leonbloy $r$ is a radius in polar coordinates, assumed to be nonnegative.
Answer: I assume $n$ stands for a positive integer.
If $n=1$, the equation is $1=\bar{z}$.
If $n=2$, the equation is $z=\bar{z}$, so any real number is a solution.
Suppose $n>2$. First of all, $z=0$ is a solution. Assume now $z\ne0$ and write it as $z=re^{i\varphi}$. The equation becomes
$$
r^{n-1}e^{i(n-1)\varphi}=re^{-i\varphi}
$$
Since $r>0$, we can write it as
$$
r^{n-2}e^{in\varphi}=1
$$
Since $n>2$, we get $r=1$ and $e^{in\varphi}=1$, so the $n$-th roots of unity are the solutions.

If $n$ is allowed to be any integer, the case $n=0$ becomes $z\bar{z}=1$, so any complex number of modulus $1$ is a solution.
If $n<0$, write $w=1/z$ and $m=-n$, so the equation becomes
$$
\frac{1}{w^{m+1}}=\frac{1}{\bar{w}}
$$
or
$$
w^{m+1}=\bar{w}
$$
and we're in the same situation as before with $n>2$ (but, of course, the solution $0$ cannot be considered).
Comment: Z=0 works iff n is not 1, right?
Comment: @Ron Yes, I'll fix. Thanks.


How to use $_GET in wordpress pages

Question: Here's the thing...
I have created a button which on click opens a link like
 https://www.something.com/something/?term=something

or [at first, I thought this is a URL problem... so I tried some other] Like:-
 https://www.something.com/something.php?term=something
 https://www.something.com/something?term=something

and else
now on this link, I want to echo $_GET['term']... which not happening, there is no error in the console... how to be able to echo it
I know the answer is in this document but I don't know how to use this thing... can anyone please describe the right way step by step...
    https://codex.wordpress.org/Function_Reference/get_query_var
Comment: `echo $_GET['term']` will always work.
Comment: Is your intention to go through Wordpress routing or to directly access a php file in your server?
Answer: get_query_arg : Retrieve only public query variable in the WP_Query class of the global $wp_query object.
I propose for security , use rewrite class in Wordpress :
/**
 * Add rewrite tags and rules
 *
 * @link https://codex.wordpress.org/Rewrite_API/add_rewrite_tag
 * @link https://codex.wordpress.org/Rewrite_API/add_rewrite_rule
 */
/**
 * Add rewrite tags and rules
 */
function myplugin_rewrite_tag_rule() {
    add_rewrite_tag( '%city%', '([^&]+)' );
    add_rewrite_rule( '^city/([^/]*)/?', 'index.php?city=$matches[1]','top' );
}
add_action('init', 'myplugin_rewrite_tag_rule', 10, 0);

for add to query arg :
/**
 * Register custom query vars
 *
 * @param array $vars The array of available query variables
 *
 * @link https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars
 */
function myplugin_register_query_vars( $vars ) {
    $vars[] = 'city';
    return $vars;
}
add_filter( 'query_vars', 'myplugin_register_query_vars' );

example link in site : yoursite.com/city/45
get data in wordpress :
$city = get_query_var( 'city' );
echo $city;

Comment: didnt worked.... i pasted the function in function.php and get_query_war in main page...plz help
Comment: you must flush rewrite after copy this code.go to setting -> permalink and click to save button.
Answer: That's quite simple
echo get_query_var( 'term', 'default_value');

Obviously you have to add this in functions.php for custom variables
function add_query_vars_filter( $vars ) {
  $vars[] = "my_var";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

read further details here
Comment: Dont forget you have to register custom query vars as mentioned by Mehrsahd in his answer
Comment: I have added the above code in the main page... and the second code in my theme's function.php but it is echoing "default_value".
Comment: @user10280601 replace my_var value with your query string variable and also value "term" in this line get_query_var( 'term', 'default_value');  with your query string variable. and default_value is optional parameter in this function to show something default if query string variable not found so you can set it what you want.
Comment: @AshfaqAhmed I have already done it but it still echoes "default value"
Comment: @KaiQing i have done what you told.... first code in function.php and second in the normal page but it is echoing "default value"

How to use $_GET in wordpress pages


How to show the trace relation: $\text{Tr} [A\not x A ^{\dagger} \not x]\geq0$

Question: A speaker from a talk/lecture I attended recently quoted the following inequality without proof, and for no good reason I have taken it upon myself to prove it:

Let $A\in SL(2,\mathbb{C})$, so $\det\left(A\right) = 1$. Also, let $\not x \equiv x^\mu \sigma_\mu$ where $x^\mu=(x^0,x^1,x^2,x^3)$ is an arbitrary real-valued four-vector (tuple of 4 real numbers) and $\sigma_\mu=(\sigma_0,\sigma_1,\sigma_2,\sigma_3)$ are the usual Pauli matrices with:
$$\begin{align}
\sigma_0&=-\begin{pmatrix}1 & 0 \\ 0 & 1 \end{pmatrix}\\
&\\
\sigma_1=\sigma_x\hspace{0.7cm}\,\,\,\sigma_2&=\sigma_y\hspace{1cm}\,\,\,\sigma_3=\sigma_z
\end{align}
$$
I would like to prove the following harmless looking inequality:
$$\text{Tr} [A\not x A ^{\dagger}\not x]\geq0$$

My progress:
I know that the trace is definitely real, and so the inequality is well-defined:
$$\begin{align}
\text{Tr}[A\not x A ^{\dagger}\not x]^*&=\text{Tr}[(A\not x A ^{\dagger} \not x )^\dagger]\\
&=\text{Tr}[(\not x )^{\dagger}(A^{\dagger})^{\dagger}(\not x )^{\dagger}(A)^{\dagger}]\\
&=\text{Tr}[\not x A \not x A ^{\dagger} ]\\
&=\text{Tr}[A\not x A ^{\dagger} \not x]
\end{align}$$
Honestly, apart from this I don't know what I could do. Hints and/or suggestions would be much appreciated.
Answer: Let $x=\sigma_3$, $A=\mathrm{i}\sigma_2$. Then $\det A = 1$, so $A\in\mathrm{SL}_2\mathbb{C}$. Nevertheless
$$\begin{split}AxA^{\dagger}x&=(\mathrm{i}\sigma_2)\sigma_3(\mathrm{i}\sigma_2)^{\dagger}\sigma_3\\
&=\sigma_2\sigma_3\sigma_2\sigma_3\\
&=-\sigma_2^2\sigma_3^2\\
&=\sigma_0\end{split}$$
whence
$$\mathrm{Tr}\,AxA^{\dagger}x=-2\text{.}$$
Comment: It's true when $x$ is a positive-semidefinite (psd) matrix, which is the case whenever $x^{\mu}$ is a spacelike or lightlike vector. For then $x$ has a psd square root $y$ and the trace is of the form $\mathrm{Tr}\,B B^{\dagger}$ where $B= y  A y$.
Comment: "..which is the case whenever $x^\mu$ is a spacelike or lightlike vector." how did you arrive at this? And what convention are you using when you say "spacelike"? I think the 4-vector $x^\mu=(0,0,0,1)$ is definitely spacelike, but you have shown that the trace is negative with that choice.
Comment: Thanks, clearly the inequality is false. I'm thinking now, should the inequality sign be reversed, or is any such inequality invalid?
Comment: Sorry, I was hasty and mixed up spacelike and timelike :/. By direct diagonalization, the eigenvalues of $x$ are $-x^0 \pm \sqrt{(x^1)^2+(x^2)^2+(x^3)^2}$. For $x$ to be psd, we need the eigenvalues to both be nonnegative, whence $x^0\leq 0$ and $\lvert x^0\rvert\geq \sqrt{(x^1)^2+(x^2)^2+(x^3)^2}$—a timelike vector.


Parameters are supposed to be distinct within a set of independent but not identically distributed random variables?

Question:
I'm confused here with one thing: If $(X_1,...,X_n)$ is not idenctically distributed, then doesn't this mean that the $\theta$'s are supposed to have subscripts $i$ in the pdf given above? I mean the $\theta$'s are not the same. Am I correct or?
Answer: The $\theta's$ are the same, but the $c_i's$ are not.  The fact that each $X_i$ has its own $c_i$ is what makes the distributions not (necessarily) identical.


SQL Server Integrated Authentication on Weblogic Server

Question: I'm developing a web application that accesses data on MS SQL Server 2012. My company's production environment already has connections to the database set up using SQL Server Authentication. My Active Directory account does not include SQL Server authentication, and we use Integrated Authentication when we are developing on our local machines. I am testing my application by deploying it to a local instance of Weblogic 10.3.4.
I am receiving this exception when attempting to create the connection pool on the Administration Console:
<code><Error> <Console> <BEA-240003> <Console encountered the following error com.microsoft.sqlserver.jdbc.SQLServerException: This driver is not configured for integrated authentication.
</code>
I've added sqljdbc_auth.dll to the classpath on the server, and added:
<code>-Djava.library.path=C:\programdata\Oracle\WebLogicServer\10.3.4\user_projects\domains\JDEV\lib
</code>
to my server start arguments in the Environment -> Server Start tab on the management console, but there is still something wrong.
Any help will be greatly appreciated!
Comment: Have you tried something like http://wmarkito.wordpress.com/2012/08/08/how-to-add-third-party-jdbc-drivers-on-weblogic-64/ to put the driver on your classpath? The example is for Linux but the files are more or less the same
Comment: @DisplayNameisMissing Thanks for your comment. I believe this article is trying to explain the absence of the driver in general, my problem here was that integrated authentication was not working correctly.
Answer: I found the problem. I believe that I did not have the sqljdbc_auth.dll in the correct location. It belongs in:
<code>%path%\WebLogicServer\10.3.4\wlserver_10.3\server\native\win\x64
</code>
Once I put this file in the correct location, the configuration worked right away.
It is also important to note that the version number on these files is very important. Make sure that your sqljdbc4.jar and sqljdbc_auth.dll versions are exactly the same, otherwise the container will blow up and you'll end up being frustrated like me.


Technical point about convergence with conditional expectation

Question: I have a sequence of non negative variables $X_n$ such as:
$$E(X_n|C_n)=\frac{C_n}{n^2}$$
where $C_n$ is a sequence of random variables converging almost surely to $1$.
Can I conclude $X_n$ tends to 0 almost surely?
Note: you can replace $\frac{1}{n^2}$ by any sequence with finite sum. The question remains essentially the same and the answer provided by Jason works just the same (see the Borel-Cantelli argument).
Answer: Yes, $X_{n} \to 0$ almost surely. The argument I have is a little convoluted, so bear with me.
First, consider the events $F_{k} = \bigcup_{n \geq k} \{ C_{n} > 2 \}$. By the almost sure convergence of the $C_{n}$ it follows that $P( \bigcap_{k} F_{k} ) = 0$, and since $F_{1} \supseteq F_{2} \supseteq \cdots$ we have $P(F_{k}) \to 0$. So it suffices to show that $X_{n} \to 0$ a.s. within $F_{k}^{c}$, for any $k$.
Now fix a $k$ and an $\varepsilon > 0$. Using the notation $E[X; A]$ to represent $E[X 1_{A}]$, we have for $n \geq k$
\begin{equation}
E[X_{n} ; F_{k}^{c}]
\leq E[X_{n} ; C_{n} \leq 2]
= E[ E(X_{n} | C_{n}) ; C_{n} \leq 2]
= E[ C_{n} / n^{2} ; C_{n} \leq 2 ]
\leq 2 / n^{2}.
\end{equation}
This is kind of the key part. (Note, too, that we used the nonnegativity of $X_{n}$ in the first step, to pass from $F_{k}^{c}$ to the larger event $C_{n} \leq 2$.) From here we just need some fairly run-of-the-mill measure theoretic arguments.
The bound above, together with the nonnegativity of $X_{n}$, implies that
$P(F_{k}^{c} \cap \{ X_{n} > \varepsilon \}) \leq \frac{2}{n^{2} \varepsilon}$ (for $n \geq k$), so that
\begin{equation}
\sum_{n \geq k} P(F_{k}^{c} \cap \{ X_{n} > \varepsilon \})
< \infty.
\end{equation}
By the Borel-Cantelli Lemma we can now say that the event
\begin{equation}
F_{k}^{c} \cap \{ X_{n} > \varepsilon \, \text{for infinitely many $n$} \}
\end{equation}
has probability zero. Since $\varepsilon$ was arbitary, this gets us $X_{n} \to 0$ a.s. on $F_{k}^{c}$.
Comment: This could be very slightly altered to show that for any exponent $\alpha$ on $n$ such that $\alpha > 1$, $X_n \to 0 \space \text{a.s.}$, it seems to me.
Comment: Thanks a lot. By $E(X;A)$ you mean $E(X|A)$ or $E(X1_A)$ ?
Comment: You mean $E(X1_A)$ :-) Maybe you should mention it. Everything seems correct to me, great!  Honestly, I don't think there is a simpler proof.
Comment: Right, Benoit, I meant $E(X 1_{A})$. I'll make an edit to clarify that.
Answer: Set $Z_n=X_n/C_n$. Then $E[Z_n]=1/n^2$ and $Z_n\ge 0$. By Markov's inequality,
$P(Z_n>\epsilon)\le E[Z_n]/\epsilon = 1/(n^2\epsilon)$ which has finite sum, so by Borel Cantelli, $P(Z_n>\epsilon \text{ infinitely often})=0$ and $Z_n\to 0$ almost surely.
If $Z_n\to0$ almost surely and $C_n\to 1$ almost surely then $X_n=Z_nC_n\to 0$ almost surely.


MySQL - INSERT INTO … ON DUPLICATE KEY UPDATE with values select from the same table

Question: I have two tables, one is posts(ID, edited_date, is_public, ... etc), another one is post_pagination(index, post_id) for storing the pagination data of posts. In post_pagination, index is primary key.
One step in the pagination process, I need to check the sorted result and post_pagination table, and do INSERT/UPDATE, like:
INSERT INTO post_pagination(`index`, post_id)
SELECT * /* full outer join new sorted result and pagination table */
FROM (
    WITH
    cte1 AS (
        SELECT ROW_NUMBER() OVER(ORDER BY edited_date DESC, ID DESC) AS new_rank, ID
        FROM posts
        WHERE is_public = 1
    ),
    cte2 AS (
        SELECT `index`
        FROM post_pagination
    )
    SELECT `index` AS dummy_rank, ID
    FROM cte2
    LEFT JOIN cte1 on `index` = new_rank
    UNION ALL
    SELECT new_rank AS dummy_rank, ID
    FROM cte2
    RIGHT JOIN cte1 on `index` = new_rank
    WHERE `index` IS NULL
) AS a
ORDER BY dummy_rank
ON DUPLICATE KEY UPDATE post_id = ID

The first time run this query, post_pagination is empty, so MySQL insert all data into the table.
index  post_id
1      390
2      391
3      392
4      393
5      307

it works well.
When I run the second time, I expect all data will not be changed, but it update all post_id field to the last value of the result.
index  post_id
1      307
2      307
3      307
4      307
5      307

I did a few tests, it seems like inserting values into a table by using values select from the same table would cause this problem, but I can't figure out why
Now I simply fix this problem by modifying the last line of the query to:
ON DUPLICATE KEY UPDATE post_id = ID + 0

Is there any better way to solve this issue?
Answer: Can you instead use a temporary table?
CREATE TEMPORARY TABLE `post_pagination_temp` (
 `index` INTEGER(1) AUTO_INCREMENT PRIMARY KEY,
 `post_id` INTEGER(1)
);

INSERT INTO `post_pagination_temp` (`post_id`)
SELECT `ID` FROM `posts` ORDER BY `edited_date` DESC, `ID` DESC;

INSERT INTO `post_pagination`
SELECT * FROM `post_pagination_temp`
ON DUPLICATE KEY UPDATE `index` = VALUES(`index`);

This assumes you have the correct index on post_pagination, i.e. the only unique being the primary key on post_id.


What's the correct relative path to a local image?

Question: I've created a topbar for my website that's displayed the whole time and added an image to it with

It looks great on the homepage, but when I for example visit a node, the image isn't found anymore. I guess this problem is caused by a wrong path, but I don't know how to fix it.
What's the correct relative path?
Comment: Indeed, it doesn't work: If you are looking at node/1, the image path is taken as node/1/sites/default/files/MYFOLDER/IMAGE.png, which is not correct.
Answer: In this case it is NOT:
.
It should be:
.
The issue you're having is Relative Path URLs vs Absolute Path Urls, see this stackoverflow in-depth answer.
By having /sites/default/files/FOO/bar.png as the PATH, you're informing the browser the file is found from the root of the website within the /sites/default/files/FOO folder and is called bar.png as an example.
By omitting the leading slash, you are saying the file resides in the folder path sites/default/files/FOO within the current directory. As you navigate the website, node paths and other URLs are rooted in other base directories.
Answer: Mainly it is the issue with your site root. If your site is on root not in any subdirectory then you can use it like /sites/all with front slash in the begining.
You must use the base url variable '$base_url' to the source of an image that defines the base path of the site. It will works always wherever the irrespective of the root of the installation
<?php global $base_url; ?>

<img src="<?php echo $base_url; ?>/sites/default/files/MYFOLDER/IMAGE.png">

Hope it works.
Comment: $base_url should be used rarely.  Use file_create_url instead.
Answer: I've found the solution for my problem, combining the answers from @tenken and @TBI Infotech. Using  didn't work, because the system was trying to retrieve the image from localhost/sites/default/files/MYFOLDER/IMAGE.png - obviously an non-existing directory.
Finally,  did the trick.
Comment: TBI Infotech's answer is a better solution. Your solution will require you to change that information presuming you move the site to a production server because it will still be looking on localhost. Using $base_url will do that work for you so long as you configure the site correctly.
Comment: @Geoff: I didn't know that. Thanks for your warning.


Add a new column to pandas data frame from dictionary

Question: I want to add a new column to my dataframe and map it to a dictionary. Mapping should be on the index of my original dataframe and I don't know how to use .map() to get there.
d={'KO': 'Consumer, Non-cyclical', 'AAPL': 'Technology'}

df:
Date   2015-12-01
KO    2144.499950
AAPL  5162.959824

I would like the result too look like this:
df:
Date   2015-12-01  industry
KO    2144.499950  Consumer, Non-cyclical
AAPL  5162.959824  Technology

Answer: Construct the Series first:
df["industry"] = pd.Series(d)

Note: This assumes that the dict keys are in the DataFrame index:
In [11]: df
Out[11]:
       2015-12-01
KO    2144.499950
AAPL  5162.959824

In [12]: df["industry"] = pd.Series(d)

In [13]: df
Out[13]:
       2015-12-01                industry
KO    2144.499950  Consumer, Non-cyclical
AAPL  5162.959824              Technology

Comment: @Mugen it's ipython/jupyter syntax. highly recommended download. e.g. see http://ipython.readthedocs.io/en/stable/interactive/tutorial.html
Comment: Thanks Andy. This is good. I was about to reindex the df data frame and have it indexed with 0,1,2,3, ... . Then move KO, AAPL,.. to fist column and use map() afterwards.
Comment: A very basic question. What does the code In[11] and Out[11] mean?\


Is there any way to work simultaneously on the same DAW project remotely?

Question: Is there any way to work simultaneously on the same DAW project remotely?
Imagine the situation. My bandmate is sitting in another town (or even country) and have his DAW (say, Cubase) open and ready. Me, sitting here at home and recording some stuff using the very same project, so my friend can see all the newly recorded parts more or less on the fly — let's skip live monitoring for a while.
Is there any out-of-the-box solution for such use-case? I am thinking of putting the project to shared Dropbox folder which will be synced on save, but considering Cubase projects are pretty much depend on plugin environment, it could be really challenging to make project work identically on several machines, but probably other DAWs are more suitable for such task?
Comment: Personally I don't even know if that's possible between two different computers in the same room.
Comment: > I am thinking of putting the project to shared Dropbox folder which will be synced on save If the files will be available after sync, after project save, what exactly do you mean by >Is there any way to work simultaneously on the same DAW project remotely? If the goal is to just see what the one recording, or using the daw, is actually doing, you could use any screen sharing app. But I think you're talking about something more complex? What exactly do you mean?
Comment: > But I think you're talking about something more complex?
Basically I want both side have the most actual version of the project, e.g. to listen closely to newly recorded phrase. Screen sharing will obviously rip the quality.
Answer: Steinberg have two 'remote' working solutions, VST Connect & the new VST Transit
I haven't used either in my real workflow, but was involved in early betas of Connect, which at the time looked very promising.
Answer: I think this is exactly what you're looking for: https://www.bandlab.com/
I've never used it myself, but from what I gather it's sort of like Google Docs, only it's a DAW.  (Google DAW?)
Comment: This is definitely cool option, especially considering it's free. You can do collab recording and then just download all the tracks to put them back to your favorite DAW. Thanks!
Answer: Share your desktop with him/her (VNC or similar), many (most/all) allow you to swap control back and forth.
Comment: That's of course a way to go, but I would rather prefer quality of project synced fully across two machines in, say, 5 seconds than mediocre quality of realtime RDP/VNC.


ID2D1HwndRenderTarget always having black background instead of transparent

Question: I am trying to create a simple transparent window where I can draw with Direct2D.
So far what I have done:

Created window
Set style to WS_EX_LAYERED
Set alpha color key as #FFF
Draw using Windows Graphics a white rectangle
Now window is transparent with per-pixel alpha
Then make a target out of the window and draw using Direct2D

Make ALPHA _PREMULIPLIED target
Clear with #FFF with 0.0f alpha

Window is now black

I just don't know how to make window to transparent. If you can point out my mistake, I would be obliged
Answer: Here how it's achievable using DirectComposition API
Russian: http://www.oszone.net/25395/
English: https://msdn.microsoft.com/magazine/dn745861.aspx
Basically what author does is

Sets WS_EX_NOREDIRECTIONBITMAP extended style to remove redirection bitmap of DWM. Content of window is now empty.
Creates DirectComposition device
Creates Composition SwapChain (and not hwnd swapchain)
Places one visual with SwapChain as content as root visual.
Renders into SwapChain using Direct2D API.

It also works well with WS_EX_TRANSPARENT | WS_EX_LAYERED | WS_EX_TOPMOST for creating event-transparent overlays.
Answer: I don't think it's possible with directX. However GDI does work.
Take a look at the source here to see how it's done: http://pastebin.com/NJf8wi2V
In the source you can see that there is an option to attempt to use directx/opengl. However as you can see from running they do not work.
Comment: Thanks for confirming. I went ahead and used GDI instead


Android MediaPlayer not playing sounds on button click

Question: I'm new to android and I need it for a project I'm working on. I need it to play a sound by clicking a button. I followed online tutorials but my code does not play sounds at all and I'm getting an error on MediaPlayer Error(-19,0). I've tried a lot of the fixes I saw here and I can't seem to make it work. Any help? Here's the code
<code>import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    MediaPlayer player;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            AudioManager audioManager = (AudioManager)     getSystemService(MainActivity.AUDIO_SERVICE);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);

            Button buttonHello = (Button) findViewById(R.id.button1);
            buttonHello.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MediaPlayer mp = Medi    aPlayer.create(MainActivity.this, R.raw.button);
                    mp.start();
                    mp.setOnCompletionListener(new OnCompletion    Listener() {
                        public void onCompletion(MediaPlayer mp) {
                            mp.release();

                        };
                    });
                }
            });
        } catch (Exception e) {
            System.out.println("Error!");
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
</code>
Comment: When is the error raised ? On `create()` or on `start` ? Is there any relevant message/trace in the exception ?
Comment: Where you give the file to mediaplayer?
Comment: (Btw you should probably set the listener before starting the player)
Answer: This links http://marakana.com/forums/android/examples/59.html has the great example to use MediaPlayer class to play song from raw folder.
To play song from files in the memory you can use the following code.
<code> MediaPlayer mp = new MediaPlayer();
         mp.reset();
         ContentValues values = new ContentValues();
         values.put(MediaStore.Images.Media.DATA, filename.getAbsolutePath());
          Uri selectedImage=RingtoneDownload.this.getContentResolver().insert(
                          MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                        try {
                            mp.setDataSource(RingtoneDownload.this,selectedImage);
                            mp.prepare();
                            mp.start();
                        }catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
</code>
This code is working for me while set the source from file.


Adding an item to Gridster.js grid with native add_widget causing unknown errors

Question: I've been trying all morning to add a simple item to a gridster grid but get errors in reference to gridsterjs' add_widget can someone please give me details on how to dynamically add widgets?
Perhaps I'm not instantiating correctly or missing a dependency...
$(function(){
    gridster = $(".gridster ul").gridster({
        widget_margins: [10, 10],
        widget_base_dimensions: [140, 140]
    });

    // errors why?
    gridster.add_widget.apply(gridster, ['
The HTML of the widget...
', 2, 1]); // Cannot read property 'apply' of undefined
    gridster.add_widget('
The HTML of the widget...
', 2, 1); // Uncaught TypeError: gridster.add_widget is not a function

});

Answer: That is not how you get the gridster object.. Try this:
$(".gridster ul").gridster({
    widget_margins: [10, 10],
    widget_base_dimensions: [140, 140]
});
var gridster = $(".gridster ul").gridster().data('gridster');

Now you can use the function gridster.add_widget(html, 2, 1);
Comment: Wow, I have never seen that code to get the gridster object. Is there anything I should know moving forward or references to go to? Thanks @pierreDuc!


Does Normality Imply Randomness?

Question: I have data indicating the number of counts per minute (so 60 rows in total - one for each minute - and # of events in that minute). I have ran the Shapiro - Wilk test which implies the data does not differ significantly from a Normal Distribution - can I therefore infer correctly that the counts are randomly distributed across each minute?
After spending some time researching I found a test called the "Runs test" which tests for randomness, however is normality enough?
Comment: Sort your dataset by count so that the counts increase over time.  Give it to another researcher who doesn't know how you created it and ask them whether it looks random: what do you think they will say?  Of course it doesn't look random to them.  Now try to persuade them it *is* random by pointing out that the Shapiro-Wilk test (which doesn't care about the order of the data, and therefore will have the same result as before) doesn't detect any non-Normality.  Do you think they will buy it?
Answer: Your question is a bit confusing, but I'll try answering. First of all, if you assume that some random variable follows normal distribution, then by definition, it is "random". However your question seems rather to ask if the fact that something looks like normal distribution (on histogram, it passes a normality test etc.), does this imply that it is a result of random process. The answer to the latter question is: obviously not. You can easily write a computer program that deterministically produces results that are consistent with normal distribution, and by "deterministic" I mean here something even stronger then pseudo random generator: you can simply repeat each of the possible values the number of times that is proportional to the probability of observing it according to normal distribution.
grid <- seq(-6, 6, by=0.01)
prob <- dnorm(grid)
prob <- prob/sum(prob)
counts <- prob*1e6
x <- rep(grid, round(counts))

hist(x, breaks=100, freq=FALSE)
curve(dnorm(x), from=-6, to=6, lwd=2, col="red", add=TRUE)

Comment: Thanks for your answer Tim. I suppose a follow question I would have is to ask how I can test if my data is random - specifically, that there is no bias to any particular minute in terms of the number of requests received in each of those minutes?
Comment: If you have a different question, post a new question.
Answer: Normality is not enough for randomness, if by "randomness" you mean independent sampling (as indicated by mentioning the runs test.) A perfectly systematic, deterministic sequence can pass a test for normality, after all such a test is only looking at the marginal distribution.
An extreme example, in R:
library(tidyverse);library(snpar)
x <- ppoints(1000) %>% qnorm
x %>% shapiro.test
x %>% runs.test

> >
    Shapiro-Wilk normality test

data:  .
W = 0.99995, p-value = 1

>
    Approximate runs rest

data:  .
Runs = 2, p-value < 2.2e-16
alternative hypothesis: two.sided

Answer: Well, by "randomness", I assume you mean "independence" (i.e: what happens on minute $x$ has nothing to do with what happens on minute $y$) for any $x$ and $y$ you may choose. If that's the case, then:
First, normality does not imply independence. Since normality tests don't care about the order of the observations, you can have "normal" data  that look like (-5, -3, -1, -.5, -0.25, 0.3, 0.45, 0.9, 2, 5), where we have an upward trend or even (-5.14, 5.18, -4.01, 4.21, -3.4, 3.1, -2.22, 2.11, -1.08, 0.97, -0.54, 0.76, -0.21, 0.32) where we have strong autocorrelations. My advice would be to perform some kind of independence test. For example, if you suspect there is order-based correlation, you can check that via ACF/PACF plots
Also, the reason why your data is not significantly different from normality is that you don't have a large enough sample. Every real-world based data will eventually fail the Shapiro-test if you have enough of it as every small deviation from normality will be detectable

Does Normality Imply Randomness?


How to include server-side script in Jade template?

Question: I've just installed moment.js; now I want to access moment inside my Jade template. Example:
.main-content
    .container
        .access-details.clearfix
            .left
                div Logged in: #{user.name}
                div Access Lvl: #{user.accessLevel}
            .right
                div= moment().format("dddd, MMMM Do YYYY, h:mm:ss a")

To be clear, I want the date to be formatted server-side and then sent to the client as a rendered string.
So how do I make a JavaScript library available inside of a Jade template?

I should probably note that I'm using this with Express:
var server = express.createServer();
server.configure(function () {
    server.set('view engine', 'jade');

Is there some options I have to pass in there somehow to tell it which libraries to include?

Just occured to me that this is absolutely no different than passing in a local variable. e.g.,
server.get('/', function (req, res) {
    res.render('index', {
        locals: {
            moment: require('moment')
        }
    });
});

But I don't want to pass this in to every view; if I ever forgot it my app would break as it's used in the main layout. So how do I make sure it's always available?
Answer: Helpers are removed from Express 3 or 4.
Kindly use app.locals
app.locals.moment = require('moment');

The app.locals object is a JavaScript Object. The properties added to it will be exposed as local variables within the application.
So you can use app.locals in any view files, Jade or EJS;
moment().format('YYYY-MM-DD h:mm:ss');

Answer: This answer got my pointed in the right direction, although the documentation on dynamicHelpers seems to have mysteriously disappeared from the Express documentation.
Also, I didn't need a dynamic helper, just a static one (no access to request/response). So I took a stab in the dark at what it would be called:
server.helpers({
    moment: require('moment')
});

Works like a charm! moment is now available in all my views.
Comment: Helpers concept has been removed from Express 3. What you mean by "static helpers" is [`app.locals`](http://expressjs.com/api.html#app.locals) (`app.locals.moment = require('moment');`). For `.dynamicHelpers` use middlewares.


Non-unique solutions to PDE of first order

Question: Given a quasi-linear PDE $u_x+yu_y=u$ with initial condition $u(p,0)=e^p$.
Of course, we use characteristic line method:
$x_t(t,s)=1$, $y_t(t,s)=y$, $u_t(t,s)=u$
$\Rightarrow x(t,s)=t+C_1(s), y(t,s)=C_2(s)e^t, u(t,s)=C_3(s)e^t$
Plug-in the initial condition: $x(0,s)=C(s):=s$, then $y(0,s)=C_2(s)=0$, $u(0,s)=C_3(s)=e^s$
Put all together, $x=t+s, u=e^{t+s}\Rightarrow u(x,y)=e^x$.
Although it does not satisfy the unique solution condition, i.e. parametrization of $x,y$ by $t,s$ is not regular, each step of derivation for me makes sense. So eventually the solution must be only that one.
However, $e^x+y$ is a solution (I found it by seeing...)
So what was wrong? Where can one get more solutitons? And how? Not just by guessing.
Answer: $$u_x+yu_y=u$$
$\frac{dx}{1}=\frac{dy}{y}=\frac{du}{u}$
First family of characteristic curves, from $\quad\frac{dx}{1}=\frac{dy}{y} \quad\to\quad ye^{-x}=c_1$
Second family of characteristic curves, from $\quad\frac{dx}{1}=\frac{du}{u} \quad\to\quad ue^{-x}=c_2$
General solution of the PDE : $\quad ue^{-x}=F\left(ye^{-x}\right)$
$$u(x,y)=e^xF\left(ye^{-x}\right)$$
$F$ is any function.
Condition :
$u(x,0)=e^x=e^xF\left(0e^{-x}\right)=e^xF(0) \quad\implies\quad F(0)=1$
Solution of the PDE with the condition :
$$u(x,y)=e^xF\left(ye^{-x}\right)$$
where $F$ is no longer any function, but is any function which is equal to $1$ when $x=0$.
Since they are an infinity of functions $F(x)$ satisfying $F(0)=1$, the problem has an infinity of solutions.
For examples :
With $\quad F(X)=1+X\quad$ the particular solution is  : $\quad u(x,y)=e^x\left(1+ye^{-x}\right)=e^x+y$
With $\quad F(X)=1+X^2\quad$ the particular solution is : $\quad u(x,y)=e^x\left(1+ye^{-x}\right)^2$
With $\quad F(X)=\cos(X)\quad$ the particular solution is  : $\quad u(x,y)=e^x\cos\left(ye^{-x}\right)$
And so on : An infinity of such examples can be found.
Answer: The problem has infinitely many solutions (no unique solution) since the initial curve $\bigg (x=t,\,y=0,\,u=e^t\bigg)$is a characteristic curve. More precisely, the Cauchy problem is defined on the characteristic curve.
From your characterictic equations you have $\frac{du}{u}=\frac{dx}{1}\Rightarrow ue^{-x}=c_1$ and $\frac{dx}{1}=\frac{dy}{y}\Rightarrow ye^{-x}=c_2$. Thus the general solution can be written in the form $$c_1=f(c_2),$$
 that is, $$ue^{-x}=f(ye^{-x}),$$ where $f$ is any $C^1$-function. When you substitute $x=t, y=0$, and  $u=e^t$, you see that $f(0)=1$. This means that there are infinitely many such $f$ satisfying the problem and $2x+1, \cos x, x^2+1,\, e^x,$..etc. are some examples of functions satisfying $f(0)=1$.
The problem has no unique solution. If it were so, $u_x$ and $u_y$ could be  solved uniquely on the curve $\Gamma: x=t, y=0, u=e^t$.
on $\Gamma$ the derivative of $u$ is $\frac{du}{dt}=u_x\frac{du}{dt}+u_y\frac{dy}{dt}\Longrightarrow e^t=u_x+0\Rightarrow u_x=e^t$
Looking at the PDE on $\Gamma$ we get $u_x=e^t$. We can find $u_x$ , but where is $u_y$? It can be anything, so it cannot be obtained uniquely. Therefore the problem has no unique solution.
Comment: Thx! Why when along the curve, it will get weird? But if you see my derivations after plug-in the initial condition, I think each step is ''if and and only if''. If I just ignore $y$, eventually, $u$ is given explicitly just by $x$..
Comment: @Junui: you cannot ignore $y$ because $u$ is a function of $x$ and $y$. Also it is not a quasilinear but just a linear equation.
Comment: I might think u is constant on y? Say arbitrarily $u(x,y,z,w,s)$, given $2u+2\sin x\cos x=3u$, so I get $u=\sin 2x$. I think the case was the same: $x=s+t, u=e^{t+s}$, no matter what $y$ is we must have $u=e^x$.
Comment: $u=e^x$ is a solution among all infinite number of solutions. In order to have a unique solution $u_x$ and $u_y$ can be solved uniquely on the given curve: $x=t,\, y=0,\,u=e^t$.
Comment: I added the reoson to the answer why the problem has no unique solution.


Conversion from my class to int

Question: I am using a library that is templated and that I do not wish to modify. Namely CImg.
This library has been mostly designed to work with templates of simple types: float, double, int etc.
At some point, this library does:
CImg<T>& fill(const T val) {
  if (is_empty()) return *this;
  if (val && sizeof(T)!=1) cimg_for(*this,ptrd,T) *ptrd = val;
  else std::memset(_data,(int)val,size()*sizeof(T));
  return *this;
}

Now I want to use this library with a more complex class as template parameter. My particular class is such that sizeof(T)!=1 and most of the time, the fill function will properly assign val to each element with the proper operator= of my class. However, when !val, I would like a conversion operator that allows my class to be cast to an int and to produce some values (for example, 0 would make the function above work).
Right now, my program does not compile as it says:
error C2440: 'type cast' : cannot convert from 'const MyClass' to 'int'

How can I create an operator that allows for (int)my_variable with my_variable of type MyClass to be legal, without modifying the function above ?
Comment: What line is giving that error?  Is it `*ptrd = val;` or is it `fill(myvalue)`?
Comment: it is `std::memset(_data,(int)val,size()*sizeof(T));`  (due to the cast from `val` of type `MyClass` to `int`)
Answer: Something like this using user defined conversions
int type;
explicit operator int()
{
   return type;
}

Comment: thanks as well! It also messes up with my other operators (see below). Any idea? thanks!
Comment: @WhitAngl: It shouldn't be messing up the other operators, and that seems largely unrelated to this question.  Can you make an [SSCCE](http://sscce.org/) and then post a new question about it with the SSCCE?
Comment: @WhitAngl can you post your other operators?
Comment: thanks ;  I have difficulty accepting an answer that ultimately still results in other errors. I'm preparing an SSCCE.
Comment: here it is : http://codepad.org/icXBM4uz  The error I get is related to the proposed solution, and `explicit` isn't supported either.
Comment: oh, thanks, that was indeed unrelated - sorry for that. Thanks again, I learned a lot!
Answer: What you want in this case is probably int conversion operator overload:
class A{
    public:

    explicit operator int() const{
        return 2;
    }
};

EDIT:
    |I added explicit conversion that should make your code compile (at least the method you showed us), and not mess-up other operators, but it's only allowed since C++11, so if you are using older compiler it might not be available yet.
Comment: Did you forget about the safe bool idiom?
Comment: I'm not sure he wants a bool conversion, I think he actually wants `int`.
Comment: that seems to work... however, that messes up my other operators (e.g., operator*(MyClass, MyClass) now has a similar conversion with operator*(MyClass, int) ). Any way to force the conversion to be explicit ?
Comment: @WhitAngl: Yes: the safe-bool idiom.
Comment: @MooingDuck what do you mean ?
Comment: @MooingDuck thanks, but what is the relationship with the `int` operator that screws up my other operators? I don't need a bool operator here.
Comment: @WhitAngl Don't define it. You don't need it, and this answer is unsafe.
Comment: @WhitAngl: use the `explicit` keyword
Comment: @MooingDuck I haven't defined the bool operator as I don't need it. And I of course tried `explicit` but this results in `error C2071: 'MyClass::operator int' : illegal storage class`
Comment: @WhitAngl: As he said "it's only allowed since C++11, so if you are using older compiler it might not be available yet."  http://coliru.stacked-crooked.com/view?id=ebbf0c8653cea8266485826982b25e8b-cc73e281b3b6abc9bf6cf4f153b944a6
Comment: does that mean there is just no solution that works for older C++, or just that this particular solution won't work for me ? thanks!
Comment: This particular solution will not work with older compiler. And even with a newer compiler, conversion marked `explicit` is really not that useful - it will work in above function because it directly requests conversion. And if you cannot use `explicit` then your problem can be stated as "You want to have a class that sometimes converts to `int` and sometimes it doesn't (eg. in your multiplication operators). I think that with some compromises you could still make it work, but it will get rather ugly.
Comment: For example, you could remove `operator*(MyClass, MyClass)`, and use multimplication with conversion to `int` - but I don't know if it even makes sense in your case. If it doesn't, there are still ways to deal with it, but the question is if it's actually worth doing.

Conversion from my class to int


How do you notate a blues scale?

Question: I understand the concept of a blues scales and its structure. For example, the one I've been trying to write on sheet music is D Major blues. The scale contains the following: D  E  F  F#  A  B
Now the main issue is, am I supposed to write the key signature as D Major and then add accidentals from there? If not, why?
I've tried searching online for sheet music based on the blues scale and it appears that all of them basically don't have key signatures. On the contrary- it seems easier if I just put the key signature and add the naturals or any other accidentals because it feels easier to read as a result... rather than having to put a bunch of accidentals without a key signature on it.
if it's possible, I would like a notated answer. If not, that is fine- I'll try my best to note them down
Answer: Music is usually written in the key that it's in. If you feel that is D major blues, then it gets written in D major. The tonic will definitely be D, and it certainly won't have a minor feel to it, so it certainly won't be written with one flat in the key sig, - for D minor.
There is usually a problem writing in D minor, as often it contains C♯, the leading note. But that will always be written as an accidental, never in the key sig - unless it's Bartok!
O.k., you may well not use the C♯ that's written in the D key sig., but even in key B, with five sharps, there's no obligation to use every one in the melody!
There's always going to be a problem with those F notes, though. If you leave F♯ out of the key sig., it'll need an accidental each time it appears; if you put it in, you'll need an accidental natural (♮) each time you want plain old F! There's no way round. Notation wasn't invented to write blues.
Answer: The standard notation
The standard is to write the diatonic key signature -- in this case F# and C#, since it's a "D Major" blues -- and use accidentals as needed. In that way, it's similar to writing in "harmonic minor" -- you use the minor key signature with accidentals in the body of the piece.
Here's an example of a blues in D Major, "Statesboro Blues", by Willie McTell. Note the D major key signature.

A bad alternative
Contemporary music does allow for some flexibility. Bartók, for example (okay, not that contemporary as of now, but a convenient example), uses odd key signatures like, say, F# and G#. So if your entire piece is structured entirely around the blues scale, you could just have an F# in the key signature and no other sharps/flats. However, this would be very confusing to most blues/jazz players. Every blues I've ever played, the key signature has been "in the key of" the blues (A "Bb" [major] blues has two flats; a "C minor" blues has three flats, ...), with accidentals as needed.
Answer: I would use the minor scale, and preferably notate the blues note as a sharp 4 rather than a flat 5.
For example, a blues in E would use the E minor scale, or E minor pentatonic if you will, (relative minor of G major, so one sharp in the key signature), and I'd write the blues note as A# rather than Bb.
Having said that, I suspect that other people will instead prefer thinking of the blues note as a b5 instead of a #4, or be flexible about it, depending on context.
Comment: Well, the blues scale is essentially a minor pentatonic with a passage note. You can use it against major chords, and you can add a major third, but intrinsically it remains a minor scale. That's how I conceive it at least. I'm sure others will have different opinions....
Comment: There are, in fact, two blues scales - major and minor.Just like there are two pentatonic, and effectively the full major (Ionian), and its relative minor (Aeolian). Blues isn't restricted to minor blues!
Comment: Do you mean that I change D Major blues to D minor blues?
Comment: I see... Though if I were to add chords I would try that. Unfortunately- I'm working on a solo melody only. It would still then remain as a minor scale then?
Comment: If you're working on a melody, I'd suggest to write in the key that most closely fits the notes and the mood. If the melody mainly feels like major, write in D major, and if it mainly feels minor -- i.e. many more minor thirds than major thirds -- then write it in D minor. Use whatever makes your life easiest...
Comment: Funny, but most blues players think of b5, most jazzers think of #4. Either way, with minor blues, there's always P4, #4/b5, and P5.

How do you notate a blues scale?


How do I create a loop for a function?

Question: I have a function that sorts a data set based on start and end dates and returns the top value. I was hoping to create a for loop that would allow me to run the function for all five year ranges in one go.
def get_topName(dataset, start_year, end_year):
    subset = dataset[(dataset.year >= start_year) & (dataset.year <= end_year)
    subset2 = subset.sort_values("n" , ascending = False)
return subset3[0:1]

I was hoping to loop this function for the following year ranges: 1950-1960, 1960-1970, 1970-1980, 1980-1990, and 1990-2000.
I was trying something like this, but I couldn't get it to work. I am also not sure how to properly create my list of date ranges.
for int in decades:
    get_topName(baby_df, start_year, end_year)

Answer: You could do something like this:
start_year = 1950
end_year = 2000
step = 10

for x in range(start_year, end_year, step):
    get_topName(baby_df, x, x+step)

Answer: Here's one suggestion, using np.vectorize():
import numpy as np

new_func = np.vectorize(get_topName)
output = new_func(dataset, [list_of_start_years], [list_of_end_years])

Note from the documentation,

The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.
Answer: Since your function has multiple args you can either unpack and use the map method, or use list comprehensions. Alternatively you could the itertools.partial method and use map over that. The easiest in this case is the list comprehension. Here is an example:
years    = range(1950, 2000, 10)
topNames = [get_topName(dataset, start, end) for start, stop in zip(years[:-1], years[1:])]

Comment: [zip](https://docs.python.org/3/library/functions.html#zip) is one of the builtin functions in python it aggregates the iterables in the argument. In this case i define a range and iterate over the years from the first element until the end -1 and from the second element until the end. This way you have the range set that you specified above.

How do I create a loop for a function?


Android Internet Browser Performance

Question: I'm finding that using transitions of any kind in the default "Internet" browser on android devices is painful. The performance is appalling, whether it's javascript or CSS transitions. It's not the device as Chrome performs exceptionally.
Is there any kind of hack to force the Android Internet browser to perform as expected, with hardware acceleration, or is it the IE of mobile browsers and we're all doomed?
Answer: You can change the default browser to another like Firefox or Chrome.
In newer versions of Android, Chrome is the default browser.
https://webmasters.stackexchange.com/a/47617
Comment: Yes I'm aware of that but it doesn't solve the problem for those using older versions.
Comment: You can do a trick to force WebKit-browsers to use hardware acceleration: http://stackoverflow.com/questions/9068132/why-arent-browsers-smart-enough-to-hardware-accelerate-without-tricks

Android Internet Browser Performance


call a bean method for each datatable item

Question: I'm facing a problem when trying to call a bean method for each item of a list displayed in a h:datatable,I get the folwing exception:
<code>- INFOS: Exception when handling error trying to reset the response. javax.persistence.NoResultException: No entity found for query
at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:498)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
</code>
I have an account entity and department entity which have a common column named code, but they're not linked, so to display the department with the same code as account I use this shared attribute(code) to get the department based on account's code.
<code><h:form prependId="false">
   <h:dataTable id="accounts_list"  class="table table-bordered table-striped table-hover table-condensed"
   var="account" value="#{AccountBean.accountProvider.allAccounts}">
      <h:column>
         <f:facet name="header">
            <h:outputText value="account type"/>
         </f:facet>
         <h:outputText value="#{account.categoy.label}"/>
      </h:column>
      <h:column>
         <f:facet name="header">
            <h:outputText value="account code"/>
         </f:facet>
         <h:outputText  value="#{account.code}"/>
      </h:column>
      <h:column>
         <f:facet name="header">
            <h:outputText value=" department"/>
         </f:facet>
         <h:outputText  value="#{AccountBean.searchDepByAccountCode(account.code)}"/>
      </h:column>
                         .....
   </h:dataTable>
</h:form>
</code>
Is it possible to proceed like that or should I search for another solution to do it.
thanks,
Comment: It's a part of business logic. What do you suppose to do if there is no such department? You can e.g. catch the exception and return empty string or "not found" string in the searchDepByAccountCode() method. You should decide it first.
Comment: Thanks, that was the problem ideed, I've already checked using sql but seems like data changed since, solved the problem by a simple try catch
Answer: It's a part of business logic. What do you suppose to do if there is no such department? You can e.g. catch the exception and return empty string or "not found" string in the searchDepByAccountCode() method.
Alternatively you can return not single result but a list of depeartment. The list could be empty of contains one or more items.


Send same info to multiple threads/sockets?

Question: I am writing a server application that simply connects a local serial port to multiple network connected clients.  I am using linux and C for the server application because the equipment for the program is a router with limited memory.
I have everything setup for multiple clients to connect and send data to the serial port using a fork() process for each connection.
My problem lies in getting data incoming on the serial port out to the multiple (varing number) client connections.  my problem lies in designing a way for each active socket to get all of the incoming data, and to only get it once.   Any help?
Comment: Are you saying that multiple network clients are reading and writing to a single common serial interface? That's what it sounds like but that's also an odd pattern.
Comment: Thats exactly it.  if it wasnt odd im sure it would be easier.  sadly the serial-in network-out is the important direction.  the other direction was easier as each thread writes to the serial port directly as needed.
Comment: I am not sure your design or requirement is right. You should be very careful with serial ports. You might use a multiplexing syscall like `poll` or `select`  instead of several threads.
Answer: Sounds like you need a data queue (buffer) for each connected client.  Each time data comes in on the port, you post it to the back of each client's queue.  The clients then read the data from the front of their respective queues.  Since all the clients will probably read at different rates/times, this will ensure all of them get a copy of the data only once, and you won't get hung up waiting for any one client while more data comes in.  Of course, you'll need to allocate a certain amount of memory for each connected client's queue (I'm not sure how many clients you're expecting, and you did say your available memory is limited), and you need to consider what to do if a queue gets full before the client reads all of it.
Answer: Presumably you keep a list or some other reference of/to connected clients, why not just loop over that for each bit of information and send it to all of them?
Comment: thanks, thats the approach im trying currently, i was hoping there was some "built-in--pipes or similar" way of doing, i've got a large number of loops aready running.
Answer: A thread per socket design might not be the best way to solve this. An event driven asynchronous approach should be a much better fit. However, if you must do it with threads, and given that serial ports are slow anyway, building a pipe between the thread listening to the serial port and all the threads talking to the network clients is the most practical. You could do fancy things with rwlocks to move the data, but you'll still need a way for the network threads to wait on both the socket and the data from the serial port, so you need to use file descriptors for both and something like poll.
But seriously, this would likely be much easier and would perform better without the threads. Think of it as a main loop which waits on poll which is watching the network and the serial port, determines which event occurred, and distributes data accordingly. It should be easier all around once you get the idea.
Comment: Just reread and given the environment you may not have the standard POSIX facilities, so pipes might not be an option. An alternative would be a signal that interrupted the read wait on the network socket. But assuming you have some form of poll, which should be a relatively safe assumption, I'd still just try giving up the threads entirely as I don't see what they add.
Comment: Thanks. this type of server programming is new to me so im trying to crawl my way along, and threads/fork was the first way i found to handle multiple conections, I'm tryin to get my head around this other approach you talk about, so instead of fork()'ing i would instead add the fd of the new socket to some time of array, then come back around and process each member of the array (read/write)??
Comment: You'll need an array of connections, and you'll need to understand the poll interface. Once you get that, your event loop just needs to use the provided functions for testing which FD(s) was/were raised and handle the events (it's up to you to figure out how to use those facilities to create logic to route events into handlers), of which I think you have four: connect, disconnect, receive from serial and receive from a network client.


Does an acoustic/electric guitar with a preamp still need an amplifier?

Question: My son wants an acoustic-electric guitar.  The one he picked out has a preamp.  I know absolutely nothing about guitars, so does he need a separate amp if this one has a preamp?
Comment: The "pre" in "preamp" means that it comes before the "amp".
Answer: To answer your question: Yes, he will need a separate amp if he wants to plug the guitar in and amplify the sound.
A preamplifier (preamp) is an electronic amplifier that prepares a small electrical signal for further amplification or processing. The preamp is inside the acoustic-electric guitar (the preamp makes up the electric portion of acoustic-electric guitar) and allows for the acoustic guitar to be plugged into an external amp and make some loud noise.
A preamp looks like this. And an amp looks like this.
Your son can still play the acoustic-electric guitar without an external amp, but the sound will not be amplified. If you are buying him a Fender Acoustic-Electric I recommend buying an external amp similar to one of these:
$ - Fender Acoustasonic 15 1x6" 15-Watt Acoustic Combo
$$ - Fender Acoustasonic 100 Acoustic Guitar Amplifier
$$$- Fender Acoustasonic 150 150W 2x8 Acoustic Guitar Combo Amp
$$$$ - Fender Eric Clapton Signature EC Twinolux 40W 2x12 Hand-Wired Tube Guitar Combo Amp Tweed TWEED
Note: You don't have to buy a Fender amp because you have a Fender guitar, but I personally like to buy the same brand just for compatibility reasons.
Good luck!
EDIT (Thank you JimR for mentioning this): Make sure you check out the Fender Mustang Amps. They are great amps at an affordable price
Comment: I would add one thing to this otherwise excellent answer...  Look at the Fender Mustang amps and see if any of them are appropriate for your sons use.  The added effects and flexibility (and low price) are pretty good for a beginner and give lots of flexibility.  The lack of flexibility for my first guitars and amps almost drove me away from playing since I had the choice of 2 sounds...  Acoustic without reverb or acoustic with reverb. :)


Integral on a quarter circle

Question: Let $S=\{(x,y):x≥0,y≥0,x^2+y^2≤1\}$. Then find the integral
$$\int\int_Sxy dx dy$$ How do I do it? I don't have any idea. Thanks.
Comment: Hint: while you can do it using Cartesian coordinates, the symmetry of the problem calls for the use of polar coordinates.
Answer: $$I=\iint_S xy\,dx\,dy = \int_{0}^{1}\int_{0}^{\sqrt{1-x^2}}xy\,dy\,dx =\frac{1}{2}\int_{0}^{1}x(1-x^2)\,dx=\frac{1}{8}.$$
As an alternative, in polar coordinates we have:
$$ I = \int_{0}^{\pi/2}\int_{0}^{1}\rho^3\sin\theta\cos\theta\,d\rho\,d\theta = \frac{1}{8}\int_{0}^{\pi/2}\sin(2\theta)\,d\theta = \frac{1}{8}.$$
Answer: Hint:
$\int \int_s xydxdy=\int_0^1\int_0^\sqrt{1-y^2}xydxdy.$

Integral on a quarter circle


pegar cliente com determinados tipos de compras

Question: Tenho essas tabelas:

Vendas : IDVenda(int)PK, DataVenda(DateTime), QdeItem(Decimal),
  ValorVenda(Decimal).IDItem(FK),IDCliente(FK)
Item: IDItem(int)PK,Descricao(Varchar),ValorItem(Decimal)
Cliente:IDCliente(int)PK,Nome(varchar),DataCadastro(DateTime)

Como eu faço para filtrar somente os cliente que compraram 5 ou mais bicicletas e um pneu pelo menos, usando LINQ apenas?
Comment: Na aplicação, cliente possui uma lista de Vendas?
Comment: Voce utiliza EntityFramework?
Comment: Isso deverá ser feito com LINQ ou Sql normal. Só peciso dentre uma lista de coisas vendidas, a linq ou sql deveria retornar quem comprou acima de cinco carros e um pneu.
Answer: você pode realizar a seguinte consulta:
public IEnumerable<int> getClientes(int itemID, int qtdMinimo)
{
    return (
        from venda in db.Vendas
        where venda.IDItem == itemID
        group venda by venda.IDCliente into grupo
        where grupo.Sum(venda => venda.QdeItem) >= qtdMinimo
        select grp.Key
    );
}

No caso acima, será retornado todos os clientes que compraram mais de 5 itens do produto informado, independente destes produtos terem sido comprados no mesmo pedido.
P.S: Não foi testado


Mongo issues when trying to look at my collection using .find()

Question: So to start off first ill display my code that i have so far.
var express = require("express"),
        app = express(),
 bodyParser = require("body-parser"),
   mongoose = require("mongoose");

   mongoose.connect("mongodb://localhost/yelp_camp");

  app.use(bodyParser.urlencoded({extended: true}));
  app.set("view engine","ejs");

var chairSchema=new mongoose.Schema({
    name:String,
    image:String,
    price:Number
});

var data =mongoose.model("data",chairSchema);
data.create(
{
  partname:"short cylinder",
  img:"http://www.needforseatusa.com/assets/images/products/replacement%20parts/short_cylinder_thumbnail.jpg",
  price:14.90
},function(err,chair){
  if (err){
    console.log(err);
  }
  else{
    console.log("newly created chair");
    console.log(data);
  }

}

);

so my issue is when I run my app using "node app.js" it is suppose to create a database and a collection called datas and inside there should be like data that looks similar to the object i am creating in the data.create function call but when i go to check my collection inside the db of yelp_camp all i get back is this sort of list
{"id" : ObjectId("3453453453453463456353sdsfdsf"),"price":14.9,"_v":0)

so i thought if i run .pretty() it might change but it remains the same i feel like i have a tiny error somewhere but I just do not see it
Answer: In your schema you have wrote name and image, but while saving you are using partname and img. thats why you are getting this behaviour.
var chairSchema=new mongoose.Schema({
    name:String,//<-look here
    image:String,//<-look here
    price:Number
});

while creating new document, you need to use same exact fieldname.
data.create(
{
  //partname:"short cylinder",
  //name should be used instead of partname
  name:"short cylinder",
  //img:"http://www.needforseatusa.com/assets/images/products/replacement%20parts/
  //'img' should not be used, 'image' should be used instead.
  image:"http://www.needforseatusa.com/assets/images/products/replacement%20parts/short_cylinder_thumbnail.jpg",
  price:14.90
}

Comment: Yes you are right. but if you are not giving same name as your schema object name then it will only not be able to save those properties. In anycase  pretty() function have to work in mongodb shell (if the document have been saved).


aiosqlite "Result" object has no attribue "execute"

Question: I'm making a discord.py bot and I'm currently on the economy part, but I'm encountering a strange error that I've never ran into before and has most of the python discord help dumbfounded. The error is as follows:

Command raised an exception: AttributeError: 'Result' has no attribute 'execute'

I'm having trouble understanding the meaning of this error due to the fact that I'm executing it on a cursor object, and not a result?
For those who need the code, here you go:
# Imports
import discord
from discord.ext import commands
from random import randrange
import asyncio
import time
import aiosqlite

# Def balance funcs
def getBal(ctx, user : discord.Member):
  main = aiosqlite.connect('main.db')
  cursor = main.cursor()
  cursor.execute(f"SELECT balance FROM MainTable WHERE member_id = {user.id} AND guild_id = {ctx.guild.id}")
  result = cursor.fetchone()
  if result:
    return
  if not result:
    sql = "INSERT INTO MainTable(balance, guild_id, member_id, warns) VALUES(?,?,?,?)"
    val = (0, ctx.guild.id, user.id, 0)
  cursor.execute(sql, val)
  main.commit()
  cursor.close()
  main.close()

# Def main class
class Balance(commands.Cog):
    @commands.command(aliases=['bal'])
    async def balance(self, ctx, user : discord.Member = None):
      if user == None:
        user = ctx.author
        getBal(ctx, user)
      else:
        getBal(ctx, user)
      main = aiosqlite.connect('main.db')
      cursor = main.cursor()
      cursor.execute(f"SELECT balance FROM MainTable WHERE member_id = {user.id} AND guild_id = {ctx.guild.id}")
      result = cursor.fetchone()
      if result is not None:
        if user is None:
          embed = discord.Embed(title=f"**{ctx.author.mention}'s Balance**", description=f"**{ctx.author.mention}** has **{result[0]}** coins.", color=0xffffff)
          await ctx.send(embed=embed)
        else:
          embed = discord.Embed(title=f"**{user.mention}'s Balance**", description=f"**{user.mention}** has **{result[0]}** coins.", color=0xffffff)
          await ctx.send(embed=embed)
      else:
        await ctx.send("Critical Error! Please contact the developers.")

# Initialize
def setup(bot):
    bot.add_cog(Balance(bot))
    print('Balance is loaded')

Comment: always put full error message (starting at word "Traceback") in question (not in comments) as text (not screenshot, not link to external portal). There are other useful information.
Comment: if `aiosqlite` uses `asyncio`  then it may create special object which waits for result from `.cursor()` - and you should use `await`  for this - and it may need also to use `async` before `def`. You may have to check documentation for `aiosqlite` to see how to use it.
Comment: see doc for [aiosqlite](https://github.com/omnilib/aiosqlite) - it doesn't create `cursor` but it runs directly `main.execute()` - eventually `with main.execute() as cursor`
Answer: You should read documentation for aiosqlite because it works different then standard sqlite3
You need
cursor = await main.execute(...)

EDIT:
It may also need to use await in every function. And add async before def
async def get_balance(ctx, user : discord.Member):   # PEP8: readable names

  main = await aiosqlite.connect('main.db')

  cursor = await main.execute(f"SELECT balance FROM MainTable WHERE member_id = {user.id} AND guild_id = {ctx.guild.id}")
  result = await cursor.fetchone()

  if result:
    return

  # there is no need to check `not result`

  sql = "INSERT INTO MainTable(balance, guild_id, member_id, warns) VALUES(?,?,?,?)"
  val = (0, ctx.guild.id, user.id, 0)
  cursor = await main.execute(sql, val)

  await main.commit()
  await cursor.close()
  await main.close()

and later you have to run it also with await
await get_balance(ctx, user)

PEP 8 -- Style Guide for Python Code


Android dynamically change keys in soft keyboard

Question: I have a problem with my custom view that contains an edittext and a spinner. I have added a "next"-button using IMEoptions. Depending on the spinner, the edittext keyboard should contain either a "next" or a "done" key.
At the moment I solve this using:
<code>@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
    final Object item = adapterView.getItemAtPosition(position);
    if (item.equals(getString(STRING1))) {
    edittext.setImeOptions(EditOptions.IME_OPTIONS_NEXT);
    } else if(item.equals(getString(STRING2)){
    edittext.setImeOptions(EditOptions.IME_OPTIONS_ACTION_DONE);
    }
    edittext.setText(edittext.getText());
     //This updates the edittext but is very much an ugly hack.
     //Is there another way to update this? invalidate() and forceLayout()
     //does not do the trick
}
</code>
Answer: Alternate solution.
<code>edittext.setInputType(InputType.TYPE_CLASS_TEXT);
</code>
As described here:
change the keyboard layout after a button click


list of states json data into dropdown select using jquery

Question: This is the json data that is being returned:
({"Data":{"Alabama":"AL","Alaska":"AK","Arizona":"AZ","Arkansas":"AR","California":"CA","Colorado":"CO","Connecticutt":"CT","Delaware":"DE","Florida":"FL","Georgia":"GA","Hawaii":"HI","Idaho":"ID","Illinois":"IL","Indiana":"IN","Iowa":"IA","Kansas":"KS","Kentucky":"KY","Louisiana":"LA","Maine":"ME","Massachusetts":"MA","Michigan":"MI"}})

I need to put it into dropdown select.
$.getJSON(url + 'GetStateList?jsoncallback=?',
    function (json) {
        if (!jQuery.isEmptyObject(json.Data)) {
            //need to write logic
        }
    });

Can anyone help me out on this?
Comment: related: http://stackoverflow.com/questions/94674/jquery-create-select-list-options-from-json-not-happening-as-advertised
Comment: http://stackoverflow.com/questions/317095/how-do-i-add-options-to-a-dropdownlist-using-jquery
Answer: var data = 'jsonstring', i, select = $('select');

for(i in data){

    select.append($('<option value="' + data[i][1] + '">' + data[i][0] + '</option>'));

}

Comment: The result only returns the 1st letter of the state name and stateid
Answer: It's just a basic example, feel free to use it as a start point:

    <TITLE>Test Example</TITLE>

    <form>
        <select id="sel" />

    </form>


How are stoppage time goals deduplicated from regulation time goals?

Question: In football, goals can be scored in stoppage time, say the 46th minute of the first half, and also in the 46th minute of the game in the second half.
Is there any way of differentiating / deduplicating the stoppage time and regulation time goals? Has there ever been a collision?
Answer: A plus sign (+) is used to indicate goals scored in the stoppage times. For example a goal scored in the 47th minute of the first half is recorded to be scored on 45+2' (the ' is shorthand for minute), where as if it was scored on the 47th minute of the second half, it would've simply been recorded to be scored on 47'.
Same format follows for the stoppage time in the second half and the extra times.
Here on the scoresheet of the round of 16 game between Belgium and Japan in 2018 World Cup you can see Belgium's third goal scored by Chadli recorded to be scored on 90+4'.
Answer: As @alamoot noted, if the goal was scored during the stoppage time, you will mostly see 45+x' (similarly 90+x', 105+x' and 120+x') notation, however, sometimes goals scored during the stoppage time are counted as last minute goals of the current half, e.g. a goal scored in the 3rd minute of the stoppage time of the second half will be simply denoted with 90'.
Comment: @FairPlayer, please follow the embedded link, it's particularly linked to the match played between Belgium and Japan. There's no such thing as official way of keeping record of goal minutes, no official football body regulates this kind of football punctuation. It's just one of the commonly utilized standards.
Comment: Goals during the stoppage time after the second half are always scored on 90+x minute, never on 90'.
Comment: @FairPlayer, e.g. here in [livescores.com](http://www.livescores.com/worldcup/match/?match=1-2059636), although Chadli scored his goal in `90+4'`, it's denoted simply as `90'`.
Comment: There are about 100 matches on this page, which one do you mean? And remember that this page is not official.
Comment: So, now on PC it's linked to a particular match. On the Iphone I saw a page with hundreds of matched from all over the world played on that day. But 90` is shown only in match details. In comments it's 90+4'. Writing 90' for stoppage time  can lead to [two goals in one minute](http://www.livescores.com/worldcup/match/?match=1-2059617).
Comment: @FairPlayer yes exactly, but still some use this notation.


How to check SRAM usage for cortex m3 for an application

Question: For Cortex-M3, how to check maximum SRAM usage by an embedded application running on it. Should we check linker map file and stack usage generated by IAR or should we try with writing a function which check current SRAM and call it in application at various place at runtime. Which method should be used.
Comment: there is no one answer that will work.  first off you should know what your usage is by analysis.  but a valgrind type approach is pretty common. fill memory with a pattern, being embedded say in the bootstrap, then at some point examine the memory and see how much has been changed/overwritten...If you have not covered all the possible execution paths and consumption use cases, then the results are not all that valid though.
Answer: Not easily, because stack usage differs by quite a lot, and can not be known at compile time, unless you have some restrictions (no proper recursion for example).
That said, there are some tools that might help you get worst-case stack usage:

StackAnalyser (https://www.absint.com/stackanalyzer/index.htm)
GNATstack (https://www.adacore.com/gnatpro/toolsuite/gnatstack)

(There's also some development on this topic in Rust: https://blog.japaric.io/stack-analysis/)


Reducing Variance in Estimating the Exponential Average of Random Variables

Question: Imagine we have a random variable called X, and the function form of the probability density for X is unknown. Now, I'm interested in finding the average value of the exponential of X, denoted as E[exp(X)]. The simplest way to do this is by taking N random samples, let's call them X_1, X_2, up to X_N, and then finding the average of their exponential values: (exp(X_1) + exp(X_2) + ... + exp(X_N)) / N.
However, there's an issue with this method. In most cases, a small portion of these samples will dominate the summation, causing the result to have a large variance.
Is there a different method we can use to estimate the average of exp(X) that doesn't suffer as much from this variance problem?
Comment: You really need to know something about the distribution.  For example, if $X$ has an exponential distribution with a mean of $\mu \ge 1$  and variance of $\mu^2$ then $\mathbb E[e^X]$ is infinite.
Comment: You may be interested in "importance sampling." Here is a link discussing the general idea: https://towardsdatascience.com/importance-sampling-introduction-e76b2c32e744 The method works when you already know the probability density or mass function for $X$, and you can generate samples using a modified density or mass function.
Comment: @Michael Unfortunately I don't know the probability density function for $X$.
Answer: This is effectively the same as asking: How can we estimate an average? The exponential is just a re-expression of the variable with different numbers.
Examples where either $X$ or $e^X$ might be observed
Consider:

Did you observe the Richter magnitudes of earthquakes ($X$), or did you actually observe the amplitudes of the waves in the earth ($e^X$), and calculate the magnitudes as their logarithms?
Did you observe the absolute magnitudes of stars ($X$), or did you actually observe the radiant fluxes ($e^X$) and calculate the magnitudes as their logarithms?

So whether you observed the variable of interest $X$ or its exponential $e^X$ may not be clearly distinguished.
General Techniques for Estimating Averages
There are some general techniques for estimating the average of a variable $X$:

You can take the mean of $X_1, \dots, X_n$.
You can use importance sampling, as suggested in the comments, if you can oversample high $X$'s and weight them appropriately.
If your $X$'s are paired with some associated variable $Y$, and you can weight them appropriately, you might oversample the $X$'s associated with particular values of $Y$. E.g.:

If $X$ = attendance at city parks, and $Y$ = day of week, you might more accurately estimate the average daily attendance by making more observations on the weekends.
If $X$ = income, and $Y$ = neighborhood, you might more accurately estimate average income by making more observations in richer neighborhoods.

If you assume that $X$ is lognormally distributed, you might take the average $\mu$ and standard deviation $\sigma$ of $\log X$, and then estimate the average $X$ as $\exp(\mu+\sigma^2/2)$. This is a consistent, probably biased estimator for the mean of $X$, with a variance smaller than the direct estimate averaging the observations, especially beneficial for $\sigma>1$. Or perhaps you can do something similar with another transformation.

Perhaps you have a situation where one of these ideas will work and you can do better than taking the mean of the observations -- but in the absence of further detail on your issue, I wouldn't expect any luck of that sort.
Appendix: Worked Example with Lognormals
For the lognormal example, I use the R code below to calculate that with $\sigma=0.5$, the estimate via logs has a variance about $99$% of that from the direct estimate, but with $\sigma=2.0$, the estimate via logs has a variance about $20$% of that from the direct estimate.
<code>directs = 1:10000
indirects = 1:10000

for (sigma in c(0.5,2)){
  for(i in 1:10000){
    x = rlnorm(10000, 0, sigma)
    y = log(x)
    directs[i]   = mean(x)
    indirects[i] = exp(mean(y) + sd(y)^2/2)
  }
  print(sprintf("for sigma = %3.1f:", sigma))
  print(sprintf(
    paste("variance by indirect method = %0.3f",
          "* variance by direct method"),
          var(indirects)/var(directs)))
  print(sprintf(
      paste("error by indirect method = %0.3f",
            "* error by direct method"),
      (mean(indirects)-exp(sigma^2/2))/
        (mean(directs)-exp(sigma^2/2))))
}
</code>
Comment: +1. But I have to object -- this is not nit-picking -- that exponentiation is not what most people mean by "change of scale," which is usually understood as a constant multiplication of all values.  A convenient term, adopted by Tukey and others c. 1970, is "re-expression."  That refers to any monotonic (usually increasing) invertible function of the values.
Comment: @Galen That would be *Exploratory* Data Analysis (EDA), published in 1977 from notes of an earlier Princeton course.  The earliest reference I can find in Tukey's Collected Works is from an American Statistician article published in 1980.  The term "re-expression" in pervasive in Understanding Robust and Exploratory Data Analysis, 1983, with chapters contributed by a dozen authors.
Comment: I suspect @whuber is alluding to Tukey's [*Exploring Data Analysis*](https://archive.org/details/exploratorydataa00tuke_0), although it is possible Tukey mentioned it earlier.


iptables --dport ssh

Question: In iptables, what is the difference between --dport ssh and --dport 22? i.e. when I change the port in sshd's settings, will iptables automatically get the new port and use that wherever --dport ssh is specified, or will it still use 22?
Answer: When you use a name it will do a look-up on what is defined in your /etc/services.  What you have defined in your openssh's sshd_config is completely irrelevant.  The name is only evaluated when the rule is being added to the kernel tables.  Once the rule has been added, any subsequent changes to /etc/services do not automatically result in a change of the rule.

iptables --dport ssh


What is the Root/Quality chord symbol for this note cluster?

Question: I am just starting to learn the music for Leigh Harline's song : "When You Wish Upon A Star"
In measure 5 the LH notes are C, D, and E and the RH notes are G♭, A♭, B♭ and C. The beginning key for this song is C major. Is there a proper name for this cluster chord ?
Comment: It depends on the context. Naming a chord like this depends heavily on what its function is, and that requires knowing what comes before and after (not just individual chords, but the wider musical context). Without that, it's just a whole-tone scale played as a chord.
Comment: I'd like to see the sheet music for the first 8 bars before making any kind of call...
Comment: When editing a post, there is a toolbar with icons (at left) for bold and italic type. After those there is a block of four icons, with the one on the right for uploading images. You can take a smartphone photo of the chord plus some of the surrounding music and upload it.
Comment: Please link a video of the performance you are taking this from or an image of the sheet music you are using so that the question can be better answered.
Comment: This song won the 1940 Academy award for Best Original Song...also sung by the famous Jiminy Cricket in 1940 !
Comment: how do we upload paper music scores to this website ?
Answer: The intro to this song plays the notes of a whole tone scale.  The whole tone scale is used as a kind of cliché in theatre and film to represent imagination or dreaming/daydreaming.  For example,

Interestingly, the whole tone scale's modes are all also whole tone scales, so a cluster played in that way may not have any distinguishable root note unless the performer or context emphasizes or suggests a certain note to be the root.  I suppose you could also conceptualize it as an augmented seventh chord with an added 2 and #4, if any note seems to be the root.
Comment: And - there is only one other 'whole tone scale' - and that starts on C#. Diffiult to say what a root would be, really.
Comment: The lower bass note in this cluster was "C" in the key of C. All the notes in the cluster make up the complete Whole Tone Scale beginning with C !


Home up button changes its direction when language is changed

Question: I have two languages in my app, English and Urdu. When the language is changed to Urdu home up button changes its direction like this:

Please help me how can I fix this issue. I want arrow direction to be on left side
Comment: What is your home button? The arrow? It might change direction if Left to Right and Right to Left Layouts have been implemented. Check this by going to developer options and enable RTL Layouts. If that is the case then disable RTL changes.
Comment: yes arrow is home button
Comment: Then simply disable RTL layouts, your problem should be resolved.
Answer: To support right to left screen layout, you have to android:supportsRtl="true" line in your manifest.xml For example:
<application
        android:name=".Application"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
>

After writing this tag, the arrow button will appear on the right and other icons on the left.
For more information, see this post.
Comment: I dont want to sift all icon left side , I just want to sift the arrow direction to  left
Comment: Try setting it to false. But I recommend you change your screen layout according to the language being used.
Comment: Its looks very bed .. all setting icons appears on left and app name on right side
Comment: Yes, Its absolutely fine. If you do **Urdu localization**, the app name and other text will displayed from the right. And this will be good user experience.
Answer: There is not issue and supportsRtl.
Because if
android:supportsRtl="true"

then view display from right-hand-side.
If false then it'll display as it is.
Can i have your manifest application tag and style which used there?
Comment: i made changes from true  to false now it appears good. It was true before


Removing spry validation on an input in javascript

Question: I want to have a form in my checkout page that has an input for billing address and I have also a list of billing address. If the user has added any billing address from their account, it will listed on the checkout. Now if the user is on the checkout page then he/she will have two options, select a billing address from the list or add a new billing address. The "add" form has had spry validation added to it.
My problem was that if the user selects a billing address from the list the spry validation still occurs on the billing address form and the user can't submit the form. What I'd like to have happen is if the user clicks on the link "add the new billing", then the spry validations object will be created and the form is displayed and when the user clicks on the cancel button then the object is destroyed.
I have created an object when the user clicks on the link for the add form. Both the object & validation works perfectly.
UserAddressBookFullNameValid = new Spry.Widget.ValidationTextField("UserAddressBookFullNameValid", "none", {validateOn:["blur"]});

How to I destroy the object or remove the validation when the user clicks on the cancel button. I have tried some ways but it won't work. Examples:
delete UserAddressBookFullNameValid;
UserAddressBookFullNameValid = null;

So can anyone help me to do this or give me some another way?
Thanks
Answer: To have this work, make sure UserAddressBookFullNameValid defined in your javascript.
var UserAddressBookFullNameValid;

Create the spry validation for the field as you do now. In the code for the cancel button put:
if (UserAddressBookFullNameValid != undefined) {
  UserAddressBookFullNameValid.reset();   //Resets any validation css on the form
                                          //(may not be necessary if hiding the inputs

  UserAddressBookFullNameValid.destroy();
  UserAddressBookFullNameValid= null;
}

I had a similar problem except I needed my field validated only if a checkbox was checked & it now works for me using this code.


$_nC_r$ probability help

Question: It's been a while since I've done probability math (a couple years ago in high school).  I play a bit of sheepshead, and we were discussing the odds of one trump being in the blind.  In sheepshead, there are 32 cards; 14 are trump and 18 are fail.  There are two cards in the blind and 3 people playing.  How do you calculate the odds of 0 trump, exactly one trump, at least 1 trump, and 2 trump being in the blind?  I know it has something to do with $_nC_r$, but cannot remember how do it.
Comment: As I've never heard of the game "sheepshead" you'll need to be a bit more clear with what it is you are asking.  If I am understanding you correctly, there are 32 cards, 14 of which are trump, and you are picking two cards from these at random and your question is what the odds are that these two picked cards are trump or not is.  Was there any importance on the number of players?
Comment: @JMoravitz I suppose not, since peeves91's problem did not specify any relation to the players.
Answer: Probability in an equiprobable setting is simply $Pr(\text{event occurring}) = \frac{\text{\# ways event occurs}}{\text{\# ways regardless}}$
Imagine for a moment that the cards not only are labeled trump or notrump, but also are labeled with numbers.  Considering our sample space as being the ways in which you can select two cards (where order doesn't matter), we notice that each occurrence will be equiprobable so we may use this definition for probability.
The number of ways of selecting two cards for the blind will be $\binom{32}{2}=~_{32}C_2=\frac{32\cdot 31}{2}$
The number of ways of selecting two non-trump for the blind will be $\binom{18}{2}$.  The probability then of having picked both cards to not be trump will be $\frac{\binom{18}{2}}{\binom{32}{2}}=\frac{18\cdot 17}{32\cdot 31}$
Similarly, the number of ways of selecting one non-trump for the blind will be $\binom{18}{1}\cdot\binom{14}{1}=18\cdot 14$, so the probability of this occurring will be $\frac{\binom{18}{1}\cdot\binom{14}{1}}{\binom{32}{2}}=\frac{18\cdot 14\cdot 2}{32\cdot 31}$
Continue similarly for the remaining cases of interest.

$_nC_r$ probability help


Create RavenDB reference field without linking to Newtonsoft.Json

Question: I am storing an object in RavenDB that has a reference to another object.  I wish to indicate to the RavenDB serializer that it should be a reference, not an embedded object.  The way to do this is to decorate it with [JsonObject(IsReference = true)] attribute.  This is fine, however it means that I have to reference the Raven.Imports.Newtonsoft.Json assembly in my POCO assembly.
So the question is, is there another way to apply this attribute?  Perhaps using DefaultContractResolver somehow?
Many thanks for any help.
Answer: You can handle that using a contract resolver yes. You can customize the contract resolvers in the RavenDB Conventions.


Subspace topologies and unions

Question: I want to show that if $(X,\mathcal{T})$ is a metric topology. Take two disjoint subsets $A$ and $B$ such that forall $x\in A$ and $y\in B$ $d(x,y)\geq\delta$. Put the subspace topology on $A,B,A\cup B$. Prove that $A\cup B$ is homeomorphic to $A+B$ (where $(A+B)$ is the disjoint union topology)
My proof bsically involves using the obvious map: $f:A\cup B\rightarrow((A\times \{0\})\cup(B\times\{1\}))$ such that $f(x)=\begin{cases} (x,0) & \mbox{if}\ x\in A \\ (x,1) & \mbox{if} x\in B \end{cases}$
Then I need to apply the inverse of $f$ and $f^{-1}$ to open sets in the topology and show that they are open.
My idea for doing this is to note that as these are metric spaces they have a basis of unions of open balls.
Then if f and $f^{-1}$ map the open balls to open balls then that will be enough to show that they are continuous and so $f$ is a homeomorphism.
Now if I can show that the open balls in $A\cup B$ are all of the form (open balls in A) $\cup$ (open balls in B). That is there is no open ball in $A\cup B$ which is not the union of open balls in $A$ and open balls in $B$.
Then $f$ and $f^{-1}$ obviously map open balls to open balls.
My proof that if $B(a,\epsilon)$ is an open ball in $A\cup B$ then it is the union of an open ball in $A$ and an open ball $B$.:
Take an open ball $B(a,\epsilon)\subset (A\cup B)$ for $a\in A$ or $B$ such that $\exists x,y\in B(a,\epsilon)$ for $x\in A$ and $y\in B$.
Now consider $(B(a,\epsilon)\setminus B)\subset A$. We have to show that this is open (and so it is the union of open balls in $A$). Suppose that it was closed, then:
$\exists x\in (B(a,\epsilon)\setminus B)$ such that $\not\exists\ r>0:B(x,r)\subset A$.
However as $B(a,\epsilon)$ is open in $A\cup B$ then $\exists r>0:B(x,r)\subset (A\cup B)$
Now take $i$ such that $\frac{\delta}{i}<r$ then $B(x,\frac{\delta}{i})\subset A$ and as $B(x,\frac{\delta}{i})\subset B(a,\epsilon)$ it is open. This shows that $B(a,\epsilon)\setminus B$ is open in $A$ and $A\cup B$ which gives the contradiction we require.
We can then use the same argument on $(B(a,\epsilon)\setminus A)$ to show that it is open. So any open ball in $A\cup B$ is a union of open balls in $A$ and open balls in $B$, where the open balls in $A$ and $B$ are open in $A\cup B$.
I this roughly correct (I've only given an outline of most of what I have done)
I have tagged this as homework as this was part of an assessment that I have already handed in and so is not really homework anymore but I'm not really looking for a complete solution to the problem if what I have done is incorrect just a small hint or something
Thanks very much for any help
Answer: You've proved that $B(a,\epsilon)$ is the union of an open ball in $A$ and an open set in $B$; this is good enough to get what you want, but it's not true that $B(a,\epsilon)\cap B$ is necessarily an open ball in $B$.
You're working harder than necessary, though. Let $$\mathscr{B}=\big\{B(x,\epsilon)\cap(A\cup B):x\in A\cup B\text{ and }0<\epsilon<\delta\big\}\;;$$ then $\mathscr{B}$ is a base for the subspace topology on $A\cup B$. Note that every $V\in\mathscr{B}$ is a subset either of $A$ or of $B$. If $\mathscr{B}_A=\{V\in\mathscr{B}:V\cap B=\varnothing\}$ and $\mathscr{B}_B=\{V\in\mathscr{B}:V\cap A=\varnothing\}$, then $\mathscr{B}=\mathscr{B}_A\sqcup\mathscr{B}_B$, $\mathscr{B}_A$ is a base for $A$, and $\mathscr{B}_B$ is a base for $B$. Now consider
$$\widehat{\mathscr{B}_A}=\big\{V\times\{0\}:V\in\mathscr{B}_A\big\}$$
and
$$\widehat{\mathscr{B}_B}=\big\{V\times\{1\}:V\in\mathscr{B}_B\big\}\;.$$
Comment: @hmmmm: Yes, every open set in $B$ is a union of open balls of $B$. But you claimed that $B(a,\epsilon)$ was the union of an open ball in $A$ and an open **ball** in $B$, which need not be true. $B(a,\epsilon)\cap B$ is an open **set** in $B$ but not necessarily an open **ball**. Yes, you can consider just open balls, or members of any other base for the topology. In my answer I suggested a base that makes the argument about as simple as it can get.
Comment: But isn't any open set in B a union of open balls in B as there is a basis of open balls of B?
Comment: So I just need that any open ball in  $A\cup B$ is the union of (unions of open balls in A) and (unions of open balls in B). Then when I'm using the map f I can just consider f on open balls?
Comment: Ok, cool but it is the union of (union of open balls in A) and (union of open balls in B)- this is what I should have claimed (not the union of an open ball in A and open ball in B). Thanks for the help

Subspace topologies and unions


Can the trigonometric functions be expressed, explained, or proven in terms of arithmetic?

Question: I'm trying to wrap my head around sine, cosine, and tangent. I'm aware that they're commonly defined in high schools as ratios of the various parts of triangles set in the unit circle, but that's not particularly intuitive.
Can the trigonometric  functions be expressed, explained, or proven in terms of something more intuitive, say, arithmetic? Is there a way to work out sine, cosine, and tangent on paper, without the aid of a calculator or computer?
How were they first proven or discovered? What proof might have been worked through to reach the trigonometry we have today?
Edit:
I discussed this question with a friend today. I think ultimately, what I'm looking for, is a way to work out the sine, cosine, or tangent of a given angle using paper and pencil.
Comment: The trig functions were certainly first discovered through geometry, which many people consider to be at least as intuitive as arithmetic.
Comment: Another easy way to approximate the sine for small arguments: $$\sin\,x\approx x\frac{60-7x^2}{60+3x^2}$$ For cosine, $$\cos\,x\approx \frac{72}{x^2+12}-5$$ For tangent: $$\tan\,x\approx x\frac{15-x^2}{15-6 x^2}$$ From that point, you can use the double-angle identities repeatedly for evaluating sines and cosines and tangents of larger angles.
Comment: You may be interested in the following [Wikipedia article.](http://en.wikipedia.org/wiki/History_of_trigonometry) Originally, a circle of fixed radius was chosen ($60$, $10000000$, more exotic choices) and people were interested in the length of the chord, given the length of the arc. So originally sine was a length, not a ratio.
Comment: There are formulas that approximate trigonometric functions with arbitrary given precision, that have been used and perfected since the ancient times. Those include infinite summations, infinite products, and such. It sounds like you might call them arithmetic approach to trigonometric.
Comment: $x-\frac{x^3}{6}$ is a good (and reasonably quick to compute) approximation then. Just convert all angles to their acute equivalents and go crazy. In general this has to do with what's known as the Taylor Series of $\sin(x)$, but you won't get to that till calculus.
Comment: @GerryMyerson - Of course, updated question.
Comment: The high school definition you mentioned is pretty geometric, isn't it?
Comment: What about the triangle definition do you not consider geometry?
Comment: Eh, true, it's late and I'm tired. My main goal is to figure out how to evaluate sine of X on paper.
Comment: @ThomasAndrews - Forget geometry for a sec. See my edits.
Comment: You need a lot of time to calculate trig functions with a generic argument on paper, but it is not impossible. For rough calculations, you just remember the function values at some special angles ($\frac\pi6$, $\frac\pi4$, $\frac{2\pi}3$ etc.), and then use formulas, e.g, for $\cos(x+y)$, $\sin\frac\alpha2$ etc.
Comment: @Moshe: the answer to your edited question is that it depends on what kind of angle you're given and what kind of answer you want (an exact answer? A good decimal approximation?).
Comment: Have you learned about Taylor/McLaurin series yet? That will give you the understanding of why it cannot be a finite simple formula.
Answer: Here is a very precise version of your first question:

Can a trigonometric function such as $\sin x$ be defined in terms of a finite sequence of arithmetic operations (say addition, subtraction, multiplication, division, and root extraction) on $x$ (say together with a finite number of constants)?

The answer is no. Before I get to the proof, let me make a philosophical comment. The conception of $\sin x$ as a function that takes as input a real number and returns another real number is modern. In antiquity, I would imagine that the input to $\sin$ was not a real number, it was an angle, and an angle was a geometric object, not a numerical one: you draw two lines and an angle is some property of how they intersect. Trigonometric ratios describe certain relationships between angles and lengths. I am not sure what your background is, but if you want to understand trigonometry you should pick up a good book on trigonometry.

Anyway, the proof. We will show a stronger statement, namely that $\sin x$ is not an algebraic function of $x$. Suppose to the contrary that there exist nonzero polynomials $c_0(x), ... c_n(x)$, say with complex coefficients, such that
$$c_n(x) (\sin x)^n + c_{n-1}(x) (\sin x)^{n-1} + ... + c_0(x) = 0$$
for all real $x$. The LHS is a holomorphic function of $x$, so by the identity theorem the above identity must actually hold for all complex $x$. But by Euler's formula we have
$$\sin x = \frac{e^{ix} - e^{-ix}}{2i}$$
and letting $t = ix$ be real, we see that as $t \to \infty$ the first term of the above sum grows in absolute value like a polynomial times $e^{tn}$ while the remaining terms grows in absolute value like a polynomial times $e^{t(n-1)}$; in particular, the first term eventually becomes much larger than the remaining terms in absolute value, so they cannot sum to zero, which is a contradiction. Similar arguments work for the other trigonometric functions.

As for your second question, the short answer is that it depends on what kind of angles you're interested in. For angles which (in radians) are rational multiples of $\pi$ you can get pretty far by repeatedly applying the angle addition formulas and the half-angle formula and so forth, although the general problem of computing trigonometric functions exactly (in terms of algebraic numbers) is somewhat delicate and best understood in the context of Galois theory and Kummer theory.
For angles which are not a rational multiple of $\pi$, the resulting numbers are in general transcendental, and it's very unclear to me whether there's a meaningful sense in which one can compute such a thing exactly. Instead, one computes decimal approximations, for example using Taylor series.