Only while debugging: java.io.IOException: An existing connection was forcibly closed by the remote host

Question: I have a Java application that accesses an Oracle 12 database.  When I run it outside the debugger, it runs fine.  If I try to debug it using IntelliJ's v2016.1.4 debugger, I get a java.sql.SQLRecoverableException, with the following stack trace:
java.sql.SQLRecoverableException: IO Error: An existing connection was forcibly closed by the remote host, Authentication lapse 0 ms.
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:794) ~[ojdbc8-184.108.40.206.jar:18.104.22.168.0]
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:688) ~[ojdbc8-188.8.131.52.jar:126.96.36.199.0]
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:39) ~[ojdbc8-220.127.116.11.jar:188.8.131.52.0]
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:691) ~[ojdbc8-18.104.22.168.jar:22.214.171.124.0]
    at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection(OracleDataSource.java:384) ~[ojdbc8-220.127.116.11.jar:188.8.131.52.0]
    at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:273) ~[ojdbc8-22.214.171.124.jar:184.108.40.206.0]
    at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:198) ~[ojdbc8-126.96.36.199.jar:22.214.171.124.0]
    at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:176) ~[ojdbc8-188.8.131.52.jar:188.8.131.52.0]
    at ...setDbConnection(OracleJmsQueue.java:537) [classes/:?]
    ...
Caused by: java.io.IOException: An existing connection was forcibly closed by the remote host, Authentication lapse 0 ms.
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:790) ~[ojdbc8-220.127.116.11.jar:126.96.36.199.0]
    ... 12 more
Caused by: java.io.IOException: An existing connection was forcibly closed by the remote host
    at sun.nio.ch.SocketDispatcher.write0(Native Method) ~[?:1.8.0_131]
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51) ~[?:1.8.0_131]
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93) ~[?:1.8.0_131]
    at sun.nio.ch.IOUtil.write(IOUtil.java:65) ~[?:1.8.0_131]
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471) ~[?:1.8.0_131]
    at oracle.net.nt.TimeoutSocketChannel.write(TimeoutSocketChannel.java:215) ~[ojdbc8-220.127.116.11.jar:184.108.40.206.0]
    at oracle.net.ns.NIOPacket.writeToSocketChannel(NIOPacket.java:211) ~[ojdbc8-188.8.131.52.jar:18.104.22.168.0]
    at oracle.net.ns.NIONSDataChannel.writeDataToSocketChannel(NIONSDataChannel.java:181) ~[ojdbc8-184.108.40.206.jar:22.214.171.124.0]
    at oracle.net.ns.NIONSDataChannel.writeDataToSocketChannel(NIONSDataChannel.java:132) ~[ojdbc8-22.214.171.124.jar:22.214.171.124.0]
    at oracle.jdbc.driver.T4CMAREngineNIO.prepareForReading(T4CMAREngineNIO.java:96) ~[ojdbc8-126.96.36.199.jar:22.214.171.124.0]
    at oracle.jdbc.driver.T4CMAREngineNIO.unmarshalUB1(T4CMAREngineNIO.java:534) ~[ojdbc8-18.104.22.168.jar:22.214.171.124.0]
    at oracle.jdbc.driver.T4C8TTIdty.receive(T4C8TTIdty.java:728) ~[ojdbc8-188.8.131.52.jar:18.104.22.168.0]
    at oracle.jdbc.driver.T4C8TTIdty.doRPC(T4C8TTIdty.java:639) ~[ojdbc8-22.214.171.124.jar:126.96.36.199.0]
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1544) ~[ojdbc8-22.214.171.124.jar:126.96.36.199.0]
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:518) ~[ojdbc8-126.96.36.199.jar:18.104.22.168.0]
    ... 12 more

The interesting thing is that this only happens while debugging.  I can start the Java process outside the debugger, with remote debugging enabled using JPDA, and everything runs fine.  If I then attach a remote IntelliJ debugger, the problem occurs.  If I then detach the debugger, the Java process runs normally again.  Here is the code where the exception occurs:
protected void setDbConnection(DataSource dataSource)
        throws InterruptedException {
    boolean connected = false;
    while (!connected) {
        try {
            dbConnection = dataSource.getConnection();
            dbConnection.setAutoCommit(false);
            connected = true;
        }
        catch (SQLException e) {
            int retryTime = 5000; // 5 seconds
            final String msg =
                    String.format("Unable to connect to %s.  Retrying in %s ms",
                                  dataSource, retryTime);
            logger.error(msg, e);
            Thread.sleep(retryTime);
        }
    }
    logConnectionDebugInfo();
}

Here is the debugging information available from the debugger.  I notice a SQLState of "08006", but haven't been able to find much useful information about it.  I welcome any ideas about this problem.  Mostly, I'd like to fix it, but I'd also like to hear what it is about debugging that might be causing it.  Could it be some threading issue?

Update 3/28/2018: I can debug using Eclipse's Neon.3 Release (4.6.3) debugger without seeing this problem.
Comment: After upgrading to IntelliJ IDEA 2018.1.3, I no longer see this problem.
Comment: Hi, could you please raise a ticket here: https://youtrack.jetbrains.com/issues/DBE
Comment: At this point, I'm not sure that it's IntelliJ's fault.  I will soon try with another debugger.  I also don't have an easy way of pruning the problem down into a small, repeatable test case.  However, if I get another debugger to work, I will file a bug report.
Comment: I can debug using Eclipse's  Neon.3 Release (4.6.3) debugger without seeing this problem.
Comment: Same problem with Eclipse 4.7.3a, but only in one of my workspaces... probabily a configuration problem then
Answer: I had exact same issue in my eclipse 2020-12. I removed all the breakpoints and it worked fine. Seems some breakpoints were slowing it down, then the existing connection got closed forcibly by the remote host once it time out.


Getting Bad State Value error trying to toggle variables

Question: I'm stuck on this code. I'm getting a Bad State Value (_tkinter.TclError: bad state value "SkyBlue1": must be normal, hidden, or disabled) but I am not sure what is wrong. Can anyone advise?
from tkinter import HIDDEN, NORMAL, Tk, Canvas

def toggle_eyes():
    current_color = c.itemcget(eye_left, 'fill') #check eye - white is open, blue is closed
    new_color = c.body_color if current_color == 'white' else 'white' #sets eye to opposite value
    current_state = c.itemcget(pupil_left, 'state')
    new_state = NORMAL if current_state == HIDDEN else HIDDEN
    print(new_state)
    c.itemconfigure(pupil_left, state=new_state)
    c.itemconfigure(pupil_right, state=new_state)
    c.itemconfigure(eye_left, state=new_color)
    c.itemconfigure(eye_right, state=new_color)

def blink():
    toggle_eyes() #close the eyes
    root.after(250, toggle_eyes) #wait 250 milliseconds and open the eyes
    root.after(3000, blink) #wait 3000 milliseconds, then blink again

root = Tk()
c = Canvas(root, width=400, height=400)
#sets the canvas size

c.configure(bg='dark blue', highlightthickness=0)
#sets the background color

c.body_color = 'SkyBlue1'
body = c.create_oval(35, 20, 365, 350, outline=c.body_color, fill=c.body_color)
ear_left = c.create_polygon(75, 80, 75, 10, 165, 70, outline=c.body_color, fill=c.body_color)
ear_right = c.create_polygon(255, 45, 325, 10, 320, 70, outline=c.body_color, fill=c.body_color)
foot_left = c.create_oval(65, 320, 145, 360, outline=c.body_color, fill=c.body_color)
foot_right = c.create_oval(250, 320, 330, 360, outline=c.body_color, fill=c.body_color)
eye_left = c.create_oval(130, 110, 160, 170, outline='black', fill='white')
pupil_left = c.create_oval(140, 145, 150, 155, outline='black', fill='black')
eye_right = c.create_oval(230, 110, 260, 170, outline='black', fill='white')
pupil_right = c.create_oval(240, 145, 250, 155, outline='black', fill='black')
mouth_normal = c.create_line(170, 250, 200, 272, 230, 250, smooth=1, width=2, state=NORMAL)
#make the pet

c.pack()
#arranges components in the Tkinter window

root.after(1000, blink)
#blink after 1 second of starting the program

root.mainloop()
#starts the function that listens for input events like mouse clicks

I tried setting the variables to normal or hidden first. I also tried using print statements to determine where the problem was happening. It seems to me that current_state is a null value although I can't figure out why. The pet blinks once but seems like the next time the function is called (to blink again) is when the error occurs.
Any advice? Thanks!
Answer: I think you want to set the fill color on the following two lines:
c.itemconfigure(eye_left, state=new_color)
c.itemconfigure(eye_right, state=new_color)

But you used wrong keyword state. fill should be used instead:
c.itemconfigure(eye_left, fill=new_color) # used fill keyword
c.itemconfigure(eye_right, fill=new_color) # used fill keyword

Answer: In the lines 11 and 12, Change from state to fill. I have removed c.configure in the initial configuration and added the configuration value in the c -widget itself. Removed the declaration c.body_color = 'SkyBlue1' and changed all the c.body_color into 'SkyBlue1'. Works fine.
from tkinter import HIDDEN, NORMAL, Tk, Canvas

def toggle_eyes():
    current_color = c.itemcget(eye_left, 'fill') #check eye - white is open, blue is closed
    new_color = 'SkyBlue1' if current_color == 'white' else 'white' #sets eye to opposite value
    current_state = c.itemcget(pupil_left, 'state')
    new_state = NORMAL if current_state == HIDDEN else HIDDEN
    print(new_state)
    c.itemconfigure(pupil_left, state=new_state)
    c.itemconfigure(pupil_right, state=new_state)
    c.itemconfigure(eye_left, fill=new_color)
    c.itemconfigure(eye_right, fill=new_color)

def blink():
    toggle_eyes() #close the eyes
    root.after(250, toggle_eyes) #wait 250 milliseconds and open the eyes
    root.after(3000, blink) #wait 3000 milliseconds, then blink again

root = Tk()
c = Canvas(root, width=400, height=400, bg='dark blue', highlightthickness=0)
#sets the canvas size

body = c.create_oval(35, 20, 365, 350, outline='SkyBlue1', fill='SkyBlue1')
ear_left = c.create_polygon(75, 80, 75, 10, 165, 70, outline='SkyBlue1', fill='SkyBlue1')
ear_right = c.create_polygon(255, 45, 325, 10, 320, 70, outline='SkyBlue1', fill='SkyBlue1')
foot_left = c.create_oval(65, 320, 145, 360, outline='SkyBlue1', fill='SkyBlue1')
foot_right = c.create_oval(250, 320, 330, 360, outline='SkyBlue1', fill='SkyBlue1')
eye_left = c.create_oval(130, 110, 160, 170, outline='black', fill='white')
pupil_left = c.create_oval(140, 145, 150, 155, outline='black', fill='black')
eye_right = c.create_oval(230, 110, 260, 170, outline='black', fill='white')
pupil_right = c.create_oval(240, 145, 250, 155, outline='black', fill='black')
mouth_normal = c.create_line(170, 250, 200, 272, 230, 250, smooth=1, width=2, state=NORMAL)
#make the pet

c.pack()
#arranges components in the Tkinter window

