How to motivate the definition of $R^2$ in `sklearn.metrics.r2_score`?

Question: TLDR: What motivates the definition of $R^2$ in the Python function sklearn.metrics.r2_score?
DETAILS
The Python machine learning package sklearn implements an $R^2$ using the following formula.
$$
R^2=1-\left(\dfrac{
\overset{N}{\underset{i=1}{\sum}}\left(
y_i-\hat y_i
\right)^2
}{
\overset{N}{\underset{i=1}{\sum}}\left(
y_i-\bar y
\right)^2
}\right)
$$
This is fine for in-sample assessments of $R^2$, but when it comes to out-of-sample assessments, the definition seems unmotivated and lacking in meaning.
In simple linear regression (in-sample), there are multiple equivalent definitions of $R^2$.

Squared correlation between the feature and the outcome
Squared correlation between the outcome and the predictions
Proportion of variance explained
Comparison of the square loss incurred by the model to the square loss incurred by a baseline model

(There may be more, and perhaps it is me only thinking of these four that prevents me from seeing what this Python function means.)
In regression models with multiple features, definition 1 does not make sense, so it is not a contender for a generalization of $R^2$ to out-of-sample assessments in complicated situations that are likely to have multiple features.
Out-of-sample, squaring the correlation misses prediction bias. For instance, $y=(1,2,3)$ is perfectly correlated with $\hat y=(11,12,13)$, yet $\hat y$ is composed of terrible predictions of $y$. While this kind of bias cannot happen in-sample in ordinary least squares linear regression, out-of-sample, all bets are off (and that's without even getting into what could go wrong in fancier regression models like support vectors or neural networks). Consequently, definition 2 is out as a generalization of $R^2$ to out-of-sample assessments.
Except in special situations, the usual methods for calculating $R^2$ do not correspond to the proportion of variance explained, and if we twist the definition to force it, we usually lose the connection to the square loss that we aim to minimize. Thus, definition 3 does not seem like a good contender for a generalization of $R^2$.
Finally, definition 4 makes sense. We have some kind of baseline model (naïvely predict $\bar y$ every time, always using the marginal mean as our guess of the conditional mean) and compare our predictions to the predictions made by that baseline model. To draw an analogy to flipping a coin, if someone guesses which side will land up and gets correct predictions less than half the time, that person is a poor predictor. If they are right more than half the time, they are at least improving somewhat upon the naïve "Gee, I don't know how it'll land, so I guess I'll just say heads every time (or tails, or alternate between the two) and get it right about half the time."
(Put bluntly, why pay a data scientist or statistician a lot of money to predict conditional means when you could do better just by predicting one number every time that you can calculate by AVERAGE(A:A) in Excel?)
In-sample, I am totally on board with the Python function. Out-of-sample, I have a problem. In the $R^2$ formula above, the Python implementation uses the $\bar y$ from the given data. That is, if you input an out-of-sample $y$ and the corresponding predictions $\hat y$, the function uses the out-of-sample $\bar y$ in the denominator.
This corresponds to comparing your model to a model that predicts the out-of-sample mean every time. However, we cannot have access to such a model, since it would require knowledge of the true out-of-sample values.
QUESTION: What motivates this definition that is used in sklearn?
An argument about ease of use does not seem legitimate to me (even if that is why the function is defined this way), because the following is even easier to implement.
def r2_score():
    return(0.5)
    # or return(np.random.uniform(0, 1, 1))

While this is an extreme example, the function does not return useful information about the regression model. Consequently, making a function easy to use at the expense of returning unhelpful information seems like a poor design or a function that we should not use.
EDIT
I have referred to this question so many times yet never noticed until now that I never wrote explicitly what the competing notions of out-of-sample $R^2$ are. That ends now!
$$
R^2_{\text{out-of-sample, Dave}}=
1-\left(\dfrac{
\overset{N}{\underset{i=1}{\sum}}\left(
y_i-\hat y_i
\right)^2
}{
\overset{N}{\underset{i=1}{\sum}}\left(
y_i-\bar y_{\text{in-sample}}
\right)^2
}\right)
$$$$
R^2_{\text{out-of-sample, scikit-learn}}=
1-\left(\dfrac{
\overset{N}{\underset{i=1}{\sum}}\left(
y_i-\hat y_i
\right)^2
}{
\overset{N}{\underset{i=1}{\sum}}\left(
y_i-\bar y_{\text{out-of-sample}}
\right)^2
}\right)
$$
EDIT 2
My preferred calculation now has a reference in the literature (Hawinkel, Waegeman & Maere (2023)) explaining its superiority over that used by sklearn. One of the authors appears to be a Cross Validated contributor, too!
REFERENCE
Stijn Hawinkel, Willem Waegeman & Steven Maere (2023) Out-of-sample $R^2$: estimation and inference, The American Statistician, DOI: 10.1080/00031305.2023.2216252
Comment: One problem with the out-of-sample $R^2$ is that it invites misunderstandings and misconceptions. I would never use out-of-sample $R^2$ without explicitly defining it, and even then people might miss the definition and go on interpreting the results in a way that is intuitive to them. A way out would be to use a different name (not $R^2$) that does not carry such deep-rooted connotations.
Comment: [A discussion I had with Firebug on this topic](https://stats.stackexchange.com/a/492446/247274)
Comment: Point 4. seems to have been cut off abruptly.
Comment: https://stats.stackexchange.com/questions/569790/how-to-distinguish-two-versions-of-r-squared-calculated-on-test-set I asked a related question a few months ago
Answer:

Squared correlation between the feature and the outcome

That would be the case if you have a single feature and the model is linear regression.

Squared correlation between the outcome and the predictions

Same as above, but it will hold also if there are more features.

Proportion of variance explained

It tells us the proportion of the variance explained, but only for the linear regression.

Comparison of the square loss incurred by the model to the square loss incurred

Again, for linear regression using the formula from Scikit-learn is equivalent to the as we can decompose the squared error to TSS = ESS + RSS and get the equivalent formulation.
So in a sense, all the formulations are the same, just have varying degrees of generality.
As for calculating $R^2$ on the test set, you can check this thread and if you search through CrossValidated.com and Scikit-learn GitHub issues, you can find many discussions considering the Scikit-learn's choice of test set mean in the denominator as controversial. As you can learn from this discussion, one of the problems with using the train set mean for the test set $R^2$ is the API, where the metrics usually are defined as metric(y_true, y_pred) and the same interface can be used regardless if it is training or test set. It would also mean that during evaluation time you would need to have access to the training data, which may not be possible in some setups where there is a hard split of the data between training time and validation time.
Notice also that $R^2$ comes from statistics, where we are usually interested in in-sample metrics, so the derivations would as well regard the train set $R^2$.
Comment: @Dave e.g. https://github.com/scikit-learn/scikit-learn/discussions/21957 but I know for certain that there are more of them.
Comment: I've been thinking about this for the past few days, particularly your comment about needing the extra information from the training set that might be separate from the test set. This strikes me as a feature, not a bug, of an out-of-sample $R^2$, and it leave me thinking that the justification for this particular Python implementation is that the other metrics like MSE and MAE only have true and predicted values as inputs, so the $R^2$ function will do the same. This bothers me. (And you're probably right about why they left it out of the function!)
Comment: Do you have any specific posts in mind in the GitHub issues?
Comment: Regarding the Campbell/Thompson finance paper mentioned in [this link](https://stats.stackexchange.com/a/492581/247274) you shared, using the historical return would seem consistent with using the in-sample mean for an out-of-sample $R^2$-style calculation agreed?
Answer:

Comparison of the square loss incurred by the model to the square loss incurred by a baseline model

Comparison of the loss seems a lot like the pseudo-$R^2$ value e.g.
$$R^2_{pseudo} = 1 - \frac{D_{null} - D_{model}}{D_{null}}$$
But with the deviance or loss equal to the sum of squared residuals and the null model the mean, then it becomes the same as the regular $R^2$.

In-sample, I am totally on board with the Python function. Out-of-sample, I have a problem. In the $R^2$ formula above, the Python implementation uses the $\hat{y}$ from the given data.

Possibly the problem stems from the use of $R^2$ as a measure for goodness of fit. But the $R^2$ value is not a goodness of fit measure. The value doesn't tell directly whether your model is a good fit or not; A perfect fit of the conditional distribution mean does not need to coincide with a $R^2=1$. Instead, it is a descriptive statistic that tells how large the variance in the noise/randomness is relative to the variance in the deterministic part. We see this in an alternative way to compute $R^2$
$$R^2 =  \frac{SS_{model}}{SS_{model}+SS_{residuals}}$$
where $SS_{model} = \sum (\hat{y} - \bar{\hat{y}})^2$ and $SS_{residuals} = \sum (y - \hat{y})^2$ and $\bar{\hat{y}}$ is the mean of the modelled values.
This way of computing $R^2$ will be equivalent to the 'other $R^2$' if you have a linear model with an intercept. But it will be slightly different in
other situations, for instance there is no occurrence of cases with negative values as in the question  Why is R^2 negative in my multiple linear regression model in python? .
Comment: @Dave I have made an update answering the question in your comment.
Comment: @Dave I thought that you were looking for an alternative for r2. The formula that I gave is different as it never gets negative.
Comment: A difference in your computation occurs because the residuals do not have zero mean. When you would apply `sextus_r2` and `r2_score` to results from a linear least squares fit then the two scores coincide.
Comment: @Dave I had the idea that you found $R^2$ not motivated. My alternative expression gives an alternative computation for $R^2$ that is equivalent to the regular computation when it is applied to least squares fitting with an intercept, but it has a different motivation (as a statistic that expresses the fraction/ratio of variance in the deterministic/modelled and variance in the random/remainder parts)
Comment: But then why does it make sense to compare to something involving the out-of-sample mean?
Comment: @Dave, in the alternative formula it is the mean of the modelled/fitted values and not the mean of the data. It is now just a comparison of two variances, of the noise and of the model.
Comment: What is $SS_{model}?$ What about for residuals? (The latter seems obvious, but I would appreciate clarification.)
Comment: So $\bar{\hat{y}}$ is the out-of-sample mean, right?
Comment: @Dave yes but of the estimated values $\hat{y}$  and not of the data values $y$.
Comment: I will play with this in the coming days and see what I learn. If I get anything particularly good, I might post a self-answer.
Comment: I am not getting your equation to match the `r2_score` result. ```import numpy as np;
import pandas as pd;
from sklearn.metrics import r2_score;
def sextus_r2(y_true, y_pred):
    ss_model, ss_residuals = np.sum((y_pred - np.mean(y_pred))**2), np.sum((y_true - y_pred)**2)
    return(     ss_model / (ss_model + ss_residuals)     );
np.random.seed(2023);
N = 100;
y_pred = np.random.normal(0, 1, N);
y_true = y_pred + np.random.normal(0, 2, N);
print(r2_score(y_true, y_pred));
print(sextus_r2(y_true, y_pred));``` // What's wrong with a negative score?
Comment: This answer seems to address a different question than I asked, then, or do you see how it relates to my issue with how `sklearn` implements out-of-sample $R^2?$


I can't use Intent at Activity

Question: when I click the marker on Google Map, I want it to enter another Activity, but when I got the result from javascript, it can't do Intent
WebSettings webSetting = webView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDisplayZoomControls(true);
webSetting.setSupportZoom(true);
webSetting.setBuiltInZoomControls(true);
webView.addJavascriptInterface(new JavaScriptInterfaceTest(this), "Android");

and my JavaScriptInterfaceTest():
public class JavaScriptInterfaceTest {
  Context mContext;

  /** Instantiate the interface and set the context */
  JavaScriptInterfaceTest(Context c) {
    mContext = c;
  }

  /** Show a toast from the web page */
  @JavascriptInterface
  public void responseResult(String result){
    Log.e("JsCallBack","DRINK");
    Intent mainIntent = new Intent(MainActivity.this, Test.class);
    startActivity(mainIntent);
  }

  @JavascriptInterface
  private void startActivity(Intent mainIntent) {
    // TODO Auto-generated method stub
  }
}

HTML:
drinkMarker = new google.maps.Marker({
                   position: {lat: 25.079734,lng: 121.569519},
                   map: map,
                   });
drinkMarker.addListener('click',function(){
                        Android.responseResult("drink");
                        });

Comment: try using startActivityForResult
Comment: What is the error you're getting?
Comment: like startActivityForResult(mainIntent,0); ?
Comment: i got no error when i run the app
Answer: Pass the Current context instead of MainActivity
public class JavaScriptInterfaceTest {
  Context mContext;

  /** Instantiate the interface and set the context */
  JavaScriptInterfaceTest(Context c) {
    mContext = c;
  }

  /** Show a toast from the web page */
  @JavascriptInterface
  public void responseResult(String result){
    Log.e("JsCallBack","DRINK");
    Intent mainIntent = new Intent(mContext, Test.class);
     mContext.startActivity(mainIntent);
  }

  @JavascriptInterface
  private void startActivity(Intent mainIntent) {
    // TODO Auto-generated method stub
  }
}

I can't use Intent at Activity


Why don't most high-tension marching snares have an inner hoop or any reinforcement on the snare side?

Question: High-tension marching snares have an inner hoop where the batter head is placed to prevent its shells from collapsing—due to the high tension from Kevlar heads being tuned to higher pitches.
If this is the case, then why don't most marching snares have an inner hoop (or any form of reinforcement) on the snare side? Especially given that marching snare-side heads are also made of Kevlar.
I mentioned "most" since Dynasty DFX marching snares do have a reinforcement on the snare side—probably since it's not free-floating.
Comment: Why _would_ they have an inner hoop? Is collapsing from the snare side a commonly encountered problem? I doubt it. Anyway, a drum head with balanced tuning shouldn't squish the drum in any direction, regardless of whether it's kevlar and high tension. On the batter side, hard strokes may cause imbalance strong enough to trigger collapse, but this shouldn't be much of a concern on the snare side.
Answer: Most marching snares don't have a reinforcement ring simply because it isn't necessary.  The drum can support the snare-side head just fine.
Remember that snare side heads are very thin.  Even the aramid fiber heads.  At the same pitch, the snare side head is at much less tension than a batter head would be.
Also, the snare-side head might not be quite as cranked as you're imagining.  Check out this video of Mike McIntosh tuning a marching snare with an aramid snare-side head.  The head pitch seems to be about 369Hz.  I've seen people tune the snare-side head on their drumsets higher.
That said, aramid snare-side heads are strong enough that you can cave the bearing edge in with too much tension.  My old high school used Evans MX5 (5 mil aramid) heads on the snare side, and the bearing edges had corners.  They blamed the previous owners of the drums.  I wish I had pictures to share.  But with proper tuning, this should never happen.


htmlParse fails to load external entity

Question: I'm trying to load some publicly available NHS data using R and the XML package but I keep getting the following error message:

Error: failed to load external entity "http://www.england.nhs.uk/statistics/statistical-work-areas/bed-availability-and-occupancy/"

I can't seem to figure out what might be causing this despite looking through a few related question.
Here is my very simple code:
library("XML")
url <- "http://www.england.nhs.uk/statistics/statistical-work-areas/bed-availability-and-occupancy/"
doc <- htmlParse(url)

Edit: Session Information

R version 3.0.1 (2013-05-16) Platform: i386-w64-mingw32/i386 (32-bit)
locale: [1] LC_COLLATE=English_United Kingdom.1252
  LC_CTYPE=English_United Kingdom.1252    [3] LC_MONETARY=English_United
  Kingdom.1252 LC_NUMERIC=C                            [5]
  LC_TIME=English_United Kingdom.1252
attached base packages: [1] stats     graphics  grDevices utils
  datasets  methods   base
loaded via a namespace (and not attached): [1] tools_3.0.1
Comment: It's not a valid XML document: [W3 Validator](http://validator.w3.org/check?uri=http%3A%2F%2Fwww.england.nhs.uk%2Fstatistics%2Fstatistical-work-areas%2Fbed-availability-and-occupancy%2F&charset=%28detect+automatically%29&doctype=Inline&group=0&verbose=1). It should at least be XHTML, HTML5 is not.
Comment: When I run the code on an Ubuntu box it succeeds, it also runs on r-fiddle.  Can you add sessionInfo() please?  http://www.r-fiddle.org/#/fiddle?id=AfoyOSGm
Comment: sessionInfo() added! I suspect I have the answer already though. This is almost certainly being caused by my work's proxy. I've hit issues with this before (via QGIS) and have never found a satisfactory solution.
Comment: @Tumbledown, I had the same problem.  However after I rebooted my R session it worked again .... weird.
Answer: Package XML has some issues. The problem is intermitent and has nothing to do with the URL. I solved the problem using the function GET of httr package in order to obtain the html code, then passed it to htmlParse, see below:
library("XML")
library(httr)
url <- "http://www.england.nhs.uk/statistics/statistical-work-areas/bed-availability-and-occupancy/"
doc <- htmlParse(rawToChar(GET(url)$content))

Answer: You can also use rvest & the xml2 packages:
library(rvest) # github version
library(xml2)  # github version

url <- "http://www.england.nhs.uk/statistics/statistical-work-areas/bed-availability-and-occupancy/"
doc <- read_html(url)

doc %>%
  html_nodes("a[href^='http://www.england.nhs.uk/statistics/bed-availability-and-occupancy/']") %>%
  html_attr("href")

## [1] "http://www.england.nhs.uk/statistics/bed-availability-and-occupancy/bed-data-overnight/"
## [2] "http://www.england.nhs.uk/statistics/bed-availability-and-occupancy/bed-data-day-only/"

Comment: This 2nd set of commands returns a set of data where the previous one returned a value that could not be searched as easily.

htmlParse fails to load external entity


I do not understand either Microsoft x64 calling convention or FASM's implementation of it

Question: I've written a short PE32+ program in FASM that writes "Hello World!" to stdout and quits.
format PE64 console
include 'win64wx.inc'
.code
  start:
    invoke WriteFile,<invoke GetStdHandle,STD_OUTPUT_HANDLE>,hello,hello.length,dummy,0
    invoke ExitProcess,0
  .end start
.data
  dummy rd 1
  hello db "Hello world!",13,10,0
  hello.length = $ - hello

I've looked at the generated machine code, but I cannot understand why RSP is manipulated the way it is. This is the disassembly:
sub rsp,byte +0x08         ;Allocate 8 bytes on the stack.
sub rsp,byte +0x30         ;Allocate shadow space for WriteFile (48 bytes)
sub rsp,byte +0x20         ;Allocate shadow space for GetStdHandle
mov rcx,0xfffffffffffffff5 ;Set the constant for stdout
call [rel 0x1060]          ;Call GetStdHandle. The handle for stdout is now in RAX
add rsp,byte +0x20         ;Deallocate shadow space for GetStdHandle
mov rcx,rax                ;Set stdout handle: hFile
mov rdx,0x403004           ;Set the pointer to string "Hello World!\r\n": lpBuffer
mov r8,0xf                 ;Set the length of the string: nNumberOfBytesToWrite
mov r9,0x403000            ;Set the pointer for lpNumberOfBytesWritten
mov qword [rsp+0x20],0x0   ;Push a 64 bit NULL pointer onto the stack: lpOverlapped
call [rel 0x1068]          ;Call WriteFile
add rsp,byte +0x30         ;Deallocate shadow space for WriteFile
sub rsp,byte +0x20         ;Allocate shadow space for ExitProcess
mov rcx,0x0                ;Set the return value
call [rel 0x1058]          ;Call ExitProcess
add rsp,byte +0x20         ;Deallocate shadow space for ExitProcess

I understand it doesn't really matter that the space for WriteFile is allocated well in advance, but why is it sub rsp,byte +0x30 and not sub rsp,byte +0x28? And why is the first sub rsp,byte +0x08 there? Is it FASM's idiosyncrasy or am I fundamentally misunderstanding Microsoft x64 stack management rules?
Comment: The stack is aligned when the program starts. Each function call pushes an 8-byte return address on the stack. So each called function must realign the stack to a multiple of 16, by subtracting an odd multiple of 8.
Comment: Moral of this story: don't use `invoke` in 64-bit code: the only way for code to be efficient is to reserve shadow space once that multiple calls use, but an `invoke` macro or built-in statement can't assume anything about surrounding code.  If you want to write high-level code, use a C compiler.  MASM chose differently from FASM: they [dropped support for `invoke` from 64-bit](https://stackoverflow.com/questions/65279900/how-does-32-bit-masm-mode-differ-from-64-bit#comment115431977_65280053), along with their `.if` crap (again, use a C compiler if you want "high level" code.)
Comment: Thanks—it's clear now that each invoke call has its own stack adjustment, which is why there are so many of them.
Comment: There is one rule that you seem to be unaware of. The stack has to be 16-byte aligned. That's probably what the first sub 8 is for. Then all the subsequent adjustments are multiples of 16.
Comment: Yeah this code is terrible. Can you add the source code that generated it? It doesn't need separate shadow space for each function called. And it's crazy to adjust the stack point multiple times. It should just do `sub rsp, 0x28` once at the beginning of the function.
Comment: The way this code is formatted makes it very difficult to read. Can you please gel rid of all the extra lines.
Comment: @prl I've added the FASM source and cleaned up the disassembly. Why would the stack not be aligned when the program starts?
Answer: The comments already addressed the 16-byte stack alignment, which causes the stack to become misaligned after pushing the return address in a call instruction, meaning you have to re-align it with sub rsp, 8 in the function prolog, see https://learn.microsoft.com/en-us/cpp/build/stack-usage.
You also mentioned the shadow store of 32 (0x20) bytes, which can be used to spill the first 4 parameters, which are passed in registers, see https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention.
While the caller is responsible for allocating the shadow store, this can of course be combined for multiple function calls. FASM can actually do this though, using the frame/endf macro, see https://flatassembler.net/docs.php?article=win32#1.4. Now if you explicitly call GetStdHandle, removing the nesting (not sure why this is required), you can combine the allocations:
format PE64 console
include 'win64wx.inc'
.code
  start:
   frame
    invoke GetStdHandle,STD_OUTPUT_HANDLE
    invoke WriteFile,rax,hello,hello.length,dummy,0
    invoke ExitProcess,0
   endf
  .end start
.data
  dummy rd 1
  hello db "Hello world!",13,10,0
  hello.length = $ - hello

Which assembles to:
sub rsp,0x8
sub rsp,0x30
mov rcx,0xFFFFFFFFFFFFFFF5
call qword ptr ds:[<&GetStdHandle>]
mov rcx,rax
mov rdx,test.403004
mov r8,0xF
mov r9,test.403000
mov qword ptr ss:[rsp+0x20],0x0
call qword ptr ds:[<&WriteFile>]
mov rcx,0x0
call qword ptr ds:[<&FatalExit>]
add rsp,0x30

The sub rsp, 0x20 is gone now. Unfortunately, the sub rsp, 8 is still here (it's inserted by the .code macro), but it's much cleaner. If you use the proc macro then the push rbp will already align the stack, so you don't need an extra sub rsp, 8.
Now of course this is FASM, so you can add/redefine some macro's to combine all allocations if you don't use proc, and maybe even use the shadow store for spills of nonvolatile registers you use, and keep the stack unaligned when you don't call functions. This is what I did in https://github.com/stevenwdv/asmsequent/blob/main/proc_mod.inc (with frame/save/rest(ore)/... macros), it may be a bit ugly and I don't know (anymore) how most of it exactly works, but it got the job done. E.g. function solve assembles to:
mov qword ptr ss:[rsp+0x8],r12
mov qword ptr ss:[rsp+0x10],r13
mov qword ptr ss:[rsp+0x18],r14
mov qword ptr ss:[rsp+0x20],r15
push rsi
push rbx
sub rsp,0x28
...
call ...
...
call ...
...
add rsp,0x28
pop rbx
pop rsi
mov r15,qword ptr ss:[rsp+0x20]
mov r14,qword ptr ss:[rsp+0x18]
mov r13,qword ptr ss:[rsp+0x10]
mov r12,qword ptr ss:[rsp+0x8]
ret

Note the combined allocations (and the usage of the shadow store where possible).


Getting postfix to receive email, connection time out on port 25

Question: I'm having a hard time setting up an email server. I decided to go with and E2C instance (specifically, with light-sail) running Ubuntu. On the server, I've put postfix on the server more or less following this guide to the letter. From postfix, I'm able to send an email (and receive it at Gmail). However, I'm not able to receive any mail when I send an email back to my server from my Gmail.
I slam my domain name for the server into mxtoolbox and it tells me "failed to connect"
So I thought to myself... either that port is closed (firewall somewhere) or there isn't a server listening on that port.
I made sure to...
sudo ufw allow Postfix

On the server I...
telnet 'mydomain' 25
Trying 'ip' ...
telnet: Unable to connect to remote host: Connection timed out

Just to see if the server is up and running...
telnet 'mydomain' 80
Trying 'ip' ...
Connected to 'mydomain'

So no new info. So I tried...
netstat -lntu
proto     Recv-Q    Send-Q    Local address    Foreign Address   State
tcp            0         0    0.0.0.0:25       0.0.0.0:*         LISTEN
tcp6           0         0    :::25            :::25             LISTEN
(other lines omitted)

So it would seem that something has opened that port and is listening to it, but... I can't figure out why no connection gets through.
Please give me some trouble shooting ideas on this. I'll add more information as it is asked for if its needed.
edit: more info & spelling
Answer:
sudo ufw allow Postfix

Should not work as there is no service named Postfix registered in /etc/services. man ufw
Use either the SMTP port:
 sudo ufw allow 25/tcp

or the correct service name:
 sudo ufw allow smtp

Comment: I entered in those commands, but it returned with

"Skipping adding existing rule"

So I think somewhere along the line of trying to fix this I had those rules in place already. Or have I misunderstood what I should do?
Answer: I figured it out! after some more digging...
I got
telnet localhost 25

to work. So the server is up and alive, that left only the networking and ports  to be looked at.
The server wasn't blocking the port, so that left either the network or the ISP blocking that port. Since the server is an E2C server (specifically light-sail), I thought that either were impossible. I was wrong. The isp that amazon uses is fine, HOWEVER! Amazon blocks all ports except 22 and 80. You need to go to your instance, go under the networking tab, and add a tcp port at port 25. Now...
telnet 'mydomain' 25
Trying 'myIp'
Connected to 'mydomain'

Thanks for the help! I hope this helps others.
Comment: *"You need to go to your instance, go under the networking tab, and add a tcp port at port 25."* What exactly are you talking about, here?  Where is the "networking tab?"  Is this a Lightsail instance?
Comment: My bad, I do mean Lightsail. If you click on an instance when looking at your lightsail dash, there should be some tabs near the top (but not at the top). the tabs are "connect", "Metrics", "Networking", "snapshots" , "history", "delete". I mean the networking tab there. There you should see a list of ports that are white listed (designated to be NOT-BLOCKED). Simply add the type of port you want at the right port number (SMTP was a TCP port at port 25, I named mine custom). After that, everything worked fine.
Comment: You should correct your question to reflect that this is Lightsail, not EC2.  The hardware is the same but the platforms are very different.


How do I query a database for only one field of a resultset? (JAVA ODBC)

Question: I have an assignment I am working on (and trying to debug). I have a JComboBox which I need to fill with only ISBN numbers.  The Database returns ISBNs, BookTitle, QuantityOnHand, and Price.  I am to make a method (loadCombo) which is to load the comboBox with (as I said) only the ISBN numbers. I have this little snippet written:
    public static void loadCombo(JComboBox box)
{
   String query = "SELECT * FROM Books";

   try
   {
       result = statement.executeQuery(query);
       result.getString(1);
       addISBN(result,box);
   }
   catch(SQLException sqlex)  {sqlex.printStackTrace();}
    public static void addISBN(ResultSet result,JComboBox box)
{
    try
    {
         while(result.next()) {box.addItem(result);}
    }
    catch(SQLException e)   {e.printStackTrace();}
}

However, this throws a load of errors.  What am I doing wrong here? I thought that I was making a resultSet (result), then getting the first field (result.getString(1)), and then throwing the resultset  and combobox to my addISBN method which will add the resultset to my comboBox?
So I did what the first answer said (thank you for the advice, I guess I should read my assignments a little more carefully!).  However, I now crash on the addISBN method. My ISBN textbox has 14 lines, all say
'sun.jdbc.odbc.JdbcOdbcReseltSet@13f9460'
Comment: For the error I guess it cause by {box.addItem(result);} use {box.addItem(result.getString(1));} and I think you don't need the result.getString(1); before addISBN(result,box);. See duffymo answer
Comment: Thanks @Ace, appreciate the tip!
Answer: Your UI and combo box should not come within one hundred yards of persistence code.  It's called layering or separation of concerns.  Tell your professor that it's considered a best practice in the real world.
This code is heinous.  I'd write it more like this.  Notice how I close those resources in the scope of the method in which they were created.  That's important.  No JDBC classes should leak out of the persistence package.  Load the results into a data structure (in this case, a List of Strings for ISBNs).
Java's an object-oriented language.  Where's the Book model class?
package persistence;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * BookDao
 * @author Michael
 * @since 4/6/11
 */
public class BookDao
{
    public static final String SELECT_ALL_BOOKS = "SELECT * FROM Books";

    private Connection connection;

    public BookDao(Connection connection)
    {
        this.connection = connection;
    }

    public List<String> find() throws SQLException
    {
        List<String> isbn= new ArrayList<String>();

        Statement statement = null;
        ResultSet result = null;

        try
        {
            statement = this.connection.createStatement();
            result = statement.executeQuery(SELECT_ALL_BOOKS);
            while (result.next())
            {
                isbn.add(result.getString(1));
            }
        }
        finally
        {
            close(result);
            close(statement);
        }

        return isbn;
    }

    private static void close(ResultSet result)
    {
        try
        {
            if (result != null)
            {
                result.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    private static void close(Statement statement)
    {
        try
        {
            if (statement != null)
            {
                statement.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }
}

Comment: +1 nice points.. this same with my coding structure.. though I have an AbstractDAO because of many different queries. @unit this will be a great if you follow this techniques.
Comment: Unfortunately, if I follow this, I will be told that I have not been taught half of it, and will lose marks for copying something off of the internet.  I do appreciate the points, however, it makes me a little sad to see that I am being taught 'heinous' coding techniques.
Comment: But you have been taught, just not by your professor.  Things like "close your resources" and "layers".  Good luck.
Answer: Might want to construct a proper SQL statement. Instead of SELECT * FROM Books, use SELECT [column name in db] FROM Books
edit: What unit wrote in his comment.
Comment: agree with the approach but that still doesn't solve poster's problem that is causing by referencing to result instead of to the string returned by result.setString(1)
Comment: Okay, that's pretty fair.  I rechecked my assignment, because I thought it stipulated that you had to use SELECT *.   I was wrong...... So I changed that to SELECT ISBN FROM Books, and that worked, but now it crashes when it tries to add the resultSet.
Answer: REmove the result.getString(1); line.  With a ResultSet, you need to do a next() before you can access the resultset elements, as there is no current row prior to a next();
Also, for the future, you are much more likely to get good responses if you post the exception details.
Answer: String myStr = result.getString(1);

Then use myStr instead of result. use result  only to navigate to the next row.
Reference - ResultSet
Comment: In that case, change box.addItem(result); to box.addItem(result.getString(1)); result is the resultset object, NOT the individual record value. You cannot get the individual  record value unless you call getString (or similar. See ResulSet api) on the resultset
Comment: My assignment stipulates that I have to pass a resultSet to my addISBN method.


How can I enlarge image on hover using HTML?

Question: I am trying to enlarge images on hover using HTML?
I am using Shopify.
Also, how can I add CSS in Shopify?
Can I combine HTML and CSS in the same code body?
Many thanks
For example, this is the image code, where do I put the "hover CSS"

<img class="multicolumn-card__image" srcset="//cdn.shopify.com/s/files/1/0621/4808/3896/files/cover_1_3750b60e-26ea-4618-b8a5-a597e561ecda.png?v=1682523968&width=275 275w,//cdn.shopify.com/s/files/1/0621/4808/3896/files/cover_1_3750b60e-26ea-4618-b8a5-a597e561ecda.png?v=1682523968&width=550 550w,//cdn.shopify.com/s/files/1/0621/4808/3896/files/cover_1_3750b60e-26ea-4618-b8a5-a597e561ecda.png?v=1682523968&width=710 710w,//cdn.shopify.com/s/files/1/0621/4808/3896/files/cover_1_3750b60e-26ea-4618-b8a5-a597e561ecda.png?v=1682523968&width=1420 1420w,//cdn.shopify.com/s/files/1/0621/4808/3896/files/cover_1_3750b60e-26ea-4618-b8a5-a597e561ecda.png?v=1682523968 1564w" src="//cdn.shopify.com/s/files/1/0621/4808/3896/files/cover_1_3750b60e-26ea-4618-b8a5-a597e561ecda.png?v=1682523968&width=550" sizes="(min-width: 990px) 550px,
                        (min-width: 750px) 550px,
                        calc(100vw - 30px)" alt="https://cdn.shopify.com/s/files/1/0621/4808/3896/files/105_Ready_To_Wear_-_The_Shimmering_Selection_1_1b411c2a-2b6f-4a37-8258-708da67cdd82.png?v=1682523879" height="2130" width="1564" loading="lazy" style="<
    style>
.zoom {
  padding: 50px;
    background-color: green;
    transition: transform .2s; /* Animation */
    width: 200px;
    height: 200px;
    margin: 0 auto;
}

.zoom:
    hover {
  transform: scale(1.5); /* (150% zoom - Note: if the zoom is too large, it will go outside of the viewport) */
}
</
    style>

;
    style>
.zoom {
  padding: 50px;
    background-color: green;
    transition: transform .2s; /* Animation */
    width: 200px;
    height: 200px;
    margin: 0 auto;
}

.zoom:
    hover {
  transform: scale(1.5); /* (150% zoom - Note: if the zoom is too large, it will go outside of the viewport) */
}
</
    style>

;
">
Answer: You can use the scale property in css to increase the image/element size:
image:hover{
  scale: 1.5;
}

The value of scale represents the multiple that the element should increase by.
You could also add a transition to make it smoother:
image{
  transition: scale .2s;
}

Comment: Thank you Miro.

Where can I put the CSS code? Can It be added with the HTML?
Answer: To enlarge an image on hover using HTML, you can use CSS to apply a transformation to the image when the mouse hovers over it.

.image-container {
  position: relative;
  overflow: hidden;
  display: inline-block;
}

.image-container img {
  transition: transform 0.3s;
}

.image-container:hover img {
  transform: scale(1.2);
}


makefile : applying a single rule to a bunch of target

Question: I'm starting to learn how to write makefiles and I can't find an existing topic related to my question, so apologies if it already exists.
As of now, it looks like this (and it works) :
INSTALL_DIR = $(realpath /home/$(USER)/bin/)
SRC         = $(realpath ./)
script      = $(SRC)/foo.sh
TAR         = $(INSTALL_DIR)/foo

all : $(TAR)

$(TAR) : $(script)
    ln -s $^ $@

What I would like to do is to use a minimum number of lines to generate symbolic links (that is, applying the existing rule for building TAR) to every bash script (that is $(SRC)*.sh)  in the same fashion as I did for the first one ('foo.sh') here.
I could just make 'script' and 'TAR' like variable for every script manually but I'm sure there must be a better way. Little help ?
Comment: You have two problems: 1) constructing a list of all scripts in the working directory, and 2) constructing a link for each script on the list. Which problem would you like help with? (P.S. and how do you want to name the links?)
Comment: Unless defining
     TAR=(wildcard $(SRC)*.sh)
is the correct way to do it, I would like help on the first issue.
I have no idea how to manage the second, so I'd like help with this as well.
I would like the links to have the same names as the files they refer to but without any extension, is this possible ?
Answer: You're looking for a pattern rule.   Something like:
SCRIPTS := foo bar xxx yyy

all: $(SCRIPTS)

% : %.sh
    ln -s $< $@

Note that $(SCRIPTS) can also be populated by $(wildcard ...) if none of the scripts are generated by make (otherwise, $(SCRIPTS) would be missing any file that did not exist when make was first invoked).
Answer: First we must find the scripts:
INSTALL_DIR = bin # there is no need for a full path here
SRC = $(realpath ./)

SCRIPTS := $(wildcard $(SRC)/*.sh) # /some/path/foo.sh /some/path/bar.sh /some/path/baz.sh
SCRIPTS := $(notdir $(SCRIPTS)) # foo.sh bar.sh baz.sh

Note my use of ":=" rather than "=". You can read about the difference here, but usually ":=" is better.
Now for the targets, the links we're trying to construct:
TARGETS := $(basename $(SCRIPTS)) # foo bar baz
TARGETS := $(addprefix $(INSTALL_DIR)/, $(TARGETS)) # bin/foo bin/bar bin/baz

The rules:
all: $(TARGETS)

$(INSTALL_DIR)/%: $(SRC)/%.sh
    ln -s $< $@

That last rule is quite general. We could restrict it to the target list we defined:
$(TARGETS): $(INSTALL_DIR)/%: $(SRC)/%.sh
    ln -s $< $@

Further refinements are possible, once this is working perfectly.
Comment: Thank you very much, I almost got it to work. The only remaining issue is that when I define TARGETS as $INSTALL_DIR$(basename SCRIPTS) (not the other way around, but it does not matter), I get a redundant path because apparently basename only cuts out the extension but not the complete absolute path that is return using wildcard. How can I go around this ? (I apology for the trivial nature of my questions but I really get lost in the documentation)
Comment: @Neutrinoceros: Sorry, that was my oversight. Try `TARGETS := $(INSTALL_DIR)$(basename $(notdir $(SCRIPTS)))`, and if that doesn't work we'll go through it step by step.
Comment: It doesn't.
The thing is, $(INSTALL_DIR)$(basename $(notdir $(SCRIPTS))) returns
"~/bin/foo bar baz", so if I use __make clean__ (defined as rm $(TARGETS)) to uninstall, it's going to remove the first link but won't find the others because it's looking for them in the current directory.
More importantly, trying to recover the installation using __make__ yields the following error:
**no rule to make target**.
I except the fault lies in the pattern definition which may be confusing because I don't want to specify any extension. Is there a way to work around that ?
Comment: Ok I got the first issue solved using addprefix as follow
`TARGETS     = $(addprefix $(INSTALL_DIR)/, $(basename $(notdir $(SCRIPTS))))`
Still struggling with the pattern part though.
Comment: I should have thought of that-- I really am making a lot of mistakes this week. But can you explain what you mean by *"I don't want to specify any extension"*? You specify the extension ".sh" when you search for scripts; would you prefer not to? Do you want Make to treat any file of the form `*.*` as a script?
Comment: Ok this one in on me. I meant I don't want my _links_ to have any extension, the goal is to make them behave as usual bash commands from terminal. But yes, I still want to specify that the corresponding dependency for "foo" is "foo.sh".
edit : I deleted the duplicate question, sorry for that and thank you very much for the help you provided thusfar.
Comment: @Neutrinoceros: All right, I've completely revised -- and tested -- my answer. That ought to do it, but if not, we'll tear it down and build up in stages.
Comment: This works like a charm. Thanks again for your patience and commitement :-)
Thank you also for the documentation, I actually meant to ask the difference between `=`and `:=`
**nb** should I make edits to the original post to include your solution of mark the topic as closed ?
Comment: @Neutrinoceros: No, you can leave it just as it is. Glad I could help.


Join query question that I can't figure out

Question: So I have three tables:
Table Place:  _id autoincrement not null primary key, name TEXT,place TEXT
Table Food: _id autoincrement not null primary key, food TEXT
Table Person:  _id autoincrement not null primary key, personName TEXT, PLACE_ID INTEGER NOT NULL, FOOD_ID INTEGER

I want to pull all the food and Place information however, as noted in the person table, there can be a null value for FOOD_ID.  Assume the database is fully populated correctly. How do I query this? I tried to following query:
select * from Person,Food,Place where Place._id = Person.PLACE_ID and if not null Person.Food_id Food._id = Person.FOOD_ID

But that doesn't work!
Any help would be greatly appreciated!
Thanks!
Jon
Answer: SELECT *
FROM Person p
INNER JOIN Place pl
    ON p.PLACE_ID = pl._id
LEFT OUTER JOIN Food f
    ON p.FOOD_ID = f._id

Remember, a LEFT OUTER join returns ALL rows in the left table (Person in this case) even when there are no matching rows in the right table. The values for the right side table will all be NULL.
Comment: and what if we want to select only people's name whose is say Jon?


Is it allowed to use ∃y-elimination rule when you have: ∀x∃y φ?

Question: I am given the following expression: ∀x∃y R(x, y) ⊢ ∃y∀x R(x, y) and I have attempted solving it as:
<code>∀x∃y R(x,y)      premise
  | ∀x R(x,y0)    assumption
  |  | x0
  |  | R(x0,y0)   ∀xe 2
  | ∀x R(x,y0)    ∀xi 4
  | ∃y∀x R(x,y)   ∃yi 5
∃y∀x R(x,y)       ∃ye 1, 2--5
</code>
My concern is the first assumption, and therefore the use of the ∃y-elimination rule. Is this a valid approach?
Comment: No, you cannot remove $\exists$ before $\forall$ in $\forall x \ \exists y$. Quantifiers must be "unpacked" the outermost first.
Comment: For these questions, it is often useful to test them on easy formulae. For instance, let us define $R(x, y) \iff x = y$. The left premise is obvious (just take $x = y$), the right premise is trivially false.
Answer: No, you have to apply the rules for the outermost operator first. Logically, you are saying that there is one $y_0$ satisfying $R(x,y_0)$ for all $x$ which is a wrong deduction.


Is this a nested logit when my regression equations are similar to that of a multinomial regression?

Question: Let the mode of transport be a categorical random variable with three categories, representing Car, Bus and Train respectively. The goal is to predict for the $n$-th person, what mode of transport they use to commute to work.
Suppose that I think that when making the choice of transport to take, a person first decides whether they will catch public transport or not. Then, if they catch public transport, they have the choice of going by bus or train. This hierarchical/nested relationship can be understood using a modification of Figure 4.1 (page 90) from Chapter 4: GEV of Train:

This leads to a model that produces a vector of probabilities $(p_{0}, p_{1}, p_{2}) = (p_{n0}, p_{n1}, p_{n2})$ for the modes Car, Bus, and Train respectively via the regression equations (I am going to abuse notation and drop subscripts involving $n$ from now on):
$$
\begin{split}
\operatorname{ln}(\frac{p_0}{1 - p_0}) &= y_0 \\
\operatorname{ln}(\frac{p_1}{p_2}) &= y_1\\
p_0 + p_1 + p_2 &= 1
\end{split}
$$
where $y_0 = \alpha_0 + \alpha_1 x_{01} + \alpha_2 x_{02} + \dots $ and $y_1 = \beta_0 + \beta_1 x_{11} + \beta_2 x_{12} + \dots $ are linear combination of covariates, possibly shared. The expression on the LHS of the first equation is the usual logit and the LHS of equation two is the generalised logit as seen in the Wikipedia article on multinomial logistic regression.
My regression equations describe two logistic regressions of sorts, one nested within the other. The first equation mimics a standard logistic regression problem for predicting whether a person catches public transport or not, and the second equation is a logistic regression (adapter so that probabilities sum to one) for whether a person catches a bus or a train, conditional on them catching public transport.
My question is whether this model is a useful discrete choice model for the question at hand, as it doesn't seem like it is a nested logit (GEV) model, nor does it seem like a multinomial regression model. It doesn't seem like a GEV model for the following reasons. Following Chapter 4.2 of Train, linking my first equation for the "upper" model to the "lower" model seems to require $\lambda$, a parameter for the cumulative GEV distribution (Equation 4.1, reproduced below), to be set to zero, which does not seem to make sense:
$$\exp\left(-\sum_{k=1}^K\left(\sum_{j \in B_k} e^{-\epsilon_{nj}/\lambda_k}\right)^{\lambda_k}\right)$$
It also is not a multinomial logit as the relationship between the covariates and the predicted probabilities are different, when covariates are shared, i.e. $x_{0j} = x_{1j}, \forall j$. My first equation is subtly different to the one given by multinomial logistic regression, when assuming that Train is the reference class:
$$
\operatorname{ln}(\frac{p_0}{p_2}) = y_0
$$
To simplify notation, let $Y_0 = \exp(y_0)$ and $Y_1 = \exp(y_1)$. Then, solving for the probabilities from my equations:
$$
\begin{split}
p_0 &= \frac{Y_0}{1+Y_0}\\
p_1 &= \frac{(1 - p_0) Y_1}{1+Y_1}\\
p_2 &= 1 - \frac{p_0}{1+Y_1} - \frac{Y_1}{1 + Y_1}
\end{split}
$$
In contrast, with multinomial logit one obtains:
$$
\begin{split}
p_0 &= \frac{Y_0}{1+Y_0 + Y_1}\\
p_1 &= \frac{Y_1}{1+Y_0 + Y_1}\\
p_2 &= \frac{1}{1+Y_0 + Y_1}
\end{split}
$$
Comment: I guess this may also be related to some kind of hurdle model: https://stats.stackexchange.com/questions/81457/what-is-the-difference-between-zero-inflated-and-hurdle-models
Answer: If you are using maximum likelihood and are performing no model selection, they are equivalent modeling strategies. However, in most other settings the multinomial model is considerably more constrained. For instance, if you include the effects of various covariates (income/work schedule/residential setting/etc.) the multinomial model requires each parameter to predict each multinomial outcome, however the hierarchical model can use non-overlapping subsets of the candidate predictors in each step leading to considerably sparser model.


Decimal to Binary within an ArrayList java

Question: Input is a decimal number and the output is supposed to be that same number in binary form in an ArrayList, but for some reason it is only outputting 1s
Digit is a class whose only value is an int "bit" and a 2-bit adder.
<code>private ArrayList<Digit> numbers;
private Digit number;

public Converter(int val){
    numbers = new ArrayList<Digit>();
    number = new Digit(val);
    if (val == 1 || val == 0){
        numbers.add(number);
    } else{
        while (val >= 1){
            number.setValue(val % 2);
            numbers.add(number);
            val = val/2;
        }
    }
}

public String toString(){
    return "" + numbers;
}
</code>
This is outputting the correct number of elements, but all of them are 1s.
ex. 5 = 1,1,1 rather than 1,0,1.
Comment: Have you tried running it through a debugger? Note that for val = 2, this returns [0, 1]... so a zero, but its in the wrong place.
Comment: Please include the Digit class
Answer: You're using the same object of Digit to occupy all places in the ArrayList, hence it just shows the last value written to the object.
Store clone of the object in the ArrayList to get the desired result.
Comment: Thank you! I didn't realize that I couldn't just change the value of the object.


Event handling (Detect when hiding form)

Question: Well normally I am quite good at figuring and researching problems without guidance however I have come across a snag. I am trying to create an "Event" with C# (which I have not done before) everything I have looked up has nothing to do with what I need.
I am trying to call a class on my main form when form2 is hidden. I found some code which was supposed to check to see if form2 closed - Either I didn't integrate it into my code properly or closing is different to hiding.
So just to clarify I want to run through the program like this:

Form1 runs
Click setting button on Form1 which opens Form2
Form2 opens where settings can be changed
Click the "Ok" button on Form2 (here is where I want Form1 to realise Form2 has been hidden
Hide form one and run a class called Refresh which refreshes button names and URLs
Answer: Also,
you can use VisibleChanged event in Form2
private Form2_VisibleChanged(object sender, EventArgs e)
{
    if (!this.Visible) { Refresh(); }
}

This might be more elegant...
Answer: Open the second form as modal
Form2 form2 = new Form2();
DialogResult result = form2.ShowDialog();

check the result and refresh:
if (result == DialogResult.OK)
    Refresh();

What you also need to do in this case is when closing the form set DialogResult of the form, for example if you have an OK button, in the button handler set:
this.DialogResult = DialogResult.OK;

This will automatically close the form as well as I remember correctly.
What you can also do is set DialogResult.Cancel on cancel button if you need that.
Comment: It couldn't find "ShowModal" wanted a reference. I did change it to ShowDialog. It opened fine but when I clicked ok it didn't reference the "Refresh." Where do I place the "result"? I placed it under the "show" on Form1.
Comment: Uh, yes, sorry for the typo, it is ShowDialog()
Comment: Thank you! Been working on events for so long and here you come giving me 3 lines of code. I hate programming sometimes! Thanks
Answer: If I understand correctly, you want to have a class that stores settings information that both Form1 and Form2 can access. Let's call that class Form1Settings, and implement as:
public static class Form1Settings
{
    public static string ButtonText;
    public static string Uri;
}

For simplicity, I made this class and its properties static, so both Form1 and Form2 have direct access to it, removing the need for a refresh method.
Form1 would call Form2 in a blocking way, and only update its display if the OK button was clicked.
public partial class Form1 : Form
{
    private Form2 form2 = new Form2();

    public Form1()
    {
        InitializeComponent();
    }

    private void buttonSettings_Click(object sender, EventArgs e)
    {
        if (form2.ShowDialog() == DialogResult.OK)
        {
            this.button1.Text = Form1Settings.ButtonText;
            this.textBoxUrl.Text = Form1Settings.Uri;
            this.Update();
        }
    }
}

And finally, Form2 will update the settings values with input from the user:
public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void buttonOK_Click(object sender, EventArgs e)
    {
        Form1Settings.ButtonText = this.textBoxButton.Text;
        Form1Settings.Uri = this.textBoxUri.Text;

        this.DialogResult = DialogResult.OK;
        this.Hide();
    }
}

Answer: Why not open Form2 as a modal dialog using ShowDialog()? That way you may return a value if Form2 was closed by OK or by Cancel and act accordingly in Form1 after the call returned.


Proving injection and surjection with functions $F:C^B\to C^A$, $F(f)=f\circ\varphi$, $\varphi: A\to B$

Question:
Let $\varphi: A\to B$ and define $F:C^B\to C^A$ such that $F(f)=f\circ\varphi$. Prove the following:

if $\varphi$ is surjective then $F$ is injective.

if $\varphi$ is injective then $F$ is surjective.

For both of them I realize that I should begin with assuming the condition on $\varphi$ is true and the condition for $F$ is false and then apply the composition in some way to get a contradiction but I have no idea how to begin...
Answer: (1) Let $\varphi$ be surjective. Let $f_1, f_2$ be such that $F(f_1) = F(f_2).$ Now $f_1 \
\circ \varphi = f_2 \circ \varphi.$ Then $f_1 (\varphi (x)) =f_2( \varphi(x)), \forall x \in A.$ Since $\phi$ is surjective, $f_1(y) = f_2(y), \forall y \in B.$ So $f_1 =f_2.$
(2) Let $\varphi$ is injective. Let $f: A \to C$ is given. Define $g : B \to C$ by $g(y)= f( \varphi ^{-1}(y)),$ if $y \in \varphi(A)$ and $g(y) = c,$ if $y \in B \setminus \varphi (A)$ where $c \in C$ is any element. Since $\varphi$ is injective, this map is well defined. Then $g (\varphi (x)) = f(\varphi^{-1}(\varphi (x))) = f(x), \forall x \in A,$ showing that $F(g) = g\circ\varphi = f.$ Hence $F$ is surjective.
$\bf Note:$ The above given solutions are based on the assumption that all the sets $A, B, C$ are non-empty (though it was not stated in the question). In fact, if we don't assume this condition, then (2) is not true. Thanks to Marc van Leeuwen for pointing this. See his comment below for an example.
Comment: Thanks. 1. looks pretty straight forward now... Can you share what was your thought process for 2 please? How did you know to define $f,g$, and  $g(y)=f(\varphi^{-1}(y)), g(y)=c$? I just really doubt I could've come up with this on my own.
Comment: if $\phi$ were given bijective, then every $y \in B$ has a unique preimage $\phi^{-1}(y) \in A.$ so from the condition $g(\phi(x)) = f(x), \forall x \in A$ it's very natural choice to define $g(y) := f(\phi^{-1}(y)), \forall y \in B.$ here $\phi$ *not* bijective, but it is injective. so $\phi: A \to \phi(A)$ is bijective. you might be interested in the following link also: http://math.stackexchange.com/questions/1095468/contruction-of-bijection-between-set-of-functions
Comment: I'll check it out. Also, how is it that you don't use $F$ in 2?
Comment: $F(g) = f \Leftrightarrow g \phi = f \Leftrightarrow g(\phi(x)) = f(x), \forall x \in A.$ I showed the last equality.(And being lazy, didn't write it completely. Now added.)
Comment: The proof shows that point 2. actually fails, in one type of case: $A=C=\emptyset$ and $B\neq\emptyset$. The $f$ is vacuously injective, but $F:\emptyset^B\to\emptyset^\emptyset$ cannot be surjective, since its domain is empty while its codomain has one element.
Comment: @MarcvanLeeuwen: Thank you for pointing this. I didn't think about this case. I assumed (back in my head) that all the given sets are *non-empty.* I'll add that hypothesis in my answer with due reference.


How to get data from DB of 'testimonials' content type?

Question: I have create a content type .i.e "testimonial",
This content type have two fields.
<code>[1]field_data_field_testimonial_title
[2]field_data_field_testimonial_image
</code>
I have insert 3 records from admin,
Now i want to retrieve all(3) records of "testimonial" content type.
But How?
Comment: How do you want to get them?  Via code?  Make a page with all three?  We need more info on what you are trying to accomplish, and then we can tell you how.
Answer: You want to learn how to use the views module.

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

Views can do a lot more than that, but those are some of the obvious uses of Views.
Comment: So, it means i want to use View module for the same?
Comment: Yes use views, to get all the records of your testimonial content type


If a finite group $G$ has a normal subgroup $N$ of order $3$ that is not contained in $Z(G)$, then $G$ has a subgroup of index $2$.

Question:
If a finite group $G$ has a normal subgroup $N$ of order $3$ that is not contained in $Z(G)$, then $G$ has a subgroup of index $2$.
Since $N$ is normal, we can consider the action of $G$ on $N$ by conjugation, because this will induce a homomorphism that is present in any such mapping of a group into its normal subgroups.

I understand the concept of this, but I am looking at one proof that defines the homomorphism to map from $G$ to $\operatorname{Aut}(N)$. Why is the codomain of this mapping $\operatorname{Aut}(N)$ instead of N?
Then the proof will claim that $\ker \phi = C_{G}(N)$. How do we know that this is true?
The principles used thereafter are just counting, so I can understand it from there. We will say that since $|N|=3$ it contains exactly the elements $1,n,n^{-1}$. Then with the identity it is obvious that for all $g \in G$, we know $g \cdot 1 = g1g^{-1}=1$, and so either $g \cdot n = n$ or $g \cdot n = n^{-1}$. Thus, $\lvert\operatorname{Aut}(N)\rvert=2$, so $G/C_{G}(N)=2$. Therefore the centralizer is a subgroup of order $2$.
Comment: Your text confuses the notions of "order" and "index" for a subgroup, so you need to edit for accuracy so that your problem is clear.
Comment: Oh yes, thank you Mark Bennet! My mistake. I changed it in the title, let me know if I missed it somewhere else too.
Answer: Let me give some structure to your problem:
You have

a finite group $G$.
a group $H$ of order $2$, $H=Aut(N)$.
and a morphism $\phi:G\rightarrow H$.

By 3. and 2. we have that $G/\ker\phi\simeq Im\, \phi$ has order $1$ or $2$ since it's (isomorphic to) a subgroup of $H$.
So your problem is equivalent to checking the statement
$$
G/\ker \phi \simeq H
$$
or equivalently
$$
\phi\text{ is not trivial}.
$$
Group structure of $Aut(N)$
Let $N$ be a group. As a set
$Aut(N):=\{N\rightarrow N, \text{group homomorphism}\}$
The binary operation given by composition
$$
\begin{array}{ccc}
Aut(N)\times Aut(N)&\rightarrow &Aut (N)\\
(F,G)&\mapsto &F\circ G.
\end{array}
$$
Notice that the unit element is the identity map $Id(x) = x$, for every $x\in N$.
Definition of $\phi$
Let $g\in G$, since $N$ is normal subgroup of $G$ then $gxg^{-1}\in N$ for every $x\in N$.
Fix an elment $g\in G$. Check that the map
$$
\begin{array}{ccc}
F_g:&N&\rightarrow &N\\
&x&\mapsto  &gxg^{-1}
\end{array}
$$
is a group homomorphism, i.e. $F_g\in Aut(N)$.
Consider the map
$$
\begin{array}{ccc}
\phi: &G &\rightarrow &Aut(N)\\
  &g &\mapsto &F_g.
\end{array}
$$
Check that $\phi$ is a group homomorphism. I.e. check that $F_{gh}  = F_g\circ F_h$.
Finishing the proof
Notice that $\phi$ is trivial if and only if $N\subseteq Z(G)$.
Answer: Since $N$ is normal, conjugation by $g\in G$ induces an automorphism of $N$, so we obtain a homomorphism $\varphi\colon G\to\operatorname{Aut}(N)$.
Since $N$ is not contained in the center, there is $g\in G$ so that the induced automorphism is not the identity. Since $\operatorname{Aut}(N)$ has two elements, $\varphi$ is surjective and therefore $\ker\varphi$ has index $2$.
The fact that $\ker\varphi=C_G(N)$ is true, but irrelevant.


How do I use API versioning?

Question: I'm using the Services module to produce a REST API.  According to the official documentation, there is a way to version services resources.  I believe version here means supplying a single API (e.g. example.com/api) and allowing clients to specify which version they want per resource with headers.
So I think that means that these two requests would return different results, despite living at the same URL:
Version 1.0:
POST /api/v1/system/set_variable HTTP/1.1
Host: example.com
Accept: application/json
Content-Type: application/json

Version 1.2:
POST /api/v1/system/set_variable HTTP/1.1
Host: example.com
Accept: application/json
Content-Type: application/json
services_system_set_variable_version: 1.2

I cannot make this work for the life of me.  Here are the steps I took:

Enabled the system/set_variable service

Added the following code to mymodule.module (cribbed directly from services.versions.api.php)

.
function _system_resource_set_variable_update_1_1() {
  $new_set = array(
    'help' => 'Create a node with an nid test',
  );
  return $new_set;
}

function _system_resource_set_variable_update_1_2() {
  $new_set = array(
    'help' => 'Create a node with an nid optional prams.',
    'args' => array(
      array(
        'name' => 'name',
        'optional' => TRUE,
        'source' => array('data' => 'name'),
        'description' => t('The name of the variable to set.'),
        'type' => 'string',
      ),
      array(
        'name' => 'value',
        'optional' => TRUE,
        'source' => array('data' => 'value'),
        'description' => t('The value to set.'),
        'type' => 'string',
      ),
    ),
  );
  return $new_set;
}

Cleared cache
Attempted to use the system/set_variable service with postman.
Saw that the system/set_variable service was working

Attempted to use the system/set_variable  service without arguments, per _system_resource_set_variable_update_1_2
Saw that arguments were still required

So what am I doing wrong here?  I'm pretty sure I followed all the instructions.
Answer: Quote from services.versions.api.php

For clients that want to request a specific version they need to pass a certain header

services_RESOURCE_METHOD_version = version
as an example, services_system_set_variable_version = 1.2
@see ServicesVersionTests for code examples

Make sure to use set acceptable Content-Type.

Content-Type: application/x-www-form-urlencoded

GET /v1/status HTTP/1.1
Content-Type: application/x-www-form-urlencoded
API-KEY: AAAAAAA
TOKEN: VVVVVVV
services_status_index_version: 1.1
Host: local.mywebsite.com
Connection: close
User-Agent: Paw/3.0.16 (Macintosh; OS X/10.11.6) GCDHTTPRequest

How do I use API versioning?


Second order differential equations using MATLAB

Question: I'm trying to input a second order differential equation to solve into matlab over x = 0 to x =1. I can't figure out how. Here's the equation:
$\displaystyle y'' = 1 + 0.1 \sqrt{1+(y')^2}$
with initial conditions at zero.
Answer: MATLAB doesn't support second order differential equations outright; it's your job to turn your problem into a system of first order differential equations, as mentioned here.
To wit, first construct the appropriate function:
function dy = rapidash(t,y)
dy = zeros(2,1);
dy(1) = y(2);
dy(2) = 1+0.1*sqrt(1+y(2).^2);

and, using ode45() as an example, ode45(@rapidash,[0,1],(conditions)).


Concatenar dois arrays de acordo com seus respectivos índices

Question: Eu tenho dois arrays, o primeiro sendo [a, c, e, g] e o segundo [b, d, f, h], por exemplo.
Eu quero concatenar estes dois arrays em uma respectiva ordem, formando: [ab, cd, ef, gh] ao invés do concat padrão, que seria [a, c, e, g, b, d, f, h]. Ou seja, o elemento do índice 0 do segundo array, eu quero que se junte ao elemento 0 do primeiro array, e o elemento 1 do segundo array, quero que se junte com o elemento 1 do primeiro array, assim respectitivamente.
O que eu tentei: Reduce, map e foreach. Por conta de eu ainda ser iniciante em lógica de programação, não consegui tirar a ideia do papel.
O meu código é o seguinte: Dois inputs. Cada array que eu demonstrei de exemplo representa os valores respectivos dos meus inputs (o primeiro array representa o primeiro input e o segundo, o segundo). Já que o array ele começa com um valor em branco, '', pois o usuário quem digitará o valor dele e exibirá na tela, eu não consegui realizar um for para cada índice, já que é um array oscilante.
Em uma parte da tela, eu tenho um span que irá mostrar o valor deste novo array que eu almejo.
Comment: *"O que eu tentei: Reduce, map e foreach"* coloca na pergunta o que já tentou
Comment: Do que adianta? Eu tentei e deu errado '-'
Comment: Se eu colocasse o que eu tentei ia ter que encher umas 30 linha de código feio
Answer: É só fazer um for e juntar os elementos.

var array1 = ['a','c','e','g']
var array2 = ['b','d', 'f', 'h']

var array3 = []

for(let i in array1){
    array3.push(array1[i]+array2[i])
}

console.log(array3)
Comment: Muito obrigado meu jovem.
Answer: Você pode intercalar dois arrays de mesmo comprimento usando o método Array.prototype.map() para criar um array o elemento n é uma string composta pelos elementos n de l1 e l2.

l1 = ["a", "c", "e", "g"]
l2 = ["b", "d", "f", "h"]

//e= elemento, i= índice
l3 = l1.map((e, i) => `${e}${l2[i]}`);

console.log(l3);

Ou então use Array.prototype.reduce() passando uma array vazio como valor inicial e com Array.prototype.push() povoe o resultado intercalando os dados.

l1 = ["a", "c", "e", "g"]
l2 = ["b", "d", "f", "h"]

//r= resultado, e= elemento, i= índice
l3 = l1.reduce((r, e, i)=>{
  r.push(`${e}${l2[i]}`);
  return r
},[]);

console.log(l3);


Do APNS push notifications work after removing an app from the App store?

Question: I am in the process from transitioning an iOS app from one developer account to another. The original app uses APNS push notifications extensively, and wouldn't be very useful were they to stop.
To remove confusion about app duplication and rights, I am planning on marking the original app as 'Developer Removed from Sale' in iTunesConnect while the new app is in the review process.
Later, I will submit an update to the original app which points the old users to the new app in the App Store.
My question is: If I mark an app as removed from sale, will my existing APNS notifications continue to work for people who have already downloaded the old application? Note: I am not deleting the application, merely marking it as not for sale.
Answer: If the application hasn't changed of appId on the same Apple account, notifications will continue to work, if the certificate is not revoked, or expired.
Comment: Production APN certificates expire after 1 year.  If you can transition your users to the new app before this happens, you should be fine; if not, you may lose the ability to send to apps created under the deprecated account.
Comment: Is there any official documentation claiming the same?


MALLET - How to pass the csv file which contains word count to näive bayes in mallet?

Question: I have created the CSV file which contains label name and word frequency.
e.g.
<code>    0, 4.0, 0.0, 0.0, 1.0, 0.0

    0, 0.0, 1.0, 2.0, 0.0, 0.0

    1, 1.0, 0.0, 0.0, 0.0, 3.0
</code>
Where the index zero represents the label (0 and 1)
My question is, How to import this kind CSV file into mallet to generate instance list? How to pass this file to Näive Bayes Classifier?
Answer: I found the answer to my own question.
In mallet, there are some pipes which create CSV to feature vector.
<code>    pipeList.add(new Csv2Array());
    pipeList.add(new Target2Label());
    pipeList.add(new Array2FeatureVector());
</code>
Output for above example:
0 and 1: It takes as target name.
for the first line:
1(1)=4.0
2(2)=0.0
3(3)=0.0
4(4)=1.0
5(5)=0.0
same for other two lines.


Graphic sequence $\langle n-d_1-1, \cdots, n-d_n -1 \rangle$

Question: Prove that the sequence $ \langle d_1, \cdots ,d_n \rangle$ is a graphic sequence if and only if  $\langle n-d_1-1, \cdots, n-d_n -1 \rangle$  is a graphic sequence.
The theorem I am trying to apply is: " The sequence $\langle d_1 ,\cdots , d_n\rangle$ is a graphic sequence if and only if the sequence $\langle  d_2-1 , \cdots ,d_{d_1 +1} -1 , \cdots ,d_n \rangle $ is a graphic sequence.
Any help?
Thank's in advance!
Comment: See also: [Degree Sequence of the complement graph](http://math.stackexchange.com/questions/1331192/degree-sequence-of-the-complement-graph)
Answer: Hint: Consider the complement of the graph.
Comment: Can you expalain it a little more? It is $n - d_1 -1$ the degree of a vertex in the complement graph.
Comment: @passenger: I am not sure what more I can explain without giving it all away. As it is, the above can be considered a full answer, instead of just a hint. Why don't you try out some graphs, write their degree sequences, and then do the same for the complements?
Comment: o.k I understand it , i did some graphs. It is clear now. $< n-d_1 -1 , \cdots ,n-d_n -1 >$ is the graphic sequence of the complement of $G$. Thank you for your time!
Comment: @passenger: You are welcome!


Why flag declined for the post?

Question: Today i flagged one post as Too Broad.
Change address of the customer confirming shipment
I flagged this. Because, this post not include the magento version. So that, i flagged this. Please check once.
Answer: This is why: https://magento.stackexchange.com/review/close/136147
Comment: Is it possible to find reviews for specific questions/answer? (https://magento.stackexchange.com/questions/101944/magento-2-code-migration-installation-using-git/120274#120274 ... its not an answer and was posted as question later)
Comment: @sv3n Maybe look through the review history...I don't know.

Why flag declined for the post?


Dealing with compressed JSON string from external API

Question: I'm trying to call the Stack Exchange API but it sends compressed JSON strings and I can't uncompress it.
$request = drupal_http_request('https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&site=stackoverflow');
$uncompressed = gzinflate($request->data);
$json_response = drupal_json_decode($uncompressed);

I'm getting an error like this: Warning: gzinflate(): data error in adventure_profile_profile() (line 104 of /home/justine/www/adventure/sites/all/modules/custom/adventure_profile.module). (where line 104 is $uncompressed = gzinflate($request->data);).
Am I doing something wrong?
Answer: Ok, I'm sorry I just figure it out. I wasn't looking at the $request->headers to see what method to uncompress I have to use. Here is the solution:
$request = drupal_http_request('https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&site=stackoverflow');

if (isset($request->headers['content-encoding'])) {
  if ($request->headers['content-encoding'] == 'gzip') {
    $request->data = gzinflate(substr($request->data, 10));
  }
  elseif ($request->headers['content-encoding'] == 'deflate') {
    $request->data = gzinflate($request->data);
  }
}

$json_response = drupal_json_decode($request->data);


Agora sdk react-js - no audio or video is sent (black screen from remote users) - local video and audio is okay

Question: I am experiencing a very strange scenario when I am replicating the example here:
SDK quickstart - Video call
Here is my final code:
1- AgoraTest.js

import react, { useState } from "react";
import { AgoraRTCProvider, useRTCClient } from "agora-rtc-react";
import AgoraRTC from "agora-rtc-sdk-ng";
import { Button } from "@mui/material";
import { Videos } from "./Videos";

 function AgoraTest(){
    const client = useRTCClient(AgoraRTC.createClient({ codec: "vp8", mode: "rtc" }));
    AgoraRTC.enableLogUpload();
// Set the log output level as INFO
    AgoraRTC.setLogLevel(1);
    const [channelName, setChannelName] = useState("test");
    const [AppID, setAppID] = useState("a71394619e2043f8ae404cd89843e908");
    const [token, setToken] = useState("007eJxTYJBhuSpQeXq6VLpOXnm0rco5h/4zifPLYr6xvijT6uYStFRgSDQ3NLY0MTO0TDUyMDFOs0hMNTEwSU6xsLQwMU61NLB4q/4otSGQkaFVQIKJkQECQXwWhpLU4hIGBgA6bBuS");
    const [inCall, setInCall] = useState(false);

    const toggleInCall = () => {
        setInCall(!inCall);
    };

    return (

Agora React Videocall

      {!inCall ?
        <Button onClick={toggleInCall}>Join</Button>
       : (
        <AgoraRTCProvider client={client}>
          <Videos channelName={channelName} AppID={AppID} token={token} />

<Button onClick={toggleInCall}>End Call</Button>
        </AgoraRTCProvider>
      )}

    )
}

export default AgoraTest;

2- Videos

import { VideoCameraFront } from "@mui/icons-material";
import { IconButton } from "@mui/material";
import { useJoin, useLocalCameraTrack, useLocalMicrophoneTrack, usePublish, useRemoteAudioTracks, useRemoteUsers, RemoteUser, LocalVideoTrack, useRemoteVideoTracks } from "agora-rtc-react";
import { } from "reactstrap";

export function Videos({ channelName, AppID, token}) {
    const { isLoading: isLoadingMic, localMicrophoneTrack } = useLocalMicrophoneTrack();
    const { isLoading: isLoadingCam, localCameraTrack } = useLocalCameraTrack();

    const deviceLoading = isLoadingMic || isLoadingCam;

    const joinData =useJoin({
      appid: AppID,
      channel: channelName,
      token: token === "" ? null : token,
  });

    const publishData = usePublish([localMicrophoneTrack, localCameraTrack],!deviceLoading && joinData.isSuccess);

    const remoteUsers = useRemoteUsers();

    const { audioTracks } = useRemoteAudioTracks(remoteUsers);
    audioTracks.map((track) => track.play());

    const toggleEnabled = () => {
      localCameraTrack.setEnabled(!localCameraTrack.enabled);
    }

    if (deviceLoading) {
      return
Loading devices...
;
  }

    if (publishData.isLoading) {
      return
Getting published...
;
    }

    if (joinData.isLoading) {
      return
Getting connected...
;
    }

    return (

Video Call {joinData.data}

            <LocalVideoTrack track={localCameraTrack} play={true}/>

            {remoteUsers.map((user) => (

              {user.uid}

                {user.hasVideo ? <RemoteUser user={user} playVideo={true} playAudio={true} /> :
No Video
}

            ))}
            <IconButton onClick={toggleEnabled}>{<VideoCameraFront/>}</IconButton>

        );
}

When I plug this in my code, here is the result:
As you see, the new user (my other laptop) is connected but no video is sent. The same is happening in the other laptop (the local camera works but nothing is sent).
When I look at the agora analytics, we can make the same conclusion:
It is certainly not the problem with the network. I tried the AgoraUI and all works pretty fine.

I am quite stuck with this. Does anyone have any idea what I missed?
Answer: I tried again with the clone and it worked for me as well.
I changed the version of the agora-rtc-react to "2.0.0-beta.0" and now everything works in my code as well.
I think I know what is the issue with recent versions (2.1.0) of agora-rtc-react:
When I use (2.1.0), there are inconsistencies in type conversion.
Both localCameraTrack and localMicrophoneTrack are cast to types from package "agora-rtc-react" rather than from "agora-rtc-sdk-ng".


Error in python string

Question: when I type this code in python it shows this error
>>> 'Ahmed' + \t 'Ashraf '

SyntaxError: unexpected character after line continuation character

what does this error mean ??
Comment: That means there was an unexpected character. `'Ahmed' + '\t' + 'Ashraf'` should work.
Comment: This question was caused by a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers.
Answer: The \t escape sequence has to be inside a string literal, so the correct syntax is:
'Ahmed' + '\t' + 'Ashraf '

Outside a string literal, \ is used to indicate that you're continuing a statement on the next line, so it's called the line continuation character. It should only be followed by a newline, e.g.
>>> var1 = 'Ahmed' + \
'Ashraf'

If it's followed by some other character, such as t in your example, you get an error.
Comment: Rather than `'Ahmed' + '\t' + 'Ashraf '` you may as well directly go `'Ahmed\tAshraf '`
Comment: @Julien Of course, but then I wouldn't demonstrate how to concatenate strings. In his real application there's likely to be variables involved.
Answer: You can also do it with the format string.
>>> '%s\t%s' %('Ahmed','Ashraf')
'Ahmed\tAshraf'
>>>

Error in python string


RoR duplication fields

Question: When an incorrect mandatory fields, the page reloads and you receive an incorrect entry fields and all fields in the form company_form duplicated.
User model(user.rb):
class User < ActiveRecord::Base
  ....
  has_many :companies, :autosave => true
  accepts_nested_attributes_for :companies
  has_and_belongs_to_many :roles
  def role?(role_name)
    return !!self.roles.find_by_name(role_name)
  end
  def with_company
    self.companies.build
    self
  end
end

Company model:
class Company < ActiveRecord::Base
  ...
  belongs_to :user
  ...
end

views/devise/registration/new.html.haml:
= form_for(resource.with_company, :as => resource_name, :url => registration_path(resource_name), :html => { :class => 'form-horizontal'}) do |f|
...
  = f.fields_for :companies do |company_form|
  ...
...

Comment: And the problem is? And the rest of the code is?
Comment: problem probably in with_company. When the page is reloaded created another company, and it is necessary to record only one company
Answer: The problem is that your with_company method uses build to create the new Company object. build will automatically create the new object and save it to the database. So every time that form gets rendered, you'll add another Company to that User. Just hit reload on the page a few times and you should see what I mean.
I think the fix will be to use create instead of build in that method; this creates a new object but doesn't save it to the database.
More likely, though, you should be doing this in the controller that renders the view, rather than in the view itself. Devise doesn't always make this straightforward, but you should be able to create a new controller that inherits from the Devise controller and adds what you need. I do something similar in my current project here.
Comment: create not working, error "You cannot call create unless the parent is saved".
Comment: not terrible, I have found the solution to my problem, thanks anyway
Answer: worked! change def with_company on
  def with_company
    if self.companies.empty?
      self.companies.build
    end
    self
  end

RoR duplication fields


Counting a Waltz

Question: I just started my first semester of beginning piano. I seem to have trouble counting in 3/4 time. I know it will come with practice, but does anyone have any tips for practicing non-standard time?
Comment: Of course, once you have mastered 3/4 for years and become a professional player, there will be the slight complication that in an actual waltz intended for dancing, the beats are of subtly unequal length: IIRC, the second beat is longest with the third beat coming slightly late. That is more pronounced with the Viennese Waltz as compared to the Slow or English Waltz and corresponds somewhat with the distribution of impetus for the dance movements.
Answer: I wouldn't consider 3/4 to be "non standard".
My advice would be to find recordings of pieces in 3/4 and count along to them.
The "oom-pah-pah" pattern is a very common way to arrange a 3/4 backing. I suppose the most direct example is "Oom-pah-pah" from the soundtrack to the musical "Oliver!" - so listen to that first. In the chorus, they actually sing "Oom-pah-pah". "Oom" is beat one; "pah-pah" is beats two and three. In the verses you can practice without that crutch.
Start by spotting the downbeats, the "oom". Most of the time they are pretty obvious - a bass instrument or a drum will be marking them. Call out the downbeats by saying "one".
Once you can do that, fill in beats two and three. Often these will be emphasised by a higher pitched instrument like violins or the higher strings of a guitar. Call out these by saying "two three". And you've got it!
There are plenty more examples in pop/rock. Try "Norwegian Wood" or "It's A Man's Man's Man's World", or any one of thousands of country ballads. In classical music, of course there are lots of waltzes, minuets, etc.
Of course, not every piece in 3/4 uses an "oom-pah-pah" arrangement but once you can count 3/4 against an oom-pah-pah backing, you should be comfortable enough with a three-beat bar to apply it to other pieces.
Once you can reliably count time on recorded music, it should be quite straightforward applying that to music you are playing yourself.
It may also help to use an electronic metronome -- the kind where you can set the time signature to get a different click on the downbeat. You can buy them as dedicated hardware, or use phone/tablet/computer apps.
Comment: Let's see.  The Beautiful Blue Danube and The Tennessee Waltz are two other well-known examples of 3/4 time.  As Slim says, the best way to get the feel of it is to find songs you know already that are examples.

Counting a Waltz


What exactly is block harmony?

Question: I heard of block harmony when I was experimenting with the dictionary in my Yamaha PSR 192 Database, and later when I went on Wikipedia.
Both of these things told me that blocks are harmonies made up of four notes.
The thing I have trouble understanding is why a C major tetrad isn't called a block. It has four notes, C, E, G, and another C. Is it because even though there are two different C's in octaves, they are still considered as one? Or, is it something else entirely?
In a block, if I played C, it might harmonise below. C4, A3, G3, and E3, which makes it sound like a C major add six. It could also harmonise above. C4, E4, G4, and A4.
Answer: You'll find lots of definitions of 'Block Harmony'!  It's not a precise term with One True Definition.  It certainly doesn't have to be 4-note.   And your C-E-G-C chord could certainly be considered a 'block'.
Here's some sample definitions.  None of them are complete or definitive.  None of them are likely to be obeyed strictly in real-life music.
It's close position voicing.  All the notes are played at the same time and all move in the same direction (or are static) when changing chord.
It's 'George Shearing' or 'Glenn Miller' voicing where the top and bottom voices double the melody an octave apart, the rest of the harmony follows the same rhythms and fits in-between.   (But it doesn't HAVE to double the melody in that way, that's just one example of 'Block Harmony'.)
It's bad 'easy keyboard' arrangements where the RH plays the tune, the LH plays close position chords in the tenor range (to be fair, this may just be intended to trigger the auto-accompaniment feature.
It's the opposite of counterpoint!  I think I'll go with that one :-)
Comment: 'All move in the same direction when changing chord'. I'd have thought some notes would stay where they are, with common notes.

What exactly is block harmony?


How can I tell if Mercurial is Installed?

Question: I am using another developer's Ubuntu box and trying to tell if Mercurial is installed and working.
As @stew pointed out, I did the 'dpkg -l mercurial' command and got this:
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Cfg-files/Unpacked/Failed-cfg/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                  Version               Description
+++-=====================-=====================-==========================================================
ii  mercurial             1.8-0ppa1~lucid1      scalable distributed version control system
agenadinik@slabrams-desktop:/usr/bin$ dpkg -l Mercurial

While it says the installation is recognized, it also gives some cryptic warning-like messages above.  It looks like it might be a bad installation.  Could anyone help me decipher those messages?
Thanks! :)
Answer: you could see if the mercurial package were installed by checking if dpkg -l mercurial spits out a line with 'i' in the second column.  you could also try running hg help and see if you get a list of mercurial commands.
Comment: Thanks - I have some funky output to that command which I pasted as an answer because it allowed me to format the funky output to be more readable.  Are you able to interpret those messages?
Answer: which hg returns 0 if the hg binary is found. In addition, if you don't need to do this in an automated script, it will print whether or not the binary was found into stdout.
Edit: Obviously this doesn't tell whether or not the package is properly installed, for which you should use the dpkg command – which you did.


How can i delete destination from activemq

Question: How can i delete a queue from activemq using java.Can any one provide any samples regarding this.I have googled it but i didn't find the correct solution.
Answer: This SO Thread, and particulary BOdays answer:
ActiveMQ delete queue from java
Points to this blog post by the same author:
http://www.consulting-notes.com/2010/08/monitoring-and-managing-activemq-with.html
which shows how to this using JMX/Java.
Enjoy


For which numbers of nodes can a connected graph be arranged in such a way that each edge has 2 intersections?

Question: Assume you have a set of $n$ points which are part of a connected graph. Every node should have degree $2$, i.e.
every point is connected to two other points and therefore the graph also has $n$ edges (edges are only allowed to be straight line segments).
I'd like to know for which $n$ you can arange the points in such a way that every edge has an even number of intersections with other edges (nodes are defined never to be exactly on an edge; 0 intersections don't count).
And a more special case would be for which $n$ each edge can have exactly 2 (or any other natural number of) intersections.
For $n=3$ and $n=4$ it is obviously not possible, as for $3$ there aren't any intersections at all, and for $4$ there are at least two edges without any intersection.
For $n=5$ it is rather easy to find a case where each edge has $2$ intersections by simply connecting them in the shape of a star.
I don't think it's possible for $n=6$ but I'm struggling to find a method to proof it.
For $n=7$ you can also make a star-shape to get $4$ intersections on each edge (I haven't found an example for $2$), and for $n=8$ I have once again found an example with $2$ intersections each.

I have not tried anything for $n>8$ yet nor have I been able to work out any steps for a potential proof.
Any help to find a proof would be greatly appreciated! (You don't have to write a finished proof as an answer, I'd also be happy if you can suggest some techniques I could use)
Comment: Look up star polygons, specifically the $\{n, 2 \}$ type (naming might be different).
Comment: Oh, that makes so much sense, how did I not see those myself. Thanks!
Comment: @299792458 Interesting question! please clarify that an edge in the question means a line segment on a fixed Euclidean plane. If an edge can be a curve, it is easy to construct various examples even for $n=3$.
Comment: @299792458 Can you include an image for the case of $n=8$ where each edge has 2
 intersections?  That should be a nontrivial example.
Comment: @Apass.Jack I included the non-trivial example I found. Do you know for which other n there are non-trivial solutions?
Answer: If we have such a drawing for an $a$-point cycle and a $b$-point cycle, then we can combine them to get a drawing for an $(a+b)$-point cycle. For example, here is a drawing where we join the $7$-point construction to the $9$-point construction:

In general, to do this, pick a point on each cycle that's not "in the middle": it can be pulled out to be an extreme in one direction. Split each cycle apart at that point into two points, so that it becomes a path. Then glue those paths at their ends. (This works very generally, whenever we have some restriction on the number of intersections along each edge, since we do not gain or lose any such intersections.)
When we want exactly two intersections per edge, we have a construction for an $n$-point cycle where $n = 5, 7, 9, 11, 13, \dots$ by going around a circle two steps at a time, as seen in each color above. By combining the $5$-point cycle with the $k$-point cycle for $k=5, 7, 9, \dots$, we get an $n$-point cycle for $n=10, 12, 14, 16, \dots$. We also have a construction (given in the question) for an $8$-point cycle.
This gives us all values of $n$ except $n \le 4$ and $n=6$, and the question shows how to rule out $n \le 4$, leaving only the case of $n=6$ open.
Comment: Thanks a lot! Just to let you know, I'm not yet marking this as answered as the case for $n=6$ is still open. I'm also wondering whether there are non-trivial constructions for all odd $n$...
Comment: What do you consider "non-trivial"; just the construction that's not the circular one? Well, for all odd $n \ge 13$, we can split $n$ as $(n-8)+8$ and get a different construction that way. For $n=5$, we are limited to only one possible construction, because each edge must cross exactly the two edges it doesn't share an endpoint with. For $n=7, 9, 11$ it's possible that we can do something unusual. (Finally, I don't have a proof yet, but strongly expect that $n=6$ is impossible.)
Comment: Yes, that's what I mean with non-trivial: a way of arranging the points such that they don't form a star-polygon. I know that you can get all $n \ge 13$ by combining smaller star-polygons the way you described. But what are the "non-trivial" ones for $n = 7, 9, 11$? By combining two star-polygons you can't get less than 10 endpoints and if $n=6$ is not possible, $n=11$ can also not be constructed in such a way
Comment: I don't have any nontrivial examples for $n=7,9,11$, I just can't rule them out.
Comment: Oh, I misunderstood you. Do you have any idea on how you could find a proof that it's impossible with $n=6,7,9,11$?


How do I run only a subset of comparisons in a t.test using R?

Question: I am using R to do some statistics:
I have generated a data.frame from raw data. The data includes a numeric variable (fold_change) and two factor variables (dis_status which includes RF and con, as well as glycan which includes 100 different glycans)
and it looks something like below with hundreds more glycans
 dis_status                      glycan fold_change
1           RF              Sulpho.Lewis.a  4.83433185
2           RF              Sulpho.Lewis.a  3.88519084
3          con              Sulpho.Lewis.a  0.94730194
4          con              Sulpho.Lewis.a  1.91278688
167         RF    P1.antigen.Trisaccharide  4.07173876
168         RF    P1.antigen.Trisaccharide  5.70383491
169        con    P1.antigen.Trisaccharide  1.34631723

> glimpse(stats_df)
Observations: 16,600
Variables: 3
$ dis_status  <fct> RF, RF, con, con, con, con, con, RF, RF, con, con, RF, con, con, RF, RF, RF, con, RF, con, RF, RF, RF, RF, RF, RF, con, RF, RF, con, con, con, RF, con, RF, RF,…
$ glycan      <fct> Sulpho.Lewis.a, Sulpho.Lewis.a, Sulpho.Lewis.a, Sulpho.Lewis.a, Sulpho.Lewis.a, Sulpho.Lewis.a, Sulpho.Lewis.a, Sulpho.Lewis.a, Sulpho.Lewis.a, Sulpho.Lewis.a,…
$ fold_change <dbl> 4.83433185, 3.88519084, 0.94730194, 1.91278688, 6.94509886, 2.80368849, 0.78262431, 2.74972572, 4.37691596, 0.85835252, 1.25431865, 1.14603706, -1.82021891, 0.…

I run a t.test on the data:
ad_nonpaired <- pairwise.t.test(stats_df$fold_change,  stats_df$dis_status:stats_df$glycan,
                               paired = F,
                               pool.sd = F,
                               p.adj = "none")

I will correct for multiple comparisons next but the issue I am having is this carries out t.tests between every possible combination of dis_status and glycan.
I am only interested in the "RF" vs "con" for each individual glycan. So with the two glycans above, I only really want "Sulpho.Lewis.a" from "RF" compared to "Sulpho.Lewis.a" from "con" NOT any comparison between "P1.antigen.Trisaccharide" to "Sulpho.Lewis.a" but can not figure out how to specify this in the test?
R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_NZ.UTF-8/en_NZ.UTF-8/en_NZ.UTF-8/C/en_NZ.UTF-8/en_NZ.UTF-8

attached base packages:
[1] parallel  stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] knitr_1.25          broom_0.5.2         ggrepel_0.8.1       readxl_1.3.1        forcats_0.4.0       stringr_1.4.0       dplyr_0.8.3         purrr_0.3.3
 [9] readr_1.3.1         tidyr_1.0.0         tibble_2.1.3        ggplot2_3.2.1       tidyverse_1.2.1     limma_3.38.3        hexbin_1.27.3       vsn_3.50.0
[17] Biobase_2.42.0      BiocGenerics_0.28.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.2            lubridate_1.7.4       lattice_0.20-38       gtools_3.8.1          rprojroot_1.3-2       assertthat_0.2.1      zeallot_0.1.0         digest_0.6.22
 [9] utf8_1.1.4            plyr_1.8.4            R6_2.4.0              cellranger_1.1.0      backports_1.1.5       evaluate_0.14         highr_0.8             httr_1.4.1
[17] pillar_1.4.2          gplots_22.214.171.124        zlibbioc_1.28.0       rlang_0.4.1           lazyeval_0.2.2        curl_4.2              rstudioapi_0.10       gdata_2.18.0
[25] preprocessCore_1.44.0 desc_1.2.0            labeling_0.3          splines_3.5.2         munsell_0.5.0         xfun_0.10             compiler_3.5.2        modelr_0.1.5
[33] pkgconfig_2.0.3       tidyselect_0.2.5      fansi_0.4.0           crayon_1.3.4          withr_2.1.2           bitops_1.0-6          grid_3.5.2            nlme_3.1-141
[41] jsonlite_1.6          gtable_0.3.0          lifecycle_0.1.0       affy_1.60.0           magrittr_1.5          scales_1.0.0          KernSmooth_2.23-16    cli_1.1.0
[49] stringi_1.4.3         affyio_1.52.0         testthat_2.2.1        xml2_1.2.2            ellipsis_0.3.0        generics_0.0.2        vctrs_0.2.0           tools_3.5.2
[57] glue_1.3.1            hms_0.5.2             pkgload_1.0.2         yaml_2.2.0            colorspace_1.4-1      BiocManager_1.30.9    caTools_220.127.116.11      rvest_0.3.4
[65] haven_2.1.1

Answer: you could just subset the data and then run the t.test on the resulting data frame, e.g. see the first answers here
https://stackoverflow.com/questions/3445590/extract-a-subset-of-a-dataframe-based-on-a-condition-involving-a-field
https://stackoverflow.com/questions/4935479/how-to-combine-multiple-conditions-to-subset-a-data-frame-using-or
Comment: Yes, although this approach relies on the `pool.sd` option being `FALSE`. Otherwise sunsetting the data would change the variance estimate being used.  (Assuming I understand how the function works).


Calculate $\int_0^\infty\frac{\sin^2t}{t^2}dt$ using Fourier transform

Question: Calculate $\int_0^\infty\frac{\sin^2t}{t^2}dt$ using Fourier transform. Unfortunately, we have not learned Plancherel's Theorem.
The only other hint that was given is $$\mathcal{F}[f(t)]=\sqrt{\frac{2}{\pi}}\frac{1-\cos(\lambda\pi)}{\lambda^2},$$ where $$f(t)=\begin{cases}t+\pi&t\in[-\pi,0]\\\pi-t&t\in(0,\pi]\end{cases},$$ and $f(t)=0$ otherwise.
I know that $$\int_0^\infty\frac{\sin^2t}{t^2}dt=\frac{1}{2}\int_{-\infty}^{\infty}\frac{\sin^2t}{t^2}dt,$$ and I know the answer is supposed to be $\pi/2$, but I am unsure of how to get started.
Comment: Hint: Recall that $1-\cos(\lambda pi)=2\sin^2\frac{\lambda\pi}{2}$. Also the inverse Fourier transform is given by $f(t)=\int_\mathbb{R}e^{2\pi i t\lambda}\mathcal{F}[f](\lambda)d\lambda$. Thus what can you say about $f(0)$?
Comment: you didn't learn the Plancherel theorem but your learnt that $\mathcal{F}[f \ast g] = \mathcal{F}[f] \mathcal{F}[g]$ ? in that case $g(t) = \overline{f(t)}$ and $2 \pi h(0) = \int_{-\infty}^\infty \mathcal{F}^{-1}_{[h]}(\omega) e^{i \omega t} d\omega$ gives the Plancherel theorem. alternatively, tell us what you learnt :-)
Answer: I solved it, thanks to the helpful comment from Frank Lu.
$$I=\int_0^\infty\frac{\sin^2t}{t^2}dt=\frac{1}{2}\int_{-\infty}^{\infty}\frac{\sin^2t}{t^2}dt$$
$$f(t)=\begin{cases}t+\pi&t\in[-\pi,0]\\\pi-t&t\in(0,\pi]\\0&\text{otherwise}\end{cases}$$
\begin{equation*}
    \begin{aligned}
        \mathcal{F}^{-1}\bigg[\sqrt{\frac{2}{\pi}}\frac{(1-\cos\lambda\pi)}{\lambda^2}\bigg] & =
        \mathcal{F}^{-1}\bigg[\sqrt{\frac{2}{\pi}}\frac{(2\sin^2(\lambda\pi/2))}{\lambda^2}\bigg] \\
        \frac{\pi}{2}\cdot\sqrt{\frac{2}{\pi}}\frac{(2\sin^2\lambda)}{\lambda^2} & = \mathcal{F}\bigg[f(\frac{2}{\pi}t)\bigg] \\
        & = \frac{\sqrt{2\pi}\sin^2\lambda}{\lambda^2} \\
        \Rightarrow \mathcal{F}^{-1}[f(2t/\pi)] & = \int_{-\infty}^\infty\frac{\sin^2\lambda}{\lambda^2}e^{i\lambda t}d\lambda
    \end{aligned}
\end{equation*}
At $t=0$, we have
$$\int_{-\infty}^\infty\frac{\sin^2\lambda}{\lambda^2}d\lambda=\pi\Rightarrow\int_0^\infty\frac{\sin^2t}{t^2}dt=\frac{\pi}{2}$$