root.after(1000, blink)
#blink after 1 second of starting the program

root.mainloop()
#starts the function that listens for input events like mouse clicks


Central Limit Theorem - Significance of Sample Count

Question: According to a Khan Academy's lecture, the Central Limit Theorem is defined as follows:

Central limit theorem states that as the sample size increases, the sampling distribution of the sample mean approaches a normal distribution.

To test this definition I considered a population of 100,000 random numbers with the following parameters (see the image below)

Population Parameters:
Mean: 503.76,
  Median: 503.0,
  Mode: 338, and
  Standard Deviation: 285.72

Then, plotting the sampling distribution of the sample mean with varying sample sizes and sample counts resulted in the following observations (each graph is accordingly labeled).

Question: It seems to me that simply increasing the sample size is not sufficient for the distribution to become normal (based on visual observation). The number of samples also should be more.

Then how do I reconcile these observations with the formal definition of the theorem?
And are these conclusions correct (given the plots)?

Increasing the sample size simply reduces the standard error
As long as the sample size is above a minimum value, increasing the sample count seems sufficient for normality
Comment: I'd adapt the x-axis range to the standard error for making statements about how normal it looks. Currently you can't really see much of the distributional shape in the n=1000 plot. It doesn't look all too non-normal to me, but I can't tell either if everything is concentrated in the middle.
Comment: The statement made in the Khan quote is inaccurate; if the variance is finite (and some other conditions hold), asymptotically the distribution of the sample mean goes to a constant, the population mean (see the law of large numbers). \[However, the *standardized* sample mean $\frac{\bar{X}_n-\mu}{\sigma/\sqrt{n}}$ will go to a standard normal, or equivalently, $\sqrt{n}(\bar{X}_n-\mu)$ will [go to a normal](https://en.wikipedia.org/wiki/Central_limit_theorem#Classical_CLT) with mean $0$ and variance $\sigma^2$. This may impact how you investigate progress toward it.\]
Comment: @Lewian I plotted the graphs by adapting the x-axis range to the range of distribution and the plots still look normal. I think a better estimate of normality would be obtained through a Q-Q plot and/or by calculating Kurtosis and Skew.
Answer: Just for remaining, this is the central limit theorem :
Suppose $\{X_1, X_2, …,X_n\}$ is a sequence of i.i.d. random variables with $\mathbb{E}[X_i] = \mu$ and $\mathbb{V}ar[X_i] = \sigma^2 < \infty$. Then as $n$ approaches infinity, the random variables $\sqrt{n}(\overline{X}_n − \mu)$ where $\overline{X}_n = \frac{\sum_i X_i}{n}$ converge in distribution to a normal $\mathcal{N}(0,\sigma^2)$ :
$$\displaystyle {\sqrt {n}}\left(\overline{X}_n-\mu \right)\ {\xrightarrow {d}}\ N\left(0,\sigma ^{2}\right).$$
We can also say $$\displaystyle \frac{\left(\overline{X}_n-\mu \right)}{\sigma/\sqrt {n}}\ {\xrightarrow {d}}\ N\left(0,1\right).$$
We can see that $\mathbb{E}[\overline{X}_n] = \mu$ and $\mathbb{V}ar[\overline{X}_n] = \frac{\sigma^2}{\sqrt{n}}$.
This help us to answer your questions.
First, it is $\overline{X}_n$ which is a random variable and can be normal distributed. To plot a distibution of $\overline{X}_n$ you need many realizations or observations of this variable. Then you need many "sample count".
By increasing $n$, you still have only one value (realization of the variable). It just help you to be closer to the real value of $\mu$ due to law of large number but not to plot the law of this variable.
Second, the variance of $\overline{X}_n$ is $\frac{\sigma^2}{\sqrt{n}}$ with help you to see that as $n$ increase, the variance converge to $0$.
Answer: Is your "visual analysis" based on kurtosis? A distribution can be normal but still look pointy. Use a QQ plot and check it. Your first conclusion is correct. Your second conclusion does not seem to have a purpose. In what scenario would need to increase your sample count? In what scenario would you be able to arbitrarily increase your sample count? Also, the sample count in a sampling distribution is the sample size. Trust large sample sizes because the standard error is smaller.
Comment: By visual analysis, I meant "from the looks of it" - just eyeballing the shape of the distributions. I was also thinking of quantifying normality, though by calculating Kurtosis and Skew. Thanks for mentioning the Q-Q plot.


Redhat Ansible Tower and Gitlab deployment

Question: I am trying to deploy RH Ansible tower and GitLab on the RHEL8.3 server. I am able to deploy GitLab successfully and access it through the browser. But when I am trying to deploy Ansible Tower on the same machine, it is throwing below error. Since both the services are using the same port 80, Ansible Tower installation is failing. How to run both the Gitlab and Ansible Tower on the same machine. I am trying to run Gitlab at https://xx.xx.xx.xx:9443/ and Ansible tower at https://xx.xx.xx.xx:8443/** . Could you please help me?
<code>Aug 13 11:23:46 tower_centos nginx[893591]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in us>
Aug 13 11:23:47 tower_centos nginx[893591]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in us>
Aug 13 11:23:47 tower_centos nginx[893591]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in us>
Aug 13 11:23:48 tower_centos nginx[893591]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in us>
Aug 13 11:23:48 tower_centos nginx[893591]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in us>
Aug 13 11:23:49 tower_centos nginx[893591]: nginx: [emerg] still could not bind() ```

</code>
Answer: After long googling and research, found the below answer and it worked. You need to send the port in the ansible tower deployment
First I deployed Gitlab and then ansible tower. and then run the made

SELinux as permissive

and ran below command

./setup.sh -e nginx_https_port=8443 -e nginx_http_port=85


Validation summary display separately for each text box. in a asp.net website

Question: <code> <asp:TextBox ID="txt_Subject" runat="server" CssClass="txt_box"></asp:TextBox>
 <asp:RequiredFieldValidator ID="valSubjectRequired" ControlToValidate="txt_Subject"
                ErrorMessage="Subject is a required field." EnableClientScript="true" Display="None"
                runat="server" />
 <asp:ValidationSummary ID="ValSummary" HeaderText="" ShowSummary="True" DisplayMode="List"
                runat="server" Style="z-index: 1; left: 437px; top: 118px; color: Maroon; />
</code>
I have this text box and validation controls. I have many text box and every text box is a required field I display the error message in the validation summary. I have positioned the validation summary below the form. I have text box and labels inside the table tag. How can I display the error message next to the text box. I have to scroll down and Up to find out what are the req fields. Instead I want to display next to the text box.
Answer: If you don't want to show the validation summary then you can delete it or set the "ShowSummary" to false.  Personally I do this and then set the "ShowMessageBox" to true so the user gets an alert.
The text that displays in the alert is whatever you put in the "ErrorMessage" of the "RequiredFieldValidator".  The "RequiredFieldValidator" also has a property called "Text".  This becomes your error message next to the text box.
<code><asp:TextBox ID="txt_Subject" runat="server" CssClass="txt_box" />

<asp:RequiredFieldValidator ID="valSubjectRequired" runat="server" ControlToValidate="txt_Subject" ErrorMessage="Error message shown in pop-up"  Text="Error Message shown next to the text box" />

<asp:ValidationSummary ID="ValSummary" runat="server" HeaderText="" ShowSummary="false" ShowMessageBox="true" />
</code>
Answer: If I understood correctly, you want to display the validation error messages next to the textboxes and don't need to display them at the bottom. If this is so, remove the ValidationSummary control from the page. This results in displaying the error message where the Validator controls are placed.
Hope this helps!!
Comment: Have you tried using Display="dynamic" in all the validators?
Comment: I tried it If I remove the val summary no error message is displayed. Even though I place the validator next to the text box


How can I add a class to #markup output?

Question: I'm using this code to add a cancel button to my form.  The link is generated through #markup:
  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );

I'd like to add a class, cancel, to the link.  I tried adding this line:
'#attributes' => array('class' => array('cancel')),

but the class is not added.  I'm guessing because #attributes cannot modify #markup?  How can I add the class in this case?
Answer: You can do this...
$form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination, array('attributes' => array('class' => array('cancel')))),
    '#weight' => 20,
  );

The third argument on the 'link' function is for attributes and such...
l($text, $path, array $options = array())

Documentation: http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7
Comment: Have you tried using #prefix and #suffix? https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#prefix
Comment: This is great for that user's case, but would you know a way to make it more general on the form element itself, and not just the link generated? I'm asking because I have a similar issue, but would like to wrap the class around the entire element (#type => 'item') that's using #markup, but according to Drupal's FAPI page, #attributes isn't available for #item.
Comment: Yeah, but I was trying to do it without having to add another div; I know, one more div is somewhat inconsequential, but I try to avoid the snowball effect...


Concatenation of undef and list is undef - proof Haskell

Question: How could one prove that the following is true for every list xs:
undefined ++ xs = undefined

Comment: I've edited the question body so that it matches your title (since I judged the title to make more sense than the body). Do feel free to re-edit if I've incorrectly guessed what you meant to ask.
Answer: There is not much to prove. There is simply a rule (which can't be explained or broken down into anything smaller) that case statements which try to match undefined against a constructor result in undefined. Once you accept this rule, we can observe
undefined ++ ys
= { by definition of ++ }
case undefined of
    [] -> ys
    x:xs -> x : (xs ++ ys)
= { case that matches undefined against a constructor }
undefined


PowerShell Question: script to move my video files from separate folders on my hard drive to a central folder

Question: I have created a PowerShell script to move my video files from separate folders on my hard drive to a central folder. The script looks like this:
<code>#location of starting directory
$_sourcePath ="C:\Movies\ -recurse"
#location where files will be copied to
$_destinationPath = "C:\New\"
#Array of extension that need to move from source path
$_FileType= @("*.*mp4")
</code>
When the scrip runs, nothing happens. I get no errors, but I also don't  get an of the *.mp4 files moved.
what is wrong with this script?
Comment: there is NOTHING in that code to move anything at all. [*grin*] take a look at `Get-Help *move*` & `Get-Help *item*` for some ideas.
Comment: There is alot to unpack here. There is alot missing and alot wrong. Basically in your script you only have created 3 variables and nothing else.
Answer: Try this
<code>$_sourcePath ="C:\Movies\"
$_destinationPath = "C:\New";

$_FileType= @("*.*mp4")

Get-ChildItem -recurse ($_sourcePath) -include ($_FileType) | move-Item -Destination ($_destinationPath)`
</code>
Comment: Please explain why this works. So the OP can learn what was wrong with his script
Comment: Line number 4 of script actually performs the moving of file (move-item) after it gathers all relevent file ( get-childitem). Recurse is used here for going deep down the subfolders if any.


How are the hashes in /etc/shadow generated?

Question: I was reading the Wikipedia article on the shadow file and it mentioned the format of the lines is like this:
$id$salt$hashed

So, my question is, how does it work?
I tried to calcualte the hash for my own account to which I had the password so I used this command:
sha512sum
{salt}+{my_clear_text_password}
But the output is different from the hash I see for myself. So how does it work? What am I missing?
Answer: A couple of things to think about (you'll have to read the sources in the Linux coreutils and glibc2 to confirm)

The output of sha512sum appears to be printable hex notation whereas the output stored in the shadow file appears to be base64 so they will be different.
I think that the sha512sum in the shadow file has been passed through the hash function more than once ( #define ROUNDS_DEFAULT 5000 ) whereas the sha512sum just passes the 'file' through the hash once.
There may be padding added by one or both commands to align the data it may be different.
Answer: If you want to create the hash in the same way that the /etc/shadow file stores it, use the following command:
mkpasswd --method=sha-512 --salt=YOUR_SALT PASSWORD

Comment: The output of this command contains chars not present in the output of `sha512sum`. Is there some more encoding going on for the hash output stored in /etc/shadow?
Answer: From the shadow(5) man-page:

encrypted password
Refer to crypt(3) for details on how this string is interpreted.
If the password field contains some string that is not a valid result of crypt(3), for instance ! or *, the user will not be able to use a unix password to log in (but the user may log in the system by other means).
This field may be empty, in which case no passwords are required to authenticate as the specified login name. However, some applications which read the /etc/shadow file may decide not to permit any access at all if the password field is empty.
A password field which starts with a exclamation mark means that the password is locked. The remaining characters on the line represent the password field before the password was locked.

From the crypt(3) man-page:

crypt() is the password encryption function.  It is based on the Data Encryption Standard algorithm with variations intended (among other things) to discourage use of hardware implementations of akey search.
key is a user's typed password.
salt is a two-character string chosen from the set [a–zA–Z0–9./].  This string is used to perturb the algorithm in one of 4096 different ways.
By taking the lowest 7 bits of each of the first eight characters of the key, a 56-bit key is obtained. This 56-bit key is used to encrypt repeatedly a constant string (usually a string consisting of all zeros). The returned value points to the encrypted password, a series of 13 printable ASCII characters (the first two characters represent the salt itself). The return value points to static data whose content is overwritten by each call.
Comment: Seems like a sane answer to me. No idea why it was voted down...
Comment: It's talking about `crypt` encoded passwords. `SHA-512` is very different.
Comment: It should be noted that the glibc2 version of crypt() supports different algorithms (MD5, SHA-256, SHA-512, and, on some systems, Blowfish) depending on the salt value. See the "Notes" section of the man page for crypt(3).


converter código javascript para jquery

Question: Como ficaria esse código em javascript:
 var ctx1 = document.getElementById("GraficoDonut1").getContext("2d");
    new Chart(ctx1).Doughnut(data1, options);
    legend(document.getElementById("lineLegend1"), data1);

Em jQuery?
Comment: Por quê o interesse em fazer em jQuery? Me parece sucinto esse código.
Comment: Se o código em questão é esse deixa como está. O jQuery está a ser cada vez menos usado. jQuery é feito com JavaScript, por isso quanto menos jQuery melhor.
Comment: Já uso o jQuery no meu projeto, e o código fica bem mais simples e menor.
Answer: Não há muito o que fazer no seu código, apenas pegar os elementos pelo #id via jQuery.
var ctx1 = $("#GraficoDonut1")[0].getContext("2d");
new Chart(ctx1).Doughnut(data1, options);
legend($("#lineLegend1")[0], data1);

Comment: Mas como foi dito, não há necessidade de usar jQuery aí, a performance do JavaScript puro é muito maior.

converter código javascript para jquery


Renaming Download File Using Header in PHP

Question: i have a link pointing to a music file on my site, now the name of the file was hashed when it was uploaded so i want to use the original filename which i have stored in my database, I did some research and found this new 'download' attribute for the 'a' tag but that only works in later versions of firefox and chrome, it doesn't work in ie and also doesn't work with the download manager i use so i checked online and found out about headers which i then implemented.  I now get the filename changed allright but the music file keeps on getting saved as a '11.35kb' filesize no matter the music file i try to download.  This is my code:
if (isset($_REQUEST['download']))
    {
        $download_id = $_REQUEST['download'];

        $db = new MysqliDatabase(ConnectionString);
        $result = array();
        $result = $db->query_one("SELECT TrackID, ma.ArtisteName, FeaturedArtistes,
                                  mc.Category, TrackName
                                  FROM `musictracks` mt

                                  LEFT JOIN `musiccategories` mc
                                  ON mt.CategoryID = mc.CategoryID

                                  LEFT JOIN `musicartistes` ma
                                  ON mt.ArtisteID = ma.ArtisteID

                                  WHERE mt.TrackID = '$download_id';");

        $filename = $result->TrackPath;
        $outputfilename = $result->ArtisteName . ' ft. ' . $result->FeaturedArtistes . ' - ' . $result->TrackName . '.mp3';

        header("Content-Type:  audio/mpeg");
        header("Content-Disposition:  attachment; filename=\"" . basename($outputfilename) . "\";" );
        header("Content-Transfer-Encoding:  binary");
        readfile("$filename");
    }

And this is the download link:
<a href="<?php echo 'musicdownload.php?download='. $row->TrackID ?>" >

Comment: So read it - change .mp3 to .html and open in browser. Probably there is error message
Comment: What does the 11.35kb file contain?
Comment: Put some mp3 file on server and try it download directly - maybe there is some problem with server. And check your `$filename` - maybe it is not what you expect.
Comment: It is saved as a music file but when i try playing it it doesn't work.
Comment: Open this file in notepad - maybe inside is text/html with error message
Comment: Maybe you need to add fullpath to `$filename`.
Comment: comment the header() calls and look at the output, there are probably errors. also: remove the `Content-Transfer-Encoding` header, it should not be used in this case and might cause unexpected browser behaviour (see here: http://stackoverflow.com/questions/7285372/is-content-transfer-encoding-an-http-header)
Comment: Okay i opened it in notepad++ and it seems it contains html code instead.
Comment: Is `$result` an array or object? You first declare it as the former and use it as the latter (what does `query_one` return?).
Comment: Okay thanx alot i opened it in notepad++ and saw the error it was generating, apparently i was having some trouble with my columns so it wasn't returning the data i wanted, rookie mistake :D, Thanx alot.
Answer: My PHP is a bit rusty but I can think of one thing with your code, no content length header. Update your code to this and see if that works:
if (isset($_REQUEST['download'])) {
  {
    $download_id = $_REQUEST['download'];

    // ...

    $filename = $result->TrackPath;
    $outputfilename = $result->ArtisteName . ' ft. ' . $result->FeaturedArtistes . ' - ' . $result->TrackName . '.mp3';

    if (file_exists($filename)) {
      header("Content-Type:  audio/mpeg");
      header("Content-Disposition:  attachment; filename=\"" . basename($outputfilename) . "\";" );
      header("Content-Transfer-Encoding:  binary");

      header('Content-Length: ' . filesize($filename));
      ob_clean();
      flush();
      readfile($filename);
      exit;
    }
  }
}

Note that we use flush(); to send the headers to the browser before we start downloading the actual file. And I also added an if (file_exists($filename)) to make sure we have a file to send. I'd recommend you put an else clause there to give you something that will show you if you don't have a file like you expect...
Answer: header("Content-Type: application/force-download");
        header("Content-Type:audio/mpeg");
    header("Content-Type: application/download");;
        header("Content-Disposition: attachment;filename=".$file_name);

Answer: Please download your mp3 files using curl
Here is sample code for your reference
<?php

if(isset($_REQUEST['inputurl']) && $_REQUEST['inputurl']!="") {

$file = $_REQUEST['inputurl'];

header("Content-type: application/x-file-to-save");
header("Content-Disposition: attachment; filename=".basename($file));
readfile($file);

}

?>

<form name="from" method="post" action="">
<input name="inputurl" type="text" id="inputurl"  value="" />
<input type="submit" name="Button1" value="Get File" id="Button1" />
</form>

may be it will help you.


How can I choose type of regression for panel data?

Question: I would like to do a research thesis where I investigate whether exists a linear relationship among a ratio commonly used by firms and a set of dependent variables. I know this is very general but I'm looking to have a clear understanding of how the statistical analysis should be run so that my results make sense. From my current idea I have a single dependent variable - the ratio - , 6 independent numeric variables which depend on the country of origin of the company and are constant over time, plus some financial variables which should serve as control variables. I want to randomly collect data from a specific database for a 10-year period so I will probably end up with an unbalanced panel.
I have zero experience with econometrics but after some research it seems that there are 3 main methods to deal with panel data for my purposes: 1) Pooled OLS - which to my understanding is basically the standard linear regression applied to panel data –  ; 2) Fixed Effects ; 3) Random Effects . I noticed that some papers related to my idea test two or three models and compare them while others just choose one - without really explaining why - and assess the results. My first concern is which option is better. I think that using more than a model can lead to more "robust" results, but if I don't get significant coefficients in one of them comparisons might be more difficult. On the other hand, I fear choosing only one model might lead to criticism such as "you used this model which assumes x so your results are weak".
Also, I see that many papers say something along the lines of "we control for year and industry fixed effects". Can this be done regardless of 1) 2) 3) regression method or only by using a specific model? I'm trying to understand when different models should be used conceptually rather than their correctness from a statistic POV, since it seems they all have some advantages and drawbacks. For example, the textbook "Econometric Analysis of Panel Data" by Baltagi says "FE estimator cannot estimate the effect of any time-invariant variable like sex, race, religion, schooling or union participation." But if I have 6 time-invariant independent variables, does this mean I should never use FE, even if the Hausman test tells me otherwise? Any help would be appreciated, thank you in advance and sorry for the length of the thread.
Answer: This is a big question with no right answer. A lot depends on your audience and field. The fact that you are citing Baltagi suggests you might be in the econ area. If so, you are going to have a hard time convincing colleagues/readers that random effects are appropriate unless you want to do something that absolutely cannot be done in a fixed effects model. Estimating the effect of time-invariant or firm-invariant predictors is an example of something that is a no-go in fixed effects models. But many in the econ audience probably would argue that you can't trust those effects anyway because of endogeneity (correlations between level-2 covariates and the random intercepts).
Note that you can get around this problem and estimate firm effects if you have an even higher level of nesting. Let's say firms are nested within countries. By including the country-specific means of the firm variables in the random intercepts model, these firm-level predictors become within-firms effects. This is a known way to get around lower-level endogeneity in random effects models, which was elaborated upon by Mundlak (1978).
One thing you should be careful about is including firm and year fixed effects in the same model. Recent methodological work shows that models like this ("two-way fixed effects") have some problems. See work by Kropko & Kubinec (2020) and Imai & Kim (2021). Note that within a random effects model where firm is the level-2 cluster variable, you could easily include time fixed effects (0/1 indicator variables for each year of data). But in random effects models, time is often treated continuously and included as a random slope, especially if the trend in the outcome is systematic and varies across firms. This is known as a growth curve model.
References
Mundlak, Y. 1978. On the pooling of time series and cross section data. Econometrica 46: 69–85
Comment: Thank you for your answer and yes, I'm a business student and guess this would fall under corporate finance. So to my understanding FE wipes out the 6 time-invariant variables I want to study. These only depend on firm's country and not on any firm's characteristic, but RE also assumes my control variables are uncorrelated with unobserved variables which is false. Could I work around this with a Correlated Random Effects model where I include averages of all my control variables, which are the only ones varying with time?
Comment: The approach I referred to in my answer, by Mundlak (1978), is, I believe, equivalent to a correlated random effects model. In that case, you are taking care of endogeneity of the time-varying variables but not the time-invariant variables. You can add additional time-invariant covariates to deal with level-2 endogeneity, but ultimately you are relying on a control on observables strategy. That's acceptable in many fields. The question is whether it is acceptable in yours.


(Soft Question) Is it bad to use Sage built in functions instead of creating my own?

Question: I've been doing Project-Euler just as a way to increase my competency in computer science.  I'm currently a Pure and Applied Math major who recently adopted computer science as a minor in order to apply to grad schools in comp. sci.
Some built-in Sage functions that are extremely fast and I do not have comparably fast definitions include gcd, lcm, .intersection(), .is_prime(), prime_range(), .factor(), solve(),...
Many Project-Euler problems I've been able to solve relatively easily and quickly with these built-in functions but when I see the forums after answering the question, other people's answers are quite lengthy (as they are writing they're own code).
I'm debating if my method of getting through Project-Euler is truly a learning environment.  I'm definitely learning more Sage commands and getting better at using Sage but I'm not sure my coding is getting any better unless I make my own definitions.
In essence what is the transition period between using built-in definitions to strictly using your own independently created code?  Or what's more beneficial, being able to create your own relatively fast code or getting the job done as fast as possible (using built-in methods)?
Answer: It depends upon what your goal is for doing Project Euler. Many of the later problems need creative problem solving skills rather than brute force for their approach so for me I use it as a means to involve my problem solving and algorithm design skills rather than my programming skills in a specific language. If you want to do both make sure you could write each of the functions you are using and then test and compare your versions to the built in ones. Yours will probably not be as fast but they should have a similar big O notation for their speed.
Answer: From the perspective of a programmer/coder, it isn't a bad practice to use inbuilt functions when you can (in fact, people are lazy, if there's an inbuilt function, why do the work of manually defining another?)
Now, from the perspective of a mathematician, the aim of the problems there is to motivate you to understand algorithms properly (i.e., understand how it works, how the algorithm is constructed from basic tools) and then implementing them on your own to solve those problems.
Take your $\gcd()$ function for example. The mathematician's way to solve this would be implementing the Euclidean algorithm (recursive definition to find gcd). There's a one-line definition for it :
<code>int gcd(int a,int b){
    return (b==0) ? a : gcd(b,a%b);
}
</code>
For lcm, you can just use the fact that $\textrm{lcm}(a,b)\gcd(a,b)=ab$ for positive integers $a,b$.
And similarly, you can think up of algorithms for all the other functions. After all, those inbuilt functions were programmed from scratch by someone using these basic mathematical algorithms.
So, in conclusion, there's no good or bad side to this, it just depends on your perspective. But since you're majoring in Mathematics and not Comp Sci, I'd recommend using inbuilt functions as rare as possible (use only when you can't think of an elementary algorithm to do it). If you do use an inbuilt function, try to search for a mathematical algorithm afterwards if you can and understand it well, so as to gain experience.


What is the relation between key and 'feeling' of a song?

Question: I think I experience a different feeling to a song when it's played in a different key, which I think makes no sense, except that all frequencies will be higher or lower compared to the original key. I'm no expert when it comes to musical terms or the technical details of sound, but is there a relation, or do I falsly asume there is one? The relation between notes does not change in a different key, or does it?
To me a song written in a key containing flats is more "soft" or "gentle", songs with sharps feel more "bright". I'm not a native english speaker, so expressing the subtle differences is somewhat difficult.
Comment: If played on the piano or other equal tempered instrument, the number of sharps or flats should not matter, since they are the same note, as you say. Also, if you are aware of the key when listening, perhaps your feelings are influenced by your expectations, in this case the notion that flat keys are soft and sharp keys bright?
Comment: Could very well be my expectation, that's why I'm looking for a technical explanation. Can you clarify what would change on non-equal tempered instruments?
Comment: http://music.stackexchange.com/questions/32438/colour-of-keys-in-the-era-of-equal-temperament?rq=1
Comment: It would differ depending on instrument, of course, but say for a piano tuned to an older/non-equal temperament some keys/chords would beat more and some less, making them sound different.
Answer: The discussion is still alive after several hundred years. There were times, were there was a sort of agreement, that a death scene has to be in this key and erotic scenes in that one and victory in another.
The chromatic argument is thin - for once orchestras as a whole and many instruments allow finer modifications of pitch. On the other hand the harmonics spectrum changes for real instruments from tone to tone. The result may well sound different.


Não consigo utilizar o shell no docker-compose

Question: estou desenvolvendo uma aplicação Python com MYSQL no docker-compose, só que não é uma aplicação web, teria alguma forma de rodar essa aplicação no contêiner pelo shell ? se tiver, vocês poderia me explicar como?
se não fosse pelo docker compose: eu utilizaria o comando:
docker run -it nomedoprojeto
E esse comando me liberaria o shell do container
se não tiver como rodar o shell pelo docker-compose, como faria para fazer a comunicação de uma imagem MYSQL com a minha imagem da aplicação??
Comment: Seja bem vindo ao SOpt. Por favor adicione o seu docker compose à pergunta, para que as demais pessoas possam apontar o que é necessário alterar.
Answer: Depois que o container subiu, você pode ativar um shell dentro dele (já em execução), usando docker exec em vez de docker run:
docker exec -it nome-do-projeto /bin/bash
Comment: Obrigado !
mas teria algum comando que eu poderia utiliza no Dockerfile ou no Docker-compose que já inicia-se no modo interativo, assim que eu subisse o contêiner.

É de suma importância essa resposta,
pois, a aplicação só roda no shell, e está dando erro na hora de subir, por conta disso!
Comment: o docer-compose é feito para ser chamado "de fora" do docker - não teria sentido chamar o docker-compose pra subir os containers e ele "roubar" o terminal.

O que você pode fazer é um outro script, curtinho - pode ter apenas duas linhas, que chama  o docker-compose _e_ roda o docker exec como está acima.
se você simplesmente colocar os comandos um abaixo do outro, isso é um script shell válido. Na primeira linha ponha  `#! /bin/sh`, segunda linha, `docker-compose up` (ou o que você estiver usando) e última linha `docker exec ...` - mude o script para executável com `chmod o+x `
Comment: certo, vou seguir suas orientações, Muto Obrigado


If $A$ is a ring, then why is $\operatorname{Proj} A[t] \cong \operatorname{Spec} A$?

Question: The following is an example I saw in a book on Algebraic Geometry.

Example: Let $A$ be a ring and consider $A[t]$, with the grading given by $\deg t = 1$ and $\deg a = 0$ for $a \in A$. Then the structure map gives an isomorphism $\operatorname{Proj} A[t] \cong \operatorname{Spec} A$

By structure map, the authors mean a morphism of schemes $\varphi : \operatorname{Proj} A[t] \to \operatorname{Spec} A$. I am not sure exactly what this morphism would be however, I assume that we start off with the standard embedding $A \hookrightarrow A[t]$ and then apply the functor $\operatorname{Spec}$ to get a map $\operatorname{Spec} A[t] \to \operatorname{Spec} A$ and then pre-compose that with the inclusion $i : \operatorname{Proj} A[t] \to \operatorname{Spec} A[t]$ to get the desired morphism $\varphi$.
Now firstly, the $\operatorname{Proj}$ construction only works for graded rings. So $A[t]$ should be of the form $A[t] = \bigoplus_{d \geq 0} A_d$. The authors say above "the grading given by $\deg t = 1$ and $\deg a = 0$ for $a \in A$", and I assume that this means that $A_0$ is the image of the standard inclusion of $A$ in $A[t]$, and that $A_1 = (t)$, the ideal generated by $t$ so that "essentially" $A[t] = A_0 \oplus A_1 = A \oplus (t)$. Is this the correct interpretation?
Now onto the claim that the $\varphi$ yields an isomorphism. I don't even see why $\varphi$ is a bijection, let alone a homeomorphism. If I label the embedding $A \hookrightarrow A[t]$ as $j$, then $\varphi$ is given by $\varphi(\mathfrak{p}) = j^{-1}(\mathfrak{p})$ for any $\mathfrak{p} \in \operatorname{Proj} A[t]$ and to say that $\varphi$ is bijective would mean that every prime ideal $\mathfrak{q}$ of $A$ is of the form $\mathfrak{q} = j^{-1}(\mathfrak{p})$ for some unique $\mathfrak{p} \in \operatorname{Proj} A[t]$ and for starters I do not see why this would be the case.
Furthermore I would need to show that the morphism of sheaves $\varphi^\sharp : \mathcal{O}_{\operatorname{Spec} A} \to \varphi_* \mathcal{O}_{\operatorname{Proj} A[t]}$
is also isomorphic and the way one usually does is by looking at basic open sets on $\operatorname{Spec} A$. In more words -  if I wanted to see what $\varphi^\sharp$ would be in this case, then if I chose an $f \in A$ and considered the open subset $D(f) \subseteq \operatorname{Spec} A$ then $\Gamma(D(f), \mathcal{O}_{\operatorname{Spec} A}) \cong A_f$. But $$\Gamma(D(f), \varphi_*\mathcal{O}_{\operatorname{Proj} A[t]}) = \Gamma(\varphi^{-1}(D(f)), \mathcal{O}_{\operatorname{Proj} A[t]})$$ and this may not have such a nice form as far as I know, since $\varphi^{-1}(D(f))$ might not be a basic open subset of $\operatorname{Proj} A[t]$. So I cannot express $\varphi^\sharp_{D(f)} : \Gamma(D(f), \mathcal{O}_{\operatorname{Spec} A}) \to  \Gamma(\varphi^{-1}(D(f)), \mathcal{O}_{\operatorname{Proj} A[t]})$ in any nice way to allow me to check that $\varphi^\sharp$ would indeed be an isomorphism.
Comment: "The grading given by $\deg t=1$...." surely means that $\deg t^2=2$ and so on, so that the grading is $A[t] = A \oplus tA \oplus t^2A \oplus \cdots$.
Comment: The idea is that $\operatorname{Spec} A[t]$ is a "line over $\operatorname{Spec} A$" and $\operatorname{Proj}$ is the set of lines in $\operatorname{Spec} A[t]$ (of which there is just one). So $\operatorname{Proj} A[t]$ is a "point over $\operatorname{Spec} A$" and a "point over $\operatorname{Spec} A$" is just $\operatorname{Spec} A$. I'll try to write a more rigorous explanation when I have more time, if nobody else gets to it.
Comment: Surely you mean $\operatorname{Spec} A$, not $\operatorname{Spec} A[t]$?
Comment: Oh yes, you are right! This question needs to be edited. I will do that now
Answer: For $R$ a graded ring, $\operatorname{Proj} R$ has as its underlying set the homogeneous prime ideals of $R$ which do not contain the irrelevant ideal. In our case, the irrelevant ideal is $(t)$, and so no homogeneous prime ideal in $\operatorname{Proj} A[t]$ contains $t$. So $D_+(t)\subset\operatorname{Proj} A[t]$ is all of $\operatorname{Proj} A[t]$, and therefore by the identification $D_+(t)\cong \operatorname{Spec} A[t]_{(t)}$ (where this denotes the homogeneous localization, or $(A[t]_t)_0$) and the observation that $A[t]_{(t)}=A$, we see that $\operatorname{Proj} A[t]\cong\operatorname{Spec} A$.

If you want to get more hands-on, you can verify that any homogeneous prime $P\subset A[t]$ not containing the irrelevant ideal is exactly specified by it's intersection with $A$. For every homogeneous element $at^n\in P$, we get that either $a\in P$ or $t\in P$ by primality of $P$. By the assumption that $(t)\not\subset P$, the former must be the case, so $P$ is the ideal generated by $P\cap A$. Thus there's a bijection as sets between $\operatorname{Proj} A[t]$ and $\operatorname{Spec} A$, and one can verify that this induces a bijection between basic open sets ($D(a)\subset \operatorname{Spec} A$ and $D_+(f)\subset \operatorname{Proj} A[t]$ where $f$ is homogeneous of positive degree), so it is even a homeomorphism.
Comment: @TrevorGunn I mean the [homogeneous localization](https://stacks.math.columbia.edu/tag/00JN) - that is, the degree-zero portion of $A[t]_t$. It's unfortunate that the notation is so close to the localization at the ideal $(t)$.
Comment: There are a few things wrong with the first half of your answer and I'm not sure what the best way to fix it is. First, $D(t)$ should be the localization at $t$ not at $(t)$. So that should be $A[t,t^{-1}]$. Second, taking Spec of that isn't right because that considers in-homogeneous primes as well. And lastly, I don't believe one can obtain $A$ (generally) as a localization of $A[t]$; the correct identity would be $A \cong A[t]/(t)$.


Mobile css reverts back to desktop version of site on smartphone

Question: I'm using a basic method of "mobilizing" my desktop site using different style sheets. At the top of every page of my site, I have this:

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://scoresquare.net/css/screen.css" type="text/css" media="Screen" />
<link rel="stylesheet" href="http://scoresquare.net/css/mobile.css" type="text/css" media="handheld" />

Whenever a user logs into my site from a smartphone, it goes to the home page [index.php] which also has the abovementioned code at the top. There are eight buttons on the home page, and whichever choice the user makes, the site properly displays the mobile version on their smartphone.
HOWEVER, whenever the user decides to return to the home page via a button on any other page, index.php displays in the DESKTOP version on their smartphone. In other words, index.php displays properly the first time on a smartphone, but not the second (and every subsequent) time.
If the user just hits the BACK button on his smartphone browser to get back to the home page, index.php displays the proper mobile format.
FWIW, each home page button involves my program querying a SQL database and returning data (which works just fine). Does this somehow reset the style sheet functionality?
If it matters, mymobile.css looks like this:
/* mobile styles */
@media handheld {

html, body {
    font: 12px/15px sans-serif;
    background: #fff;
    padding: 3px;
    color: #000;
    margin: 0;
    }
#sidebar, #footer {
    display: none;
    }
h1, h2, h3, h4, h5, h6 {
    font-weight: normal;
    }
#content img {
    max-width: 250px;
    }
.center {
    width: 100% !important;
    text-align: center;
    }
a:link, a:visited {
    text-decoration: underline;
    color: #0000CC;
    }
a:hover, a:active {
    text-decoration: underline;
    color: #660066;
    }
    }
/* iPad [portrait + landscape] */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
.selector-01 { margin: 10px; }
.selector-02 { margin: 10px; }
.selector-03 { margin: 10px; }
    }
 /* iPhone [portrait + landscape] */
@media only screen and (max-device-width: 480px) {
.selector-01 { margin: 10px; }
.selector-02 { margin: 10px; }
.selector-03 { margin: 10px; }
}

Any idea what might be causing this?
Comment: Have you tried other media queries? Something like `media="only screen and (max-device-width:480px)"`?
Comment: I think your media type isn't valid ("handheld"). Try Caleb's suggestion and I feel like it will solve your problem.
Answer: Strange that it works on the first load!
The valid media types are "all," "print," "screen," and "speech." In current practice, "screen" is often considered equivalent to "all", and the type is simply left out (leaving media type specification for cases of print-only and screen reader-only styles).
Media queries in a linked stylesheet will look something like
<link rel="stylesheet" media="(max-width: 800px)" href="example.css" />

(that was copied from this write-up of how to use media queries)
In your case, the final markup will be similar to
<link rel="stylesheet" href="http://scoresquare.net/css/screen.css" type="text/css" />
<link rel="stylesheet" href="http://scoresquare.net/css/mobile.css" type="text/css" media="(max-width: 400px)" />

(I don't know what width you're using as a "handheld" breakpoint, so I just used 400px. CSS-Tricks' Media Queries for Standard Devices is one good reference for max-width mobile break points… it's rare that you'd bother targeting a specific device, but for example this shows you that a breakpoint at 800px will catch the most popular tablets)
Comment: Thanks for the prompt response, but I'm afraid this doesn't work. It still defaults back to a desktop version on my smartphone (tho it works fine on my tablet)

Feel free to visit the main site on your own smartphone and see for yourself (you must sign up for an account, but just enter a dummy email address). Still baffled.
Comment: Strange. Is it possible it's a different page? Maybe you have an extra copy of the main page, and you're linking to the wrong one (that's actually happened to me before). No offense but browser malware has slipped through my defenses before so I'm a little wary of signing up for your site.
Comment: Completely understand about signing up for the site. I only have a single index.php.  Could it have anything to do with the way I link back to index.php? [button vs. input, onclick vs. a href only, etc.?]
Comment: No, a page is a page regardless of how you got there. Did you double check to the see that the loading source has the fixed ``s? Maybe the old version is cached and still being used
Comment: Sorry - what do you mean by "loading source"? And how would I change/clear the cached version?


Optional param not working in jersey using regex

Question: I am working to cater REST url of three types:

url/detail/3    (integer only)
url/detail/hello    (String only)
url/detail/3/1d

For URL 1 and 3 I am using method1 and for URL 2 method2 is used.
Problem 1: All requests type of 1 and 2 matches method 2 only.Though I've specified Integer pattern in method 1 for queries having integer specifically.
Problem 2: To use an optional param (like in 3) I am using method1 because jersey doesn't provide any option for optional param.But url types of url/detail/3/1d   is never matched as specified in method 1.
Please help me understand what I am doing wrong as I am newbie to jersey.
@GET
@Path("/detail/{id: \\d+}/{time-period:(/time-period/[^/]+?)?}")

@Produces({ MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_JSON)
public JResponse method1(
        @Context HttpHeaders headers,
        @PathParam("id") String id,
        @PathParam("time-period") String timePeriod) {
    if(timePeriod == null || timePeriod.equals(""))
    {
        //code
    }
    else
      //code
}
@GET
@Path("/detail/{name}")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_JSON)
public JResponse method2(
        @Context HttpHeaders headers, @PathParam("name") String name) {
    //code
}

Answer: Maybe a missing whitespace leads to the problem. See Optional @PathParam in Jax-RS
You can define default values for parameters with @DefaultValue("1000")
Answer: Instead of complicated regexps you should probably use subresource.
Answer: @Path("detail/{id}{time-perioid:(/[^/]+?)?}")
http://x.y.z:4080/analytics/internal/detail/kala
2014-01-17 07:35:50,509 [http-nio-4080-exec-8] INFO  xxx - id: kala
2014-01-17 07:35:50,510 [http-nio-4080-exec-8] INFO  xxx - time-period:
and
http://x.y.z:4080/analytics/internal/detail/kala/123
2014-01-17 07:36:01,644 [http-nio-4080-exec-9] INFO  xxx - id: kala
2014-01-17 07:36:01,645 [http-nio-4080-exec-9] INFO  xxx - time-period: /123
If id can be string or integer I would go validating it inside handler.


How do I get the current node ID?

Question: In Drupal 7, if I wanted to get the node id of the currently displayed node (e.g. node/145) I could get it with the arg() function. In this case, arg(1) would return 145.
How can I achieve the same in Drupal 8?
Answer: The parameter will have been upcasted from nid to full node object by the time you get access to it, so:
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

See the change record for more information.
Comment: I just want to add you have to careful with this - I just got stung where \Drupal::routeMatch()->getParameter('node'); will return an array of 1 item (the node id) on node revision delete pages, so if you calling a method on what you assume to be an object you will get a fatal error like "Fatal error: Call to a member function getType() on string".
Comment: Is this a functional replacement for ```menu_get_object```?
Comment: @AshwinP The parameter is whatever you write inside `{}` in your route. For taxonomy terms the route paramater is called `taxonomy_term`, route definition `/taxonomy/term/{taxonomy_term}`. Here you can get it like this, `\Drupal::routeMatch()->getParameter('taxonomy_term')`.
Comment: This code isn't working for *unpublished* node when the user doesn't have the permission to see it.
This code `$node = \Drupal::requestStack()->getCurrentRequest()->get('node');` will correctly load the node.
Comment: How can I get parameter, if I visited `/taxonomy/term/{tid}`?
Comment: Pretty much yes @Frank. It's a bit different of course, but if you're dropped in a context that doesn't know what entity page (if any) it's on, this is the recommended way to find out
Comment: BTW, there's a d.o issue to resolve the revision inconsistency: https://www.drupal.org/project/drupal/issues/2730631
Comment: As Jeff said, on the revisions urls, $node won't be a loaded instance of Node but a string. the node string, not the revision node id.
/node/1653/revisions/2188/view
Be carefull
Comment: The check against NodeInterface should no longer be needed as Drupal now consistently upcasts on node revision routes, see this change record from May 2021: https://www.drupal.org/node/2942013
Answer: It is correct to use \Drupal::routeMatch()->getParameter('node'). If you just need the node ID, you can use \Drupal::routeMatch()->getRawParameter('node').
Answer: Note on the node preview page, the following doesn't work:
$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->id();

For the node preview page, you have to load the node this way:
$node = \Drupal::routeMatch()->getParameter('node_preview');
$nid = $node->id();

How to load node object in node preview page?
Answer: if you are using or creating custom block then you have to follow this code to get current url node id.
// add libraries
use Drupal\Core\Cache\Cache;

// code to get nid

$node = \Drupal::routeMatch()->getParameter('node');
  $node->id()  // get current node id (current url node id)

// for cache

public function getCacheTags() {
  //With this when your node change your block will rebuild
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
  //if there is node add its cachetag
    return Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
  } else {
    //Return default tags instead.
    return parent::getCacheTags();
  }
}

public function getCacheContexts() {
  //if you depends on \Drupal::routeMatch()
  //you must set context of this block with 'route' context tag.
  //Every new route this block will rebuild
  return Cache::mergeContexts(parent::getCacheContexts(), array('route'));
}

Comment: This answer is 100% incorrect. Do not do this.
Answer: By using Service,
    use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Provides a 'UtilitiesDataService' service.
 */
class MyClass {

  /**
   * The route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Constructs a new service.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   */
  public function __construct(RouteMatchInterface $route_match) {

    $this->routeMatch = $route_match;
  }

  public function getNodeId(){
    $nid = $this->routeMatch->getParameter('node')->id();
  }
}

In services.yml file,
services:
   my_module.get_data_service:
    class: Drupal\my_module\MyClass
    arguments: ['@current_route_match']

Comment: I think it is correct. A similar example is also in change record link Clive has provided.
The example Sneha has provided is better than a static call others have provided.
Comment: Procedural code would still need to make a static call to `\Drupal`. In this case, using the service defined in this answer or the *current_route_match* service doesn't make any difference, which means the static call isn't removed.
Comment: Agree with @apade. This isn't providing any benefit over making the call to the CurrentRouteMatch class.
Comment: This is not "by dependency injection" - this is the creation of a new service. You're going to write a new service just to wrap one method of the existing current_route_match service? This is just wrong. Use @Clive's answer, which accesses the current_route_match service directly.
Answer: Blocks are context aware and you should be using them. This will allow using the blocks in places where the route itself doesn't have a node but some subsystem provides the context anyways.
Example from core:
/**
 * Provides a 'Node Context Test' block.
 *
 * @Block(
 *   id = "node_block_test_context",
 *   label = @Translation("Node Context Test"),
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
 *   }
 * )
 */
class NodeContextTestBlock extends BlockBase {

  public function build() {
    /** @var \Drupal\node\NodeInterface $node */
    $node = $this->getContextValue('node');

You can also see how easy it is to get the node. The test this block is used for is instructional: it tests whether the block appears on the preview page. This is not doable with the route match approach as the /node/preview/{node_preview}/{view_mode_id} route doesn't contain a node at all.
This will also make the node context required so there's no need to check whether there is a node at all. It's possible to make the node optional, of course:
 *     "node" = @ContextDefinition("entity:node", label = @Translation("Node"), required = FALSE)

the order of options after the first argument does not matter.

How do I get the current node ID?


How can I get the minimum value of a column based on the another column value?(I don't think this is a duplicate, couldn't find any answer here)

Question: Hello I have this dataframe:
dict = {'Group':[234, 345, 234, 456], 'Value':[5000, 2000, 1000, 3000], 'name':['abc','def','ghi','jkl']}
df = pd.Datafram(dict)

df:
   Group  Value name
0    234   5000  abc
1    345   2000  def
2    234   1000  ghi
3    456   3000  jkl

I want to get the minimum value from the column value depending on the group and put it in a new column next to name:
For example for the Group '234' the minimum value will be '1000' and I want the new df to look like:
   Group  Value  name min
0    234   5000  abc 1000
1    345   2000  def 2000
2    234   1000  ghi 1000
3    456   3000  jkl 3000

I tried doing the following:
df['min']=  df.loc[df['Group'] == df['Group'], 'Value'].min()

This gives me :
   Group  Value name   min
0    234   5000  abc  1000
1    345   2000  def  1000
2    234   1000  ghi  1000
3    456   3000  jkl  1000

It is not taking the group dependency. Can someone please help me with this?
Answer: Let's try groupby transform:
import pandas as pd

df = pd.DataFrame({'Group': [234, 345, 234, 456],
                   'Value': [5000, 2000, 1000, 3000],
                   'name': ['abc', 'def', 'ghi', 'jkl']})

df['min'] = df.groupby('Group')['Value'].transform('min')
print(df)

Output:

   Group  Value name   min
0    234   5000  abc  1000
1    345   2000  def  2000
2    234   1000  ghi  1000
3    456   3000  jkl  3000


Jackson tries to cast Integer to String

Question: I have a very basic Spring Boot app with .-data-jpa, .-data-rest and .-web dependencies.
In my model there is an entity Game that contains an Integer property homeGameSwitch.
When I get the resource with a REST call I get this exception:

.w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP
  message:
  org.springframework.http.converter.HttpMessageNotWritableException:
  Could not write JSON: java.lang.Integer cannot be cast to
  java.lang.String; nested exception is
  com.fasterxml.jackson.databind.JsonMappingException: java.lang.Integer
  cannot be cast to java.lang.String (through reference chain:
  org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$PersistentEntityResourceSerializer$1["content"]->com.coli.stripebackend.model.Game["homeGameSwitch"])

I find it strange that Jackson can't handle an Integer.
Is there something I can do prevent this error?
The entity:
@Entity
public class Game {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private Integer homeGameSwitch;

    public Integer getHomeGameSwitch() {
        return homeGameSwitch;
    }

The DAO:
@Repository("gameDao")
public interface GameDao extends JpaRepository<Game, Integer> {}

The service:
@Service("gameService")
public class GameServiceImpl implements GameService {

    @Autowired
    private GameDao gameDao;

    @Override
    public Game retrieveGameById(Integer id) throws Exception {
        Optional<Game> optionalGame = gameDao.findById(id);
        return optionalGame.get();
    }

The error occurs when calling localhost:8080/game/7
Comment: Show us your entity (or at least the least code necessary to reproduce the problem) and what exactly you're doing to get this exception. Read also [mcve] and [What topics can I ask about here?](https://stackoverflow.com/help/on-topic) (more precisely point (1)).
Comment: @Coli, since the -1 was not from me, perhaps address that to whoever it was
Comment: You're still missing some info. You first said you were using spring-data-rest, but you're not using any REST repository, so where exactly is the code that is being served when you call `/game/7`?
Comment: I'm still learning, but following [this tutorial](https://www.lynda.com/Spring-Framework-tutorials/Advanced-lookup-APIs-search-resource/510079/571077-4.html?srchtrk=index%3a5%0alinktypeid%3a2%0aq%3aspring+boot%0apage%3a1%0as%3arelevance%0asa%3atrue%0aproducttypeid%3a2) when using spring-data-rest it is not necessary to add any code to have a REST API. The fact that the error comes after the retrieval from the DB proves that the REST API is working with this URL.
Answer: The problem was related to the version of Spring Boot. I was using the version 2.0.0.M2 in which there seems to be a bug.
I don't have the problem when using the version 1.5.4.RELEASE.
Answer: This is a warning to future readers who come here: There are many ways to trigger this exception: Some similar ones are collected in Jackson serialization exception when trying to serialize LocalDateTime
It seems I just ran into another way of getting the exact same exception: Have a class like this:
class Foo extends HashMap<String, String> {
  public long bar;
}

and try to serialize it.

Jackson tries to cast Integer to String


What's the minimum number of points I need to measure to find out how much two rectangles are overlapping?

Question: This is for a web app, but I think it's a general geometric problem, and almost certainly a solved one:
I have a rectangle $(A)$ and I know its size. I'm trying to figure out if there's another rectangle $(B)$ overlapping mine, and by how much to $25\%$ accuracy. (That is, I want to know if $B$ is covering $0\%$, $0-25\%$, $25-50\%$, $50-75\%$ or $100\%$ of $A$.)

There may or may not be a second rectangle.
There may be more than one other rectangle.
The rectangles are all oriented parallel to each other (no rotation).
I can only test by checking for an overlap at a particular point on my rectangle's surface.

I'm trying to figure out the most efficient possible arrangement of detection points. Ideally, I'd simply be able to count up the number of hits to know the $\%$ in some kind of simple linear way. Something like the image in this overlap detection drawing.
$\hskip{2.8in}$
Comment: The answer might depend on whether the sides of the other rectangles are always perpendicular/parallel to the sides of the first rectangle.
Comment: They are parallel. Well... in theory, there could be rotation, but it's extremely rare, so let's assume "no" for now. It doesn't have to be a perfect approximation.
Comment: So for an overlap of >25%, the centre of the rectangle will be covered. And I have a feeling that there will be points along the line from the centre to each vertex that suffice to show more overlap? I'm not sure.
Comment: >50%, I agree, but couldn't you have an overlap like that in the drawing that was just shy of 50% without the centre being covered?
Comment: Oh yeah. I was just imagining congruent rectangles sliding over each other. And even there I was being silly. So this is true: it is a necessary condition on >50% being covered, that the centre is covered. But it is not sufficient. A sufficient condition for >25% coverage is one vertex and the centre covered. But this is not necessary.
Comment: 0-25% seems to be the tricky bit. I think I have to check each point along the perimeter to be certain about that.
Answer: There are a few domains that treat this kind of thing.

In math, you'll probably only need some simple 2D geometry, but some way more complicated, but related ideas, are: simplicial complexes, gaussian integers and half-integers, lattices, etc.
In computer graphics/vision, there is...?
In physical modeling, there is collision detection (probably your best bet).

Just to try to give your problem a concrete formulation,
here are some very simple observations and fundamental questions.
I imagine your problem is that you have a collection of rectangles $\{A_k\}_{k=1}^n$ in $\mathbb{N}^2$ (i.e. with nonnegative integral coordinates), each centered at $(x_k,y_k)$ and having half-lengths $(a_k,b_k)$, so that $A_k=\{(x,y)\in\mathbb{N}^2 \mid |x-x_k| \le a_k \wedge |y-y_k| \le b_k \}$. Such representations are unique as long as $\forall k: a_k \le x_k,~b_k \le y_k$.
Fundamental questions (the first being, are you working in $\mathbb{R}$ or ${Z}$, continuous or discrete coordinates):

Are you working with continuous or discrete rectangles (i.e. over $\mathbb{R}$ or $\mathbb{Z}$), and are the coordinates signed or unsigned?
Do all the edges of a rectangle contain points (which can cover those of another rectangle)?
Do you know $k$?
Do you know all rectangles?
Do you know their centers $(x_k,y_k)$ and "radii" $(a_i,b_i)$?

One subtlety with the above definition is that,
in the discrete case,
the $x$ or $y$ coordinates of the center and "radii"
will be half-integers, in $(\frac12\mathbb{N})^2$,
precisely when the full length in that dimension is even.
This amounts to an additional constraint, namely, that
$2x_k\equiv2a_k\pmod2$ and
$2y_k\equiv2b_k\pmod2$.
But the interval endpoints are always integers.
Let us abbreviate this by saying
$A_k=\text{Rect}(x_k,y_k,a_k,b_k)$,
$C(A_k)=(x_k,y_k)$ for the center and
$R(A_k)=(a_k,b_k)$ for the "radii".
We could then say that an arbitrary point
$P$ is inside $R$ if $|P-C| \le R$,
where this is interpreted as a joint
statement or simultaneous inequality
in each dimension
(so that $|P-C| \not\le R$
and $|P-C| \gt R$ have different meanings).
This definition is equivalent to defining rectangles on $[0,\infty)^2$ by identifying points $(x,y)\in\mathbb{N}^2$ with cells $[x,x+1)\times[y,y+1)\in\mathbb{R_{\ge0}}^2$.
With this identification of $\mathbb{N}^2$ with $\mathbb{R}_{\ge0}^2$,
we can say that $A_k=[x_k-a_k,x_k+a_k  ]\times[y_k-b_k,y_k+b_k  ]$ in the former
space, but that $A_k=[x_k-a_k,x_k+a_k+1)\times[y_k-b_k,y_k+b_k+1)$ in the latter
space.
Let $m$ be your area function on rectangles, i.e. $m(A)=\#(A\cap\mathbb{N}^2)$ is the number of integer points in the rectangle (this formula works also in $\mathbb{R_{\ge0}}^2$ if the rectangles have integral side lengths and are left-closed, righ-open). The intersection of two rectangles $A$ and $B$ is also a rectangle, $AB=A\cap B$, since they are parallel. The overlap is just $m(AB)$.
Given $A_j$ and $A_k$ as above,
their intersection is (non)empty iff
their centers are (not) too far apart
in either dimension:
$$
A_j \cap A_k = \emptyset
\qquad
\iff
\qquad
|x_j-x_k|>a_j+a_k
\quad
\vee
\quad
|y_j-y_k|>b_j+b_k
$$
$$
A_j \cap A_k \ne \emptyset
\qquad
\iff
\qquad
|x_j-x_k| \le a_j+a_k
\quad
\wedge
\quad
|y_j-y_k| \le b_j+b_k
$$
In the case that it is nonempty, the intersection will be given by
$$
\eqalign{
A_j \cap A_k
&=
% why are the parenthesis pair sizes different when using \left & \right?
% \left( [x_j-a_j,x_j+a_j] \cap [x_k-a_k,x_k+a_k] \right)
% \times
% \left( [y_j-b_j,y_j+b_j] \cap [y_j-b_j,y_j+b_j] \right)
  \bigg( [x_j-a_j,x_j+a_j] \cap [x_k-a_k,x_k+a_k] \bigg)
  \times
  \bigg( [y_j-b_j,y_j+b_j] \cap [y_j-b_j,y_j+b_j] \bigg)
\\
&=       [\max(x_j-a_j,x_k-a_k),\min(x_j+a_j,x_k+a_k)] \\
& \times~[\max(y_j-b_j,y_k-b_k),\min(y_j+b_j,y_k+b_k)] \\
}
$$
where, since we are treating endpoints, they are all integral
in the discrete case.
Assuming parallel rectangles and in the discrete case that edges contain points and can therefore cover points from other objects, it will be true that for two rectangles $A$ & $B$, $A$ covers half or more of $B$ iff $A$ (as an object in $\mathbb{R}^2$) contains the center of $B$:
$$m(AB)\ge\frac12m(B) \iff C(B)\in A.$$
Note, in the discrete case, that we must on the RHS treat half-integer coordinates of $C(B)$ as being in $A$ as long as they satisfy (both) the distance inequalities above, i.e. if the point's four nearest integral neighbors lie in $A$.

Actually, the diagram you linked is very illuminating.
If you think about integer-valued vertices as the sample points
each being assigned or identified with a $1\times1$ cell
(say, by a left endpoint rule to use terminology from Riemann sums),
I think you will see that it is a limiting case.
Therefore, the interplay between discrete rasterization
and the more familiar continuous geometry of $\mathbb{R}^2$
comes into play, and you need $25$ sample points to detect
quarter-area overlaps of a $4\times4$ rectangle of area $16$.


Finding Limits using the Definition

Question:
Using the definition of a limit, find the limit
  $$\lim_{x\to 0} x^2\cos\left(\frac1x\right)$$
  or prove it does not exist.

I did an example similar to this in class where we figured what the trig function was bounded by and then determined delta was equal to epsilon. However, I do not understand what was done and do not know how to go about doing this problem.
Comment: @user72195 It might be a good idea to ask a question with your notes regarding the example given in class and ask what you didn't understand.
Comment: I suggest that you start by stating the definition of a limit. If you add this to your original question, we can show you how to use it as a step-by-step guide to solve this problem. Also include the example from class and ask about the specific parts that you don't understand.
Answer: The idea here is this: we know that $x^2\rightarrow0$ as $x\rightarrow0$; we also know that no matter what $x$ happens to be,
$$
-1\leq\cos\left(\frac{1}{x}\right)\leq 1.\tag{1}
$$
So, no matter what the cosine term does, it cannot "overrule" the tendency of $x^2$ to take us to 0.
To use the definition: let $\epsilon>0$ be given. We want to show that if $x$ is close enough to 0, then $x^2\cos(\frac{1}{x})$ is within $\epsilon$ of 0 - in other words, that $\lvert x^2\cos(\frac{1}{x})\rvert<\epsilon$.  But, by the inequalities in (1), $\lvert\cos(\frac{1}{x})\rvert\leq 1$.  See if you can use this inequality, along with a proof that $x^2\rightarrow0$ as $x\rightarrow0$, to finish the problem.
Hint: $\delta$ here will be completely determined by the $x^2$ term after you apply the inequality.
Comment: I am getting caught on the proof from the limit of x^2 I have: let E>0 and choose a delta = ? such that [x^2-0]0$ so that $\delta^2<\epsilon$... if we do that, then $\lvert x\rvert<\delta$ implies $\lvert x\rvert^2<\delta^2<\epsilon$. So, how do you un-do the square root?
Comment: then [x]< E but what does that mean?
Comment: Not $\lvert x\rvert<\epsilon$... $\lvert x^2\rvert<\epsilon$. Which implies that $\lvert x^2\cos(\frac{1}{x})-0\lvert\leq\lvert x^2\rvert<\epsilon$, which is exactly what you are trying to show.
Comment: I hope that this has helped; but, I'm afraid that I can't offer too much more in the way of hints without just writing down a solution to your homework for you (and I'm not prepared to do that).  Might I suggest making an appointment with your instructor to go over the problem?  They can much more easily draw a picture to help explain it than I can in a forum like this.
Comment: that is what I meant, sorry, I mixed up the two expressions I had ([x]^20$ such that, for any $x$ with $\lvert x-0\vert<\delta$, it follows that $\lvert x^2\cos(\frac{1}{x})-0\rvert<\epsilon$.
Comment: @user72195 I hope this helped.  If it did: please, consider accepting my answer!

Finding Limits using the Definition


MATLAB put a LED to a serial port

Question: I'm working on MATLAB, I want to connect only a LED & resistor to a serial port.
When a specific action happens in my program, the LED must turn on.
What I did but nothing had happened:
S   = serial( 'com1' );
fid = fopen( s );                         # ... 've checked the s vs. S ?

Comment: @Ratbert: no special hardware is needed. On can connect LEDs with resistors directly to a serial port with no additional hardware ([see here](http://slicksolutions.eu/ledsdriver.shtml) for example). This doesn't mean that it's a good or robust idea, however. And Matlab's `serial` class is unlikely to work for this. A lower level means of sending data to the serial port will be required.
Comment: This cannot work, you need a device that is able to "talk" to the computer to establish the serial connnection. You can look for instance at arduino boards, but there are many other options.
Comment: This is not a programming question, since it's essentially a problem of lacking hardware.
Comment: Thanks, but i need a simple board which only consist of resistor and a led then I will connect them to the pc through the serial port. Any help please how to code it
Comment: Again, this is simply not possible. This is not how thing work.
Comment: What can I do in this situation, if u have any solution.
Comment: @horchler OK, I didn't knew about that, thanks or the link.
Comment: It should be working... serial port do not require impedance checking or wake up acknowlegment messages prior sending bytes.... I suggest you try with a third party tool -Hyperterminal :)- and with a tester over pins 2&3 and see what happens.....
Answer: You should be able to control the DTR and RTS lines (on DB-9 connectors on pins 4 and 7, respectively) from MATLAB. According to the reference, serial port objects have the properties DataTerminalReady and RequestToSend, which can be toggled. For example,
S = serial('com1');
for ii = 1:5
    set(S, 'RequestToSend', 'on');
    pause(1)
    set(S, 'RequestToSend', 'off');
    pause(1)
end

will flash an LED connected to the RTS pin five times.

MATLAB put a LED to a serial port


Apple Remote Desktop (ARD) OS Specific package installation

Question: Faced with the recent Java kerfuffle imposed by Apple's silent updates I am looking for a solution to install .pkg files specific to the OS version.
Apple continues to provide Java updates for 10.6, but for 10.7+ we need to get the file from Oracle. Apple finally released the Java update for 10.6 on Friday, but the software was available before it was showing up as a Software Update through the OS's Software Update section.
For 10.6, we may just end up resorting to waiting for Apple to push it through their Software Updates and use ARD to run those Software Updates, but when pushing out Java updates through ARD using the .pkg file provided by Oracle, I'd like to ensure we are only attempting to install on machines which are 10.7+ and not on anything less than that.
Question: I was wondering if ARD Software Distribution has the capability of installing based on Client OS version, I don't want to attempt to install the Oracle Java intended for 10.7+ machines on any of our 10.6 clients. I can't seem to find any documentation or discussions online. Any/All help is appreciated.
Answer I formulated (great help from the answer below, just wanted to offer an end result for people who may still be scratching their heads):
#!/bin/bash
os_ver_maj=$(sw_vers -productVersion | cut -d . -f 2)
    if [ $os_ver_maj -ge 7 ]; then
        mkdir /Volumes/ARD && mount_afp afp://ardservername.localdomain/ARD_pkgs /Volumes/ARD && installer -pkg /Volumes/ARD/jre-7u13-macosx-x64.pkg -target /
    else
        mkdir /Volumes/ARD && mount_afp afp://ardservername.localdomain/ARD_pkgs /Volumes/ARD && installer -pkg /Volumes/ARD/Java6u12OSX10.6.pkg -target /
    fi
umount /Volumes/ARD

Explanation:

I chose to host the files right on the ARD server, downloading from Oracle is almost impossible and I'm sure it will change without warning.
I also opted to not use softwareupdate for 10.6, too many other problems arose, even when choosing the specific PackageName.
When new Java updates come out, we will download and extract the .pkg from the .dmg, place it on the ARD server in the ARD_pkgs directory and update the script to reflect the package version change.

I hope this helps others, thanks for the input and guidance.
Comment: I like your ultimate solution to self-host the files and install them over the wire. One minor improvement, you could do the `mkdir /Volumes/ARD && mount_afp afp://ardservername.localdomain/ARD_pkgs /Volumes/ARD` once before the OS check since it's required regardless of OS version (much like you did with the `unmount /Volumes/ARD`).
Answer: Apple Remote Desktop's Copy Items & Install Packages features don't have the specific filtering ability to do that, but you can do it in two easy steps with a Smart List:

Click the "+" button in the lower-left corner of the Remote Desktop window and select "New Smart List..."
Name the new "Smart List" where "Mac OS Version" is "greater than" version "10.7" (you can add other filters if you'd like) and click OK.
Select the new Smart List from the source list.
Select all the computers in that list.
Click the Install Packages button (or select Manage -> Install Packages...) to proceed to install the Oracle Java package to only those selected Macs.

Alternatively, if you want to either run Software Update or install the Oracle Java package on all machines at once, you could write a shell script to check the OS version. Here's an example in bash:
os_ver_maj=$(sw_vers -productVersion | cut -d . -f 2) # get the major OS version
if [ $os_ver_maj -ge 7 ]; then
    # download & install the Oracle Java package
else
    # run software update
fi

Once you've built a script that correctly does what you want, then you can select all the machines in ARD, then you can do Manage -> Run UNIX Command... (or click the Send UNIX Command button) & paste in the script.
Answer: I think what you're looking for is sw_vers. You can create a script that calls it and parses the output. If it matches (or doesn't match) then call the package installer.
Sample output:
Marks-MacBook-Pro:~ mark$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.8.2
BuildVersion:   12C60


How Kafka distributes the topic partitions among the brokers

Question: I have 3 Kafka brokers in 3 different VMs, with one additionally running a Zookeeper. I now create a topic with 8 partitions. The Producer pushes messages to these group of brokers on the created "topic".

How does the Kafka distribute a topic and its partitions among the brokers?
Does the Kafka redistribute the topic when a new Kafka Broker joins a cluster?
Can the topic partition be increased after the topic was created?
Answer:
When you create a new topic, Kafka places the partitions and replicas in a way that the brokers with least number of existing partitions are used first, and replicas for same partition are on different brokers.
When you add a new broker, it is used for new partitions (since it has lowest number of existing partitions), but there is no automatic balancing of existing partitions to the new broker. You can use the replica-reassignment tool to move partitions and replicas to the new broker.
Yes, you can add partitions to an existing topic.
Comment: When a producer firsts connect to the cluster (via a broker in broker.list parameter), it issues a Metadata request, with the topics you are publishing to, and the broker replies with which broker has which partition. If a broker goes down, the producer detects the failed connection (via tcp timeout usually), and re-issues a metadata request to find the new leader.
Comment: A precise answer! Thanks for that.
Do the producers need to know which broker the partition exists and push message to them? What happens when that broker goes down while the producers are pushing messages? Basically, how the producers see the partitions in a huge Kafka cluster?


What is considered to be inspiration? How can I be sure my idea is original?

Question: I'm feeling like I'm not fully understand what degree of musical creativity is considered to be creating original content or inspiration.
When a musical idea "jumps in my head" it sometimes remind me some other song I heard before. For example today I had a 8-bit music idea, I've even played with it in my head, trited to form it but it kept constantly remind me to some 8-bit tracks I've heard before, I think they were from Mega Man. There were parts I wasn't even sure not just a "well remixed" part from one of the songs or a deformed part of an existing melody. And there was a melody part which was very similar to an existing one.
Last time I wrote a song in MuseScore I was trying to get a good sounding melody and when I got one I liked I was like "this melody is familiar..." but I can't even name a song where I could heard it.
I still don't know if it's my idea, or it's very familiar because once I heard a melody and it inspired me or just "got lost" in my passive memory.
Comment: I see, you are looking at the distinction between inspiration and being completely unoriginal, which is plagiarism.  Bach learned music by secretly copying his brother's Vivaldi scores.  He was inspired to the point of outright just copying out what Vivaldi wrote.  It's in Bach's hand but no one calls it Bach's music. It's originality is Vivaldi. But the stylistic mark Vivaldi left on Bach was permanent. So in that sense Bach was inspired by Vivaldi. Bach also successfully used many unoriginal ideas in new ways, such as new harmonizations of common hymn melodies.
Comment: @RichardBarber I see... So if a few of my music has melody similar to other pieces of music it can be because I listened to those tracks so many times that I don't even noticed they left a mark on me?
Comment: I'm not a Bach historian, but @RichardBarber's account of the Vivaldi concertos seems wildly inaccurate. Those works were commissioned court music... https://en.wikipedia.org/wiki/Weimar_concerto_transcriptions_(Bach)
Comment: This would have been when he was 9 or 10 when he went to live with his brother, years before he would be appointed.
Answer: Sometimes when we write, if we follow our ear purely, it will lead us in patterns that are familiar to us. If you find that your ear is constantly doing this, I'd recommend listening to unfamiliar types of music. Doing so will disrupt your ear patterns and give you new ideas.
Concerning your particular melody. Ask yourself: What makes this familiar? What exact musical elements make this familiar? Is that something you want? A composer should be able to control all aspects of the music, including whether or not it sounds familiar. Once you've analyzed your melody, you can use your knowledge and tools to change it as you see fit.
Don't be so paranoid. Creativity and expression blossom with doing something new with established materials. What matters most is that you are scratching that creative itch.
Comment: Well...recently I've listened to Schönberg and Webern. I think we can call that "unfamiliar type" because of the strange - but I think quite good - sensation of atonal music. I'll see if that's help.

Analyzing my own melody sounds an interesting idea.


What is the Reproducing Kernel Hilbert Space of $k(x,y)=\langle x,y\rangle^2$?

Question: Digging in the definition of Reproducing Kernel Hilbert Spaces (RKHS) I came across the following example taken from pages 49-51 of [1]:
Given the kernel $k(x,y) = \langle x,y\rangle^2$, with $x,y\in \mathbb R^2$, one can show that both
$\phi(x) = [x_1^2,~ x_2^2,~ x_1x_2, ~x_1x_2]$, with feature space $\mathcal H = \mathbb R^4$
$\phi^{\prime}(x) = [x_1^2,~ x_2^2,~ \sqrt 2 x_1x_2]$, with feature space $\mathcal H^\prime = \mathbb R^3$
are valid feature maps for the kernel. However, the slides point  out that neither $\mathcal H$ nor $\mathcal H^\prime$ are RKHS because the RKHS must by definition be unique for a given kernel. Can you explain what the RKHS would be in this case?
Other references on the topic state that the RKHS $\mathcal H_k$ is unique up to isomorphism [2]. Under this definition I guess both  $\mathcal H$ and $\mathcal H^\prime$ can be considered RKHS by being isomorphic to  $\mathcal H_k$.
[1] http://www.stats.ox.ac.uk/~sejdinov/teaching/atml14/Theory_slides1_2014.pdf
[2] http://users.umiacs.umd.edu/~hal/docs/daume04rkhs.pdf
Answer: Prof. Dino Sejdinovic, author of the slides my question referred to, was kind enough to send me the following answer:

Feature spaces are not unique and indeed they are all isomorphic. RKHS
  of a given kernel is unique as a space of functions, i.e. the one
  that contains functions of the form $k(\cdot , x)$. If these functions form a
  finite-dimensional RKHS, that RKHS is isomorphic to a standard
  Euclidean space of that dimension. For intuition about uniqueness for
  infinite-dimensional case, you can consider an orthonormal basis of
  $\mathcal H_k$, e.g. given by Mercer's theorem -- then the $\ell^2$ space of
  coefficients corresponding to this basis is a valid feature space and
  isomorphic to RKHS. You can choose many different bases so there are
  many versions of feature spaces. But they all correspond to the same
  space of functions which is the RKHS.

In addition, the first twenty minutes of this class by Prof. Lorenzo Rosasco delve a bit deeper into the relation between feature spaces, feature maps and RKHS.
Comment: What did he mean by "If these functions form a finite-dimensional RKHS, that RKHS is isomorphic to a standard Euclidean space of that dimension" ?


Feature function for logistic regression

Question: In his Natural Language Processing textbook, Eisenstein defines the logistic regression as follows:
$$p(y|x,\theta) = \frac{\exp (\theta f(x,y))}{\sum_{y'} \exp (\theta f(x,y'))}$$
Where $\theta$ are the regression parameters and $f(x,y)$ a given feature function. My question concerns the feature function we just defined as a function of $x$ and $y$. Indeed, I can't grasp why Eisenstein's feature function also takes the label $y$ as an input. From my understanding, in standard regression (e.g. multiple linear regression), the feature function is a way to catch non-linearities in the data by projecting data point $x$ in a well-chosen feature space using the feature function $\phi(x): X \rightarrow{} F$. But I can't really see when and how having label $y$ is useful.
Answer: This is basically a notational variant of standard logistic regression. In that case, the distribution looks like $p(i|x,\theta)\propto e^{x\cdot w_i}$, where $w_i$ is a vector of coefficients corresponding to the $i$th class. This corresponds to using a feature map in which $x\mapsto f(x,y)$ is linear for each fixed $y$. I would imagine that this is being introduced with an eye towards using more complex feature maps later on.


Creating notification based on table insert in Android

Question: I am new to Android and my requirement is this. I am in need to develop an application that will list all the events (past and upcoming). These event details , I will fetch from tables and that table will have only past events. For the upcoming events, I will be inserting into the table which will create a notification for the same.
My doubts:

What is the table I should use (SQLite(inbuilt) or MySql from any hosting services) ?
If SQLite, Is there a way from GUI, I can insert data so that it will reach all users having this application?

To be simple, how I can achieve this entire functionality?
Thanks in advance!!!
Answer:
What is the table I should use (SQLite(inbuilt) or MySql from any hosting services) ?

If you want all user devices to access the same database, you will have to setup a MySQL server. As soon as the database is updated in your host, the changes will be reflected in the users apps - as soon as they reload the view or a new request is made. You can query your database every N seconds to keep things updated.
Comment: Thanks R.Costa. Is there a link to refer connecting to MySQL and what is the best MySQL hosting service ? Thanks again!!!
Comment: Regarding the server side, I would install something like XAMPP to try MySQL and test the system. You can worry about hosting providers later . To combine Android and MySQL, there are thousands of tutorials online; just use Google or Youtube to learn the basics.
Answer: MySQL will be my choice or MariaDB, MySQL's community fork.
You can start with this tutorial:
http://dev.mysql.com/doc/refman/5.7/en/tutorial.html


Declaring Man of The Match and Man of the Series/Tournament Award

Question:
Who holds the decision to declare Man of the Match/Man of the Series/
  Tournament award?

Some sources say that it is decided by commentators and former cricket players.

How the Man of the match is decide when there are equivalent
  performance from two players in the same match ?

a case in which a batsmen scores 100 runs with a good strike rate and a bowler takes a 5 wicket haul with an average economy rate.

What will be things considered while declaring a Man of the Match for
  such case ?

I know it is possible to Award two man of the match. But how it is decided in other matches where there is only single man of the match award given.Any ICC rule for such case.
Answer:
Who holds the decision to declare Man of the Match/Man of the Series/ Tournament award?

It depends on the tournament or series that is going on. In some series they are decided by commentators as they say while giving award as it was quite difficult for us to choose. But For the Big tournaments such as World Cup there is always a panel selected for decision taking.

How the Man of the match is decide when there are equivalent performance from two players in the same match ?

It depends on which performance lead to match winning and at crucial time of the game.

What will be things considered while declaring a Man of the Match for such case ?

I am not sure about if there is some rule as such but it is completely dependent on the performance.
Hope this helps.
Answer:
Who holds the decision to declare Man of the Match/Man of the Series/ Tournament award?

In most cases, the panel of TV pundits and commentators chosen for the series act as the jury.

How the Man of the match is decide when there are equivalent performance from two players in the same match ?

Generally, preference is given to the best match-winning effort, but there have been a number of awardees from the losing side too, by virtue of an extraordinary one-man role. Sometimes, the fielding accomplishments of the players are also considered. Joint winners have also been selected, like  HH Gibbs and RT Ponting in the  "greatest game ever"  in 2006 between Australia and South Africa. Thus, there are no ICC rules in this regard and the decision is purely subjective.


Microsoft System CLR Types for SQL Server 2012

Question: I need to install Microsoft Report viewer Run time for running some report from a desktop application. I also need to install the System CLR Types for SQL Server 2012 package for this. Which one to  install 64 bit or 32 bit, Is this for OS or Application. What type of resource load will these packages add to the servers – CPU or memory intensive?
Answer: It will be installed on the basis on of your O.S version.
MS-SQL Server Report viewer will utilize both CPU and memory of your server.
You can find the detailed description here.