RegEx for Positive Lookahead - password rules (contains required numbers and characters)

Question: I'd like to understand the below regex and tried testing it in regex101
^(?=.*[a-zA-Z])(?=.*[0-9]).{4,}$

Comment: there is an explanation section in regex101
Answer: That regex doesn't mean much and can be shortened to:
.{4,}$ // match at least 4 characters (or more) before ending

The reason is that lookaheads define where your matching group pattern ends. But you are placing the lookahead at the start of the input string, catching "" (nothing) in front of all the lookahead patterns. So all the lookaheads are redundant.
So:

^ pattern must start at the beginning of input
(?=.*[a-zA-Z]) find lookahead of any number of consecutive alphabets (found "TestPassword", not to be included in matching group)
(?=.*[0-9]) find lookahead of any number of digits (found "1", not to be included in matching group)
Given above, the only match is "" at the beginning of "TestPassword1". Now we continue the matching...
.{4,}$ now match anything of at least 4 characters situated right at the end of
  input (found "TestPassword1", which is returned as matching group)

See below code for proof and explanation:

let regex = /^(?=.*[a-zA-Z])(?=.*[0-9]).{4,}$/;
[match] = "TestPassword1".match(regex);
console.log(match); //TestPassword1

// just test for lookaheads result in matching an empty string at the start of input (before "T")
regex = /^(?=.*[a-zA-Z])(?=.*[0-9])/;
match = "TestPassword1".match(regex);
console.log(match); //[""]

// we're now testing for at least 4 characters of anything just before the end of input
regex = /.{4,}$/;
[match] = "TestPassword1".match(regex);
console.log(match); //TestPassword1
Answer: Explained
 ^                        # BOS
 (?= .* [a-zA-Z] )        # Lookahead, must be a letter
 (?= .* [0-9] )           # Lookahead, must be a number
 .{4,}                    # Any 4 or more characters
 $                        # EOS

Comment: @greenb - Assertions and other non-consuming constructs, don't actually exist at character positions. They exist _between_ characters. It is a subject I've written about here at SO, but I just can't find the link to it. It's too bad, maybe you could find it, it would help you to forever understand these ghosts.
Comment: I knew about result. but i didn't understand rules of `positive lookahead`. `regex1(?=regex2)` that is first search `regex1` and if exists `regex2`. but `^(?=.*[a-zA-Z])(?=.*[0-9]).{4,}$` ...
Comment: No worries, we've all been there and regex is not easy and can't be grasped in one day. Just take baby steps, one step at a time and you'll get better and better. You can start with resources on the web like https://regexone.com.
Comment: @sln Thank you very much. I understood from your comment :)


Erro do retorno da expressão do tipo UITableViewCell no swift

Question: class OcorrenciaVinculadaCell: UITableViewCell{

    @IBOutlet weak var tipoOcorrencia: UITextField!
    @IBOutlet weak var descricao: UITextField!

}

class OcorrenciaVinculadasViewController: UITableViewController {

    var id:Int = 0;
    var schedulingId = 0;

    var ocorrencias:Array<Ocorrencia> = [];

    override func viewDidLoad() {
        self.schedulingId = Util.schedullingId;

        OcorrenciaHttp.GetOcorrencia(
            success: {
                (ocorrencias) in
                self.ocorrencias = ocorrencias;
                self.tableView.reloadData();
            }
            ,fail: { (error) in
                print("Failure: \(error.localizedDescription)");
            }
        );
    }

    @IBAction func createOcorrenciaButton(_ sender: Any) {
        Util.schedullingId = schedulingId;
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ocorrencias.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt
    indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath) as! OcorrenciaViewCell

        let ocorrencia = ocorrencias[indexPath.row]

        cell.tipoOcorrencia.text = Util.GetText(text:ocorrencia.tipoOcorrencia?.Name) as? String;
        cell.descricao.text = Util.GetText(text: ocorrencia.descricao) as? String;

        return cell
    }

No retorno fica dando o erro:

Cannot convert return expression of type 'OcorrenciaViewCell' to return type 'UITableViewCell'

Comment: isso está ocorrendo porque a função `tableView` espera que seja retornado um objeto do tipo `UITableViewCell` porém você está retornando `cell` que é um objeto do tipo `OcorrenciaViewCell`: `let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath) as! OcorrenciaViewCell`. Você teria que converter `cell` em `UITableViewCell` só que na sua pergunta não mostra a declaração de `OcorrenciaViewCell` para saber se é possível ou se teria que criar um método de conversão.
Answer: no  override func viewDidLoad() { ...
adicione:
self.tableview.register(OcorrenciaViewCell.self, forCellReuseIdentifier:"itemCell")
Confira na célula se voce colocou o identifier como "itemCell"
aproveitando, sempre chame o super em
override func viewDidLoad() {
   super.viewDidLoad()


What are the odds for winning this drinking game?

Question: Out of pure boredom during the corona period back in 2020 I 'invented' a drinking game which seemed to have a fair outcome, but I am not sure. We were sitting on the couch and after a lot of beer, and some games of Perudo (which is played with a lot of dice) I came up with the following game.

There are 24 dice on the table.
One person throws all the dice.
Every '1' and '6' that is rolled is removed from the table. (So if you roll 5 times a '6' and 4 times a '1', your next throw contains 15 dice)
Repeat this process for a total of 8 times.
If you are able to remove all the dice in 8 throws or less, you win the game and the rest of the room has to drink a X amount of sips.

That night we a had a lot of fun playing this very simple and rather stupid drinking game, and it seemed to have a fair outcome: the chances for winning this game felt like a 50/50. The next day I woke up with a hangover and I was curious about the actual probability of winning this game. I calculated the expected number dice you would be left with after 8 throws:

The number in the third row is calculated as follows; 24 - (1/3*24) etc. So, after 8 throws the expected number of dice you are left with is .936. I am probably wrong but; On the one hand, as this is less than 1, you might argue that the probability of winning this game is therefore greater than fifty percent. On the other hand you might argue that it is more than .5 dice and therefore it could be that the probability of winning this game is smaller than fifty percent.
What is the probability of winning this game? There is probably one 'easy' answer which is simulating the game for a million times. However, I am not familiar with coding, is there anyone who could help me? Furthermore, I am very curious how you could interpret this .936. Is there any way to express this as a percentage of winning the game? Or is there any calculation that gives you the percentage of winning this game?
I am very curious! If something is not clear let me know.
Thanks in advance,
Pim
Comment: Just a note about being precise about what you want: please be aware that *odds* and *probability* are different things. https://en.wikipedia.org/wiki/Odds ... if you want probability, don't say odds.
Comment: The problem is equivalent to rolling each dice 8 times (even when it had a 1 or 6 in the meantime) and see whether any had zero times a 1 or 6 (that's a dice that never got removed in your version).
Comment: @Glen_b Thanks a lot for your clear reply! I understand it now :)
Comment: @SextusEmpiricus Oops, it was a typo I guess... I've edited it :)
Answer: The chance a single fair die doesn't show a $1$ or a $6$ in eight rolls is $(\frac46)^8$ $\approx$ $0.039$.
The chance that all 24 dice do show a $1$ or a $6$ within 8 rolls is therefore $[1-(\frac46)^8]^{^{24}}$ $\approx$ $0.3847$. That is, the probability of a win is just a little below 40%.
[In case you did want odds, the odds in favour of a win are therefore $0.3847/0.6153 \approx 0.625$ or about $5:8$.]
Comment: Very clear! Thanks a lot :)


32bit SQLServer with AWE NOT enabled. Buffer Cache Hit Ratio High, Disk Read Queue VERY HIGH, WHY?

Question: We have a "SQLServer 2005 SP3 32bit Enterprise Edition" running on a 32 bit Windows 2003 32bit Enterprise Edition 12GB RAM with AWE enabled using RAID5(5 pysical disks).
We tuned AWE to enabled and restart sqlserver this afternoon after work, hope the performance will be better than old time.
But there is something that we are very confused.
On working days, SQLServer has a very bad performance. When we are looking for reasons, we check Windows Performance counter.
<code>Avg. Disk Read Queue Lenght > 140
Avg. Disk Write Queue Length < 1
SQL Server Buffer Cache Hit Ratio > 96%
%Processor Time < 30%
SQL Server Total Server Memory < 1.8G
</code>
Obviously, without AWE enabled, SQL Server can use only less than 2G memory. My Question is:

why "SQL Server Total server Memory" is less than 2G?I think SQL Server will use all 2G process address space. Does this counter count anything out?
we known that sql server is sufferring lack of memory, but why "buffer hit ratio" is as high as 96?

Any advice is welcomed!
Answer: To take advantage of the extra RAM you need to enable PAE as well as AWE.
http://support.microsoft.com/?kbid=283037
Additionally, you should allow the account that is running your SQL services the "lock pages in memory" option.
http://msdn.microsoft.com/en-us/library/ms190730.aspx
The Buffer Cache Hit Ratio value isn't that far out of bounds. You generally want this number > 95%. However, this counter is hard to read as it depends a lot on how many different things are going on in how many DB's and how much I/O is queued up (all at once). Jonathan Kehayias over at Simple-Talk discusses this topic very well.
Great SQL Server Debates: Buffer Cache Hit Ratio by Jonathan Kehayias
http://www.simple-talk.com/sql/database-administration/great-sql-server-debates-buffer-cache-hit-ratio/
Answer: Maybe I'm missing something but this seems to be an issue of disk contention.  What is on the raid 5 array?  Temp, user DB's, transaction logs?
Comment: thanks.It's a server used for developers, So, TempDB, UserDB, Log are all on the same raid. And We know that there is a disk issue , or more persisely, memory issue. My question is , why performance counters are "not in the right position"?


Tkinter Button Callback Lambda Unexpected Result

Question: I want to create multiple rows of tkinter widgets and I thought storing them in a dictionary would be a clean way to do this. I'm having trouble getting the callbacks for the buttons to work correctly though. With the code as is, the value passed to the button callback is always E and I can't see why that is. How do I pass the correct key to the callback please - i.e. A for the first row, B for the second etc?
import tkinter as tk

NUM_ROWS = 5
BOLD_FONT = ("calbri", 16, "bold")
NORMAL_FONT = ("calbri", 16, "normal")

def submit():
    print("you win")

def clear(key):
    print(key)
    # widgets[key]["factor_field"].delete(0,"end")
    # widgets[key]["factor_field"].insert(0, key)

data = {}
widgets = {}

root = tk.Tk()

# Build widgets
for i in range(NUM_ROWS):
    key = chr(i + 65)
    this_row = widgets[key] = {}
    this_row["label"] = tk.Label(root, text=key, font=BOLD_FONT)
    this_row["label"].grid(row=i, column=0, padx=5, pady=10)
    this_row["factor_field"] = tk.Entry(root, width=60, font=NORMAL_FONT)
    this_row["factor_field"] .grid(row=i, column=1, padx=5, pady=10)
    this_row["target_node_field"] = tk.Entry(root, width=5, font=NORMAL_FONT)
    this_row["target_node_field"].grid(row=i, column=2, padx=5, pady=10)
    this_row["clear_button"] = tk.Button(root, text="Clear", command=lambda: clear(
        key), font=BOLD_FONT).grid(row=i, column=3, padx=5, pady=10)

submit_button = tk.Button(root, text="Submit", command=submit,
                          font=BOLD_FONT).grid(row=NUM_ROWS + 1, column=0, padx=5, pady=10)

print(widgets)
root.mainloop()

Comment: Use `command=lambda key=key: clear(key)` instead of command=lambda: clear(key) .
Answer: Use this:
this_row["clear_button"] = tk.Button(root, text="Clear",
                                     command=lambda x=key: clear(x),
                                     font=BOLD_FONT)
this_row["clear_button"].grid(row=i, column=3, padx=5, pady=10)

In your current code, the value for the key variable is fixed at E after the for loop has completed. As a result, your existing lambda function will always call clear('E').


render :partial returning an array when defined in ApplicationController but string when in ApplicationHelper

Question: This method:
  def admin_buttons
    render :partial => 'portable/admin/admin_buttons'
  end

returns this (not html_safe) when defined in ApplicationControler and made a helper with helper_method:
["my partial's output "]
But it returns the expected string normally when defined in ApplicationHelper.
I don't understand. This is new behavior as far as I know in rails 3.1
Comment: Arbitrary controller methods shouldn't be returning rendered views.
Answer: Simply put, don't call the controller's render in helpers.  It just does not work that way
render in the controller and render in a helper can't be used interchangeably.  This isn't new in Rails 3.1.
When you call render in the controller it eventually does call render on the view, the result of which is stored as its response_body.  The response body is eventually returned in the way Rack expects, as a string array (what you see as your output).
These links may shed some more light on how this works:
- The controller's definition of render (metal)
- It's superclass method, where response_body is set (abstract_controller)
Comment: I've never experienced this issue for 3 years until 3.1. Calling render in helpers is one of the primary uses of helpers, since it cleans and dries up a lot of :partial calls throughout the app. I've solved this problem by creating a module and including into ApplicationHelper, since calling render in a controller helper doesn't make any sense anyway.
Comment: Yes you're right.  Rendering partials is something you do very often in helpers.  You just have to make sure you're calling the view's `render` method, which does the actual work of rendering the template, versus the controller's `render` method, which renders a response to a dispatched request.
Comment: I figured this would be the case when defined as a helper with helper_method, but apparently not. Tnx for your input.
Comment: Yea, helper_method is still calling the method on the controller.  You could use `helper MyHelperModule` on the controller, in which case the methods of the module would be mixed into the view context instead.


Angular  changing [value] does not update it only for the first time

Question: So I have this code in my angular project :

    <form [formGroup]="firstFormGroup">

TEMPLATE EDIT

Plz select a template first

            <input type="text" [value]="selectedList.templateMesage" formControlName="firstCtrl">
            {{selectedList.templateMesage}}

            <input type="text" [value]="selectedList.templateCaption!== undefined ? selectedList.templateCaption : ''">
            {{selectedList.templateCaption!== undefined ? selectedList.templateCaption : ''}}

            <input type="url" [value]="selectedList.templateAction !== undefined ? selectedList.templateAction : ''">
            {{selectedList.templateAction !== undefined ? selectedList.templateAction : ''}}

            <input type="text" [value]="selectedList.templateImage !== undefined ? selectedList.templateImage : ''">
            {{selectedList.templateImage !== undefined ? selectedList.templateImage : ''}}

        <button (click)="checkValidity()">Next</button>

    </form>

But when I update the selectedList for the first time , my input does not update
First Update :

Second Update :
 firstFormGroup = this._formBuilder.group({
    firstCtrl: ['', Validators.required],
 });

 selectList(list:viberTemplateDetails){
    if(this.selectedListId != list.templateId && list.templateId!=undefined){
      this.selectedListId = list.templateId;
      this.selectedList = list;
    }
    console.log(this.selectedList);
  }

My console.log() also shows the selectedList when I change it

Is there something that I am missing? I am new to Angular and Typescript so this is maybe normal behavior and I have to do something else
Comment: You are using the `formControlName` approach, so I assume that you have a `FormGroup` defined in your `.ts` file that has the `firstCtrl` `FormControl` listed on it. Could you please include that code in your question :) If you do not have a `FormGroup` defined, that will already be part of the problem, but there are different routes we could go down to get it working
Comment: @nate-kumar I added the part where I defined the FormGroup
Answer: You don't reference the created FormGroup. Try referencing it like this:
        <form [formGroup]="firstFormGroup">
            <input type="text" [value]="selectedList.templateMesage"
              formControlName="firstCtrl">
            {{selectedList.templateMesage}}
        <form>

I hope it helps. :)
Update:
I used [value] and formControlName by accident in the same Tag:
        <form [formGroup]="firstFormGroup">
            <input type="text" formControlName="firstCtrl">
            {{formGroup.controls['firstCtrl'].value}}
        <form>

Comment: I didnt have the full code , I now posted the full code with the formGroup included
Comment: Please, don't use `[value]` and `formControlName` in the same tag. If you want to give an initial value, give it when you create the formGroup or use setValue or patchValue.


Prove that $\sqrt[3]5 - \sqrt[4]3$ is Irrational

Question: I've gone many directions and they all fail.
The sum of two irrationals doesn't need to be irrational.
I found a proof saying: if irrational $x,y$ have a rational sum $x+y$, then $x-y$ is irrational, or vice versa. However, in this case $x+y$ and $x-y$ are irrational.  I must have misinterpreted the proof maybe.
Is the sum and difference of two irrationals always irrational?
I recognize $n\in\Bbb Q\implies \exists a,b\in\Bbb Z~(b\neq 0) : n=\dfrac ab$
Also the product of a rational and irrational number are irrational so $a = b(\sqrt[3]5 - \sqrt[4]3)$ where $a,b\in \mathbb{Z}$. I've looked on this basis as well, but so far fruitless.
Thank you,
Julian
Comment: If you know [algebraic integer](https://en.wikipedia.org/wiki/Algebraic_integer), there is a relative short argument. Since $\sqrt[3]{5}$, $\sqrt[4]{3}$ are both algebraic integers and algebraic integers are closed under sum, difference and product, $\sqrt[3]{5} - \sqrt[4]{3}$ is an algebraic integer. It is known that if an algebraic integer is a rational number, then it is an ordinary rational integer. Since $|\sqrt[3]{5} - \sqrt[4]{3}| \approx 0.3939019337242045 < 1$ is not an integer, it cannot be a rational number.
Comment: Note that the sum and difference of two irrationals is of course not always irrational. For example, if $x$ is irrational, then $x - x = 0$ is obviously rational.
Comment: I can come up a proof by calculating the minimal polynomial and then proving it cannot have any rational roots. But the minimal polynomial isn't really computable by hand. I can show you the work if you are interested.
Comment: Please, I found that on wolfram, and I'm reading about it but I don't exactly understand it yet.  Thank you.
Answer: The minimal polynomial over $\mathbb{Q}$ of $\alpha=\sqrt[3]{5}$ is $p_{\alpha}(x) = x^3-5$ and the minimal polynomial over $\mathbb{Q}$ of $\beta=\sqrt[4]{3}$ is $p_{\beta}(y)=y^4-3$. Monomials of the form $x^{u}y^{v}$ with $0\leq u\leq 2$ and $0\leq v\leq 3$ give a base of $\mathbb{Q}[x,y]_{/(x^3-5,y^4-3)}$. If we represent $(x-y)^{m}$, for $0\leq m\leq 12$, with respect to such a base, we get, by Gaussian elimination, a polynomial with degree $12$ and rational coefficients that vanishes when evaluated at $\alpha-\beta$. Such a polynomial is:
$$ q(x) = x^{12}-20 x^9-9 x^8 +150 x^6-720 x^5+27 x^4-500 x^3-2250 x^2-540 x+598.$$
Since $598=2\cdot 13\cdot 23$, by checking that $q$ does not vanish over the set
$$ \left\{\pm 1, \pm 2,\pm 13,\pm 23, \pm 26,\pm 46,\pm 299,\pm 598\right\}$$
we have, by the rational root theorem, that $q$ has no roots in $\mathbb{Q}$, hence $\alpha-\beta\not\in\mathbb{Q}$ as wanted.
We may speed-up the last phase by noticing that $\left|\alpha-\beta\right|<1$, hence $\alpha-\beta$ cannot belong to the previous set, as pointed by achille hui in the comments.
Comment: Shouldn't candidates for rational roots be $\{\pm 1,\pm 2,\pm 13\ldots\}$?
Comment: @Ennar: you are right, now fixed.
Comment: @Julian73: $q$ vanishes over $\alpha-\beta$, but due to the rational root theorem, if $q$ has a rational root such a rational root is an integer. $\alpha-\beta$ is not an integer, hence it is not a rational root. It is a root, hence it is not rational.
Comment: @Julian73: you're welcome.
Answer: Another approach, though I like @AchilleHui's comment a lot:
Write $\lambda^3=5$, $\mu^4=3$, and let $a=\lambda-\mu$, which we want to show is irrational. Assuming rationality of $a$, we get:
\begin{align}
3=\mu^4&=(\lambda-a)^4\\
&=5\lambda-20a+6a^2\lambda^2-4a^3\lambda+a^4\\
0&=(a^4-20a-3)\,+\,(5-4a^3)\lambda\,+\,(6a^2)\lambda^2\,.
\end{align}
Notice that the three quantities in parentheses are rational (assuming that $a$ is rational), and with the knowledge that $\{1,\lambda,\lambda^2\}$ is a $\Bbb Q$-linearly independent set, you see that $6a^2=0$, a contradiction, since $\lambda\ne\mu$.


Comparing Cox Proportional Hazards Models (variable selection)

Question: I am using a cox proportional hazards model to run a survival analysis in r on a number of non-nested, distinct covariates such as Age, Blood Type, Cancer, etc:
 A, B, C, D, E

When I run the model on the omnibus null hypothesis:
surv ~ A + B + C + D

The effects of all of the covariates are insignificant because the number of subjects that have measurements for every covariate is relatively small.  However, when I isolate single or other combinations of covariates in different cox models:
surv ~ A
surv ~ A + C
surv ~ B + D

I'm showing significant effects because the sample set is larger (i.e. the number of observations discarded by the model shrinks).
What I'm having difficulty understanding is how to do the following:

Comparing the different cox models for the best fit, i.e. is     surv ~ A + B + D     a better model than     surv ~ A + C    ?  Should I be comparing the likelihood, wald or logrank scores?
Is it possible to run every possible combination of covariates to determine the best model? I have about 15 covariates.
More broadly, is this tactic the best approach to optimizing for both significant covariates and overall model "cost"? I will be attaching a cost to each distinct cox model i.e. using covariates    A + B + C    in the model costs \$100 while using covariates    A + B costs \$75 and using only covariate    A    costs \$10. I'd like to look at the cost for each combination of covariates vs. the accuracy for each cox model.

Thanks very much for your help!
Answer: In general there is no reason to do variable selection.  The model uncertainty and bias resulting from it are problematic.  Insignificant variables are not tragic.  And the data are incapable of telling which variables are "really" important.  But if you have true costs of measuring variables, you can fit a well-defined sequence of models by adding variables in ascending order of cost, and stop when you have the best model for the money.  There is little model uncertainty when using an apriori ordering of variables.
Comment: This might be a point on the curve (x=total cost, y=likelihood ratio chi-square) where things start to flatten.
Comment: The likelihood ratio $\chi^2$ statistic has the best properties and since it is a simple function of the -2 log likelihood it is more likely to order the models correctly.  Be sure that you do not use any $\chi^2$ or $P$-values to select the model sequence.
Comment: Thank you. When you say "best model" how are you determining "best"?
Comment: Again, thanks. But why would you use the likelihood ratio as opposed to the wald test or the score (logrank) test. In looking at model accuracy, the coxph function in r presents (for example):
Comment: `Likelihood ratio test = 10.47 on 2 df, p=0.005316. Wald test = 10.02 on 2 df, p=0.006686. Score (logrank) test = 10.24 on 2 df, p = 0.005966` vs. (for a 13 covariate example): `Likelihood ratio test = 54.06 on 13 df, p=5.897e-07. Wald test = 41.12 on 13 df, p=9.115e-05. Score (logrank) test = 47.1 on 13 df, p = 9.304e-06`. Is it valid to say one model is more accurate than the other and if so, per your prior comment, I'm assuming you would recommend doing so based on the likelihood ratio?


Show that $3\mid xy$ in $x^2 + y^2 = z^2$

Question: Part 1:
If $x$, $y$, and $z$ are positive integers for which $gcd(x, y, z) = 1$ and $x^2 + y^2 = z^2$, show that $3\mid xy$
Part 2:
Now again if $x$, $y$, and $z$ are positive integers for which $gcd(x,y,z) = 1$ and $x^2 + y^2 = z^2$, can a similar result to the one in (part 1) be said modulo 5? Not that $5|xy$, but one of $x,y,z$?
Comment: Hint: $a^2\equiv 0\text{ or }1\pmod 3$
Answer: Note that $3$ is a prime, so $3 \mid xy \iff 3\mid x$ or $3\mid y$. Suppose to the contrary that $3 \nmid x$, and $3\nmid y$, then:$x = 1,2$ mod $3$ and $y = 1,2$ mod $3$. Then:
$x^2+y^2 = 2$ mod $3$, and $z^2 = 0,1$ mod $3$. Contradiction, proving the claim.
Comment: If I add a second part to this problem, would you help with that by adding to this answer?
Comment: @Sandikae All you questions have been answered in my answer and in the links provided.
Answer: Primitive Pythagorean triplets can be characterized precisely.

If $x^2+y^2=z^2$, where $x,y,z \in \mathbb{Z}$, and $\gcd(x,y,z) =1$, then $x=m^2-n^2$, $y=2mn$ and $z=m^2+n^2$, where $\gcd(m,n) = 1$ and are of opposite parity.

From the above, we can immediately conclude that $3$ divides $xy$. Similarly, we can conclude that $4$ divides $xy$ and $5$ divides $xyz$. Look here for more properties on Pythagorean triplets.
Comment: You really linked to dropbox, a site that is specifically meant to be temporary storage? The point of this site is to be a permanent repository for answers, not just to answer the OPs question.


Windows Server 2008 crashes

Question: Server has crached several times this year and I can't find cause for these crashes. From minidumps I can tell only that one of processors deadlocked.
Can someone help me with this problem?
Server spec.:
OS: Windows Server 2008 SP1 x32bits
CPU: Intel Xeon 2.13Ghz x4
RAM: 4GB
Chipset: Intel Corporation 82441FX 440FX (Natoma) System Controller Rev 2 (SU053)
Archive with minidump files
Answer:
check driver levels
If driver levels are ok... return server as faulty.

Seriously. Server 2008 is dead stable. So, either you have a borked driver, or you simply have defective hardware.
Answer: Try running some cpu tests, or memtest, see if that shows up anything... recently I had an Intel i5 CPU have problems calculating primes, nothing crashed, but the system would lock up or run very slowly - but only intermittently.
Answer: Do you have more than one role installed on the server? It is a possibility that the roles are running in the background and using a lot of resources. Since you have 4GB of memory, you can install one additional server using hyper-v and install few roles into that server.
If this is not an issue, you can run a virus scan or malware scan using malewarebytes (note the false positive). You can also use Ultimate boot cd or Hirens boot cd to run at start up.  You can use any of these softwares to test if your CPU is functioning well.

Windows Server 2008 crashes


Am I calling my API correctly? Getting CORS error

Question: So this is really baffling me. I have tested the following API in AWS Lambda and with the aws npx cli test command and it is working on both. The issue arises when the api is called from the client when i submit a form. I get the following error
Access to XMLHttpRequest at 'https://sdigg5u4xb.execute-api.eu-west-1.amazonaws.com/prod/sites' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have already tried DISABLING cors on my serverless.yml file. I have tried using different IAM roles and I have tried calling it differently in the client code.
Here is where I am calling the API:
import { API } from "aws-amplify";

export default (async function submitSite(values) {
  console.log(JSON.stringify(values));
  return API.post("sites", "sites", {
    body: values
  })
});

Here is where my API is defined in the serverless.yml file
createSite:
    handler: CreateSite.main
    events:
      - http:
          path: sites
          method: post
          cors: true
          authorizer: aws_iam

and here is the api code itself
import uuid from "uuid";
import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";

export async function main(event, context) {
  const data = JSON.parse(event.body);
  const params = {
    TableName: "sites",
    Item: {
      userId: event.requestContext.identity.cognitoIdentityId,
      siteId: uuid.v1(),
      siteName: data.siteName,
      siteAddress: data.siteAddress,
      siteCounty: data.siteCounty,
      siteEmail: data.siteEmail,
      siteNumber: data.siteNumber,
      openTimes: data.openTimes,
      siteCat: data.siteCat,
      siteFees: data.siteFees,
      access: data.access,
      w3w: data.w3w,
      gps: data.gps,
      detailsHeader: data.detailsTxtHeader,
      detailsContent: data.detailsTxtContent,
      tourName: data.tourName,
      tourWaypoints: data.waypoints,
      tourDuration: data.duration,
      tourHeader: data.tourTxtHeader,
      tourContent: data.tourTxtContent,
      poiName: data.poiName,
      poiType: data.poiType,
      poiDesc: data.poiDesc,
      poiDuration: data.poiDuration,
      poiRanking: data.poiRanking,
      poiTime: data.poiTime,
      poiAccess: data.poiAccess,
      poiHeader: data.poiTxtHeader,
      poiContent: data.poiTxtContent
    }
  };

  try {
    await dynamoDbLib.call("put", params);
    return success(params.Item);
  } catch (e) {
    return failure({ status: false });
  }
}

Answer: You need to set CORS also on the response. So adjust it accordingly in your success() method (which you have not shown by the way, so it'd be nice to add it as well in case the code below does not work):
const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true,
    },
    body: JSON.stringify(yourCustomObject),
  };

Comment: I actually have fixed the cors aspect of it, now i just have the error `POST https://sdigg5u4xb.execute-api.eu-west-1.amazonaws.com/prod/sites 403` as if it is not recognising my api
Comment: 403 is forbidden.Does the logged in cognito user have access to your resource? Also, I suggest you tackle this in a separate question as this is a completely different problem.
Comment: But I have tested it in aws lambda and it succeeded, would it still be user access related if it wont work in the client?


Use CASE to update some records

Question: Private Sub Command204_Click()

Dim db As Database

Set db = CurrentDb

db.Execute "UPDATE Table1 SET Test =(CASE WHEN (Test = 'A') THEN 'B' WHEN (Test ='B' THEN 'A') ELSE Test END ) WHERE Test IN ('A','B')"

db.Close

End Sub

Getting error when I press the button. Can anyone help me with this.
Answer: MS Access' flavor of SQL does not support CASE expressions.  You could use IIF() here instead:
UPDATE Table1
SET Test = IIF(Test = "A", "B", "A")
WHERE Test IN ("A", "B");

Comment: `its not working` <-- this is not feedback which lets me update my answer.  _What_ exactly isn't working?
Comment: can you read out my equation again. becoz i made some changes now. please
Comment: Actually i trying to update  'A' in the place of 'B' and the same 'B' in the place of 'A'.

Use CASE to update some records


Introducing the EWS Managed API!

Question: Does the system administrator need to install anything extra to get Managed EWS working for clients on Exchange 2010? At the moment I am getting problems just using AutoDiscover via the Managed API so i'm beginning to think the server has been configured incorrectly.
Has any administrator here had any experience with setting up Exchange 2010 to allow access via the Managed API?
thanks,
Answer: You don't have to do anything extra. EWS is on by default, as Outlook (2007 and later), Communicator, Entourage, and several other programs use it by default. If AutoD is failing, I'd check to make sure that you have the correct internal and external URLs registered for the CAS; take a look at http://technet.microsoft.com/en-us/library/bb201695.aspx and verify that you've set everything properly.

Introducing the EWS Managed API!


What are the mechanisms for the propagation of effects across stages in a structural model?

Question: I have an SEM question to which I have not found an answer anywhere. I have used SEM a bit already but my difficulties with this question suggest I lack some basic understanding.
Question:
In a structural model involving chains of paths as long as four or five paths (a multistage model, e.g., as in x1 -> x2 -> x3 and x4 -> x5 and x6 -> x7 and x8), some of which stages thus contains several parallel variables and paths, I find that the ML estimates of the path coefficients in early parts of the model (early stages) change when I adjust later parts of the model (i.e., when I insert an additional stage just prior to the final variable by means of a new variable with paths to it and from it, or when I separate an existing latent factor in a late stage into two different latent factors). The changed estimates for the early path coefficients happen as far away from the inserted or split (divided in two) variables as two paths away (e.g., paths from x3 and x4 are affected by new insertions just before x7 and x8).
The changes in the early path coefficients are substantial and involve change of sign as well as change of statistical significance. (The intermediate path coefficients between the newly inserted paths and the affected earlier paths change too.)
Do my adjustments late in the model (i.e., in later stages close to the final dependent variables) somehow back propagate by creating changed residual variance in earlier variables to which earlier variables are connected, such that the paths to this residual variance in the earlier stages is affected? It is clear how addition or removal of covariates can affect coefficients in a multiple regression, but it is unclear (to me) whether something similar could be going on (and in that case how) even across several paths in a structural model of an SEM, which is based on a covariance matrix fitting. What is the mechanism whereby changes in one place can affect paths in another place? Does the mechanism involve the residual (co)variances (perhaps even in a way that could allow me to anticipate what the changes might be of adding or removing paths even far away in the model)?
I have used STATA to carry out the analyses.
Thanks very much for any advice on how to understand (or deal with) this.
Answer: Standard maximum likelihood estimation searches for estimates that simultaneously minimize all discrepancies between observed and expected (model-implied) (means and co)variances.  This makes it subject to "propagation of errors", which some SEM textbooks discuss (e.g., Kline or Loehlin).  Most (un)weighted least-squares estimators (including GLS) are also subject to this.  But Bollen (1996) introduced two-stage least-squares (2SLS) estimation that solves for paths equation by equation.  This is not immune, but is much less susceptible to, propagation of errors.  I'm not sure about Stata, but I know this estimator is implemented in R using the MIIVsem package (see lots of details on the <code>?miive</code> help page).


How to rotate a particle in three.js

Question: I have a particle which is an image. When I rotate the particle it leaves a circle behind. How do I get rid of this strange circle?
The Fiddle is here: http://jsfiddle.net/zUvsp/137/
Code:
<code>var camera, scene, renderer, material, img, texture, particle;
init();
animate();

function init() {
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
  camera.position.z = 1000;
  scene.add(camera);

  img = new Image();
  texture = new THREE.Texture(img);

  img.onload = function() {
    texture.needsUpdate = true;
    makeParticle();
  };
  img.src = "http://www.atalasoft.com/cs/blogs/davidcilley/files/PNG_Mask.png";

  renderer = new THREE.CanvasRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
}

function makeParticle() {
  material = new THREE.ParticleBasicMaterial({
    map: texture,
    blending: THREE.AdditiveBlending,
  });
  // make the particle
  particle = new THREE.Particle(material);
  particle.scale.x = particle.scale.y = 1;
  particle.position.x = 10;
  scene.add(particle);
}

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
  particle.rotation.z += 0.01
}
</code>
Answer: -EDIT
I tested my theory, its not the issue, don't waste your time
Just a guess, but I think it might have something to do with you loading the texture .png from a different domain.
Try using an image loaded from the same domain your code is running on, and see if that fixes the problem.
I think the issue might have something to do with three.js not being able to access the pixel data on the texture, because of the Cross-origin issue.

How to rotate a particle in three.js


Create a distribution

Question: How is it possible to create a new Drupal distribution based on site that I already built? I've already exported the content types using
drupal config:export:content:type MYCONTENTTYPE --module MYMODULE
Drupal console has the following function which may be useful.
https://hechoendrupal.gitbooks.io/drupal-console/content/en/commands/generate-profile.html
This following link leads to the current drupal.org documentation on creating a Drupal 8 distribution. It looks like it only shows how to create a distribution manually though.
https://www.drupal.org/docs/8/creating-distributions/how-to-write-a-drupal-8-installation-profile
I was hoping that there was something in Drupal console or Composer that would take all the information in my current database and create an installation profile out of it.
EDIT
The Drupal Profile Builder seems wonderful but current only supports D7.
Answer: Actually, the drupal.org link above will work. At the bottom of the page there is a section that discusses bringing configuration files into the install directory. You can use Drupal Console (DC) to create the configuration files like this:
drupal config:export

It will put all the configurations in the public folder unless you specifiy a directory.
https://hechoendrupal.gitbooks.io/drupal-console/content/en/commands/config-export.html
https://www.drupal.org/docs/8/creating-distributions/how-to-write-a-drupal-8-installation-profile
EDIT
Also, I've added a Drupal.org page has a lot of resources for creating a distribution. On the sidebar it lists common make errors and other useful links.
If you check the release download page of your distribution, you can find the Drupal packager error messages if you send a distribution for packaging.
A lot of this needs to be learned by trial and error. I've spent a fair amount of time on this and still haven't gotten the hang of things.
https://www.drupal.org/node/642116
EDIT
Also, there appears to be something called drupalorg_drush. It's a drush extension that helps build a replica of what drupal.org would do with your distribution files should you upload them to your project's Git repository. However, at the time of this writing, Drupal 8 version is not available.
Comment: I've been working through this "trial and error" part for a few days. It seems that installation profiles do not work with Drupal 8. If you use the doc link that you pasted on building a profile, they simply do not install without errors. If you include all of the modules that you need in the info.yml, the installation complains about those modules not being available. Having a composer file with dependencies does not help. As I see it, there is no way to complete an installation with a profile out of the box without troubleshooting.
Comment: @JasonGlisson this was a real pain I remember. I was able to get by with some hacks.
Comment: If there is any useful documentation you can send my way, that would be great. Nothing on Drupal.org is correct for this or it's lacking something.

Create a distribution


Please explain Java inheritance in this case

Question: I'm learning Java and can't understand some tricks of inheritance.
Example:

we have a class Animal;
we have a class Cat, extends Animal;
we have a class Tiger, extends Cat;

Questions:
1) Why Cat uses Tigers method?
See below example of "make_a_sound" method. It's from Tiger, but Cat can use it.
2) Why Cat, can not see any properties of Tiger?
Cat can use method "make_a_sound" of Tiger, but can not see its properties... quite strange.
Thanks,
Gennadiy
public class Solution {
    public static void main(string[] args) {

        Cat cat = new Tiger();

        // The result is from Tiger class: A tiger says RRRRR & new tiger property
        // Why???
        cat.make_a_sound();

        // Only cat's and Animal's properties are visible. No Tiger's properties
        System.out.println(cat.this_is_a_cat);
    }

    // Base class
    public class Animal {
        public String this_is_an_animal = "Animal";

        public void make_a_sound() {
            System.out.Printf("I'm an animal");
        }
    }

    // Extends base class
    public class Cat extends Animal {
        public String this_is_a_Cat = "Hi, I'm a cat";

        public void make_a_sound() {
            System.out.Printf("A cat says meey");
        }
    }

    // Extends prev. class
    public class Tiger extends Cat {
        public String this_is_a_Tiger = "Tiger";

        public void make_a_sound() {
            System.out.Println("A tiger says RRRRRR");

            this_is_a_Tiger = "new tiger property";
            System.out.println(new_tiger_property);
        }
    }
}

Comment: 1. It uses a method declared in its own class `Cat`, that is overridden in `Tiger`. 2. Because a `Tiger` is a `Cat` but a `Cat isn't necessarily a `Tiger`.
Comment: Q1: Due to polymorphic behavior because of this: `Cat cat = new Tiger();`
Comment: Sure, but do you have any links to Videos with detailed description? I just wanna understand the depth of this.
Answer: You defined cat as type Cat. That means cat can do anything that any other Cat can do.  The Animal object does define the make_a_sound function so it's available to all Animal instances. When you run your code, the variable cat points to a Tiger instance so when make_a_sound is called, it's the one in Tiger that runs. That's the whole point of inheritance.
For your second question, cat is of type Cat so you can only do things with it that you can do with any Cat object. Since this_is_a_Tiger is not something every Cat object has, it is not available to cat even though cat really points to a Tiger.
But you could do this:
if (cat instanceof Tiger) {
   Tiger tiger = (Tiger)cat;
   System.out.println(tiger.this_is_a_Tiger);
}

Answer:
Why Cat uses Tigers method? See below example of "make_a_sound" method. It's from Tiger, but Cat can use it.

Answer) Because when you say Cat cat = new Tiger() you are not saying any cat,you are saying you want sound of the Tiger and not any generic cat.Tiger is using cat's "make_a_sound" method by over riding the implementation by the Tigers sound.
if you had not overriden tigers "make_a_sound" method then the Cat's "make_a_sound" method will be called.You can try it out by saying super().make_a_sound in Tiger class or removing implementation of this method.
2) Why Cat, can not see any properties of Tiger? Cat can use method "make_a_sound" of Tiger, but can not see its properties... quite strange.
Answer) If parents classes would know everything about child class then OOPS will be broken.In OOPS each class should only know about what it does and nothing else.It does not care of other class responsibility.
Answer: This link could give you some concept regarding Overriding in Java:
https://www.geeksforgeeks.org/overriding-in-java/
For simplicity, Overriding only take effective on methods (regarding Question 1), but not on field variables (regarding Question 2).


How do I write Rails ActiveRecord update query with dynamic binding?

Question: With where we can do Item.where('stock_amount > ?', 0).
Question: Is there a way to write in ActiveRecord that will produce the following SQL?
UPDATE items SET stock_amount = stock_amount - 10 where id = 1;

I have tried
Item.update(1, {stock_amount: ['stock_amount - ?', 10]}

and it runs but does not produce the SQL I want.
I know I can achieve the same result with more lines like
item = Item.find(1)
item.stock_amount = item.stock_amount - 10
item.save

and using exec_update
ActiveRecord::Base.connection.exec_update('UPDATE items SET stock_amount = stock_amount - $1 WHERE id = $2', 'sql', [[nil, 10],[nil, 1]])

This post is the closest I get.
Answer: Item.where(id: 1).update_all(["stock_amount = stock_amount - ?", 10])

should produce:
UPDATE "items" SET stock_amount = stock_amount - 10 WHERE "items"."id" = $1  [["id", 1]]

Comment: With Rails 5.1.6, I get little bit different SQL that achieve the same result. `UPDATE "items" SET stock_amount = stock_amount - 10 WHERE "items"."id" IN (SELECT "items"."id" FROM "items" WHERE "items"."id" = $1 ORDER BY "items"."name" ASC)  [["id", 1]]`


Capturar texto dentro de uma  via jQuery

Question: Como faço para pegar somete o valor (R$11,20)?
R$11,20

Não deu certo, e tem essa outra estrutura, preciso somente do texto:
"R$ 8,62 - Até 8 dias úteis"
Econômica - R$ 8,62 - Até 8 dias úteis

$('#Econômica').text(); // Retorna
$('#Convencional).text(); // Retorna
$('#Rápida).text(); //Retorna
$('#Entrega Agendada I Convencional').text(); // Não Retorna
$('#Entrega Agendada I Sábado').text(); // Não retorna

        Entrega Agendada I Sábado - A partir de R$ 76,20 - Primeira data em 06/08/2016

    Entrega Agendada I Sábado - A partir de R$ 76,20 - Primeira data em 06/08/2016

Entrega Agendada I Sábado - A partir de R$ 76,20 - Primeira data em 06/08/2016

Comment: Tens acesso ao código do servidor que gera esse HTML? assim podias passar isso num atributo `data-` e era bem mais seguro e fácil.
Comment: Somente uma curiosidade:
Se quiser capturar o texto de dentro de um select apenas do que foi selecionado o código seria o seguinte: var texto = $('#id_do_select :selected').text();
Answer: Eu não sei como é o resto da estrutura do HTML, mas um código assim resolve para o caso apresentado:
$("td.monetary").text();

Pela estrutura parece que você está usando knockoutjs, se estiver existem outras opções.
Comment: Estou usando a biblioteca knockout-2.3.0.js sim Douglas. Pode me ajudar?
Comment: estou usando a biblioteca knockout-2.3.0.js sim Douglas. Pode me ajudar?
Comment: Eu não sei qual a estrutura do seu Model para o Knockoutjs, mas você pode acessar diretamente o valor pelo seu modelo.(seuobjeto).maxEstimateOptionText(). Isso para o segundo caso.
Comment: Você poderia colocar mais informações?  O primeiro caso está dentro de um data-bind="foreach: " ?
Comment: @BrunoNascimento, eu preciso de um exemplo melhor do seu HTML, eu vi a sua edição, mas eu não sei quais são os Ids que você está utilizando em seus elementos.
Comment: Eu melhorei a descrição @Douglas Fernandes, só estava estruturando, acho que agora está completa. Como disse, não consegui selecionar as entregas agendadas. Me desculpe a bagunça, se precisar que edite, pode falar. Grato desde já!
Comment: @BrunoNascimento, você pode tentar fazer algo deste tipo                  $(".seller-BTP-sla-EntregaAgendadaISabado span").text();                  . Mas eu acho que não é o caso. Pela sua lógica também pode tentar algo assim $(".seller-BTP-sla-EntregaAgendadaISabado.selected span").text();
Comment: Ou você pode tentar fazer algo deste tipo no Knockout: var TextEsperado;
    foreach( var i in objeto.()){

     if(objeto.()[i].name == $parent.selectedSlaName()){
     TextEsperado = objeto.()[i].maxEstimateOptionText(); break;
     }

    }
Answer: Segue exemple de como tirar o texto de um elemento do HTML e manipula-lo. Nesse exemplo eu peguei o texto do DIV e o coloquei dentro de um Input.
Espero ter ajudado.

$(function(){
    var valorDaDiv = $(".divdemonstracao").text();
    $("#inputdemonstracao").val(valorDaDiv);
});

Produto teste 1

Texto vai aparecer dentro do Input:

<input type="text" id="inputdemonstracao">
Answer:
Preciso somente do texto: "R$ 8,62 - Até 8 dias úteis"

$(document).ready(function(){
  var span = $("span").text();
  var dados = span.split("Econômica - ");
  console.log(dados[1]);
  alert(dados[1]);
});

Econômica - R$ 8,62 - Até 8 dias úteis

Capturar texto dentro de uma  via jQuery


Pass data between a container and its children components in react

Question: I have a <Container /> component that takes a list of <Card /> as children:
<Container>
  <Card />
  <Card />
</Container>

<Card /> has a boolean state openExpansion that I want once changed, all sibling <Card /> would change to the same value. What is the best way to achieve that?
Obviously I can have openExpansion as <Container /> state and inject it to each <Card />. Also I don't want to use redux store as I don't know where <Container /> will be called. But is there a way to keep  openExpansion as <Card /> state while achieving the same effect?
Thanks!
Comment: It sounds like you already know what the arguably best solution is, move the bool to the parent's state. But can you tell us *why* you don't want to do that?
Comment: @ChrisG No, I don't know the best solution, and that's the point of the discussion.
Comment: You mentioned the best solution *in your question*. Again: move the bool to the parent, like at least three of the answers here are recommending. If you don't want do to that, tell us *WHY* not.
Comment: @ChrisG because in this way,  will always rely on props passed from  and it is better called  rather than a more generalizable  component. It'd be nice to have a solution to achieve the generalisability. But maybe there's no way to do that.
Comment: Without an external wrapper of some kind (parent Component, Context, redux, etc.), children cannot communicate with each other.
Answer: If you want to share the same value between siblings, you should put openExpansion props in each of the child.
Also if you want to change the openExpansion you can create a function in Container
class Container extends React.Component{
    ....
    state = {
        openExpansion: true
    }

    changeOpenExpansionValue = (value) => this.setState({openExpansion:value})
    render(

        <Card openExpansion={this.state.openExpansion}
            toggleOpenExpansion={this.changeOpenExpansionValue }/>

        <Card openExpansion={this.state.openExpansion}
            toggleOpenExpansion={this.changeOpenExpansionValue }/>

    )

}

any time you want to change all the values from one child component just call this.props.toggleOpenExpansion(boolValue) from your Cards
You can't keep openExpansion value locally in each Card as it would be stored and accessible only inside of Card component and might differ from values in siblings
Answer: Just create a state in the main component and pass the function to update state to Card. Something like
   const App = () => {

   const [openExpansion, setOpenExpansion] = React.useState(false);

   return (
     <Container>
     <Card setOpenExpansion={setOpenExpansion} openExpansion={openExpansion} />
      <Card />
    <Card setOpenExpansion={setOpenExpansion} openExpansion={openExpansion} /><Card /> /* Similar to above card */
     </Container>
    );
   };

  const Card = ({setOpenExpansion openExpansion})  => {
    return (

 openExpansion(true)}>
            {openExpansion ? "opened" : ""}

    );
  }

If I'm getting correctly this is something that you want to achieve by passing setState, state variables.
Answer: I think you explained one option which is having one variable in Container and passing it into every Card component. Another option is to use a static property inside the Card component. Every Card instance would have the same value.
Answer: It seems to me that you have to lift your state up: https://reactjs.org/docs/lifting-state-up.html
So in your case, you can create a method/function where you wrap these cards.
class WrappedCards extends React.Component {
  constructor(props) {
    super(props);
    this.handleOpenExpansion= this.handleOpenExpansion.bind(this);
    this.state = {openExpansion : false};
  }

  handleOpenExpansion(value) {
    this.setState({openExpansion : value});
  }

  render() {

    return (
      <Container>
        <Card
          handleOpenExpansion={this.handleOpenExpansion} />
      </Container>
    );
  }
}


Understanding relations: Are these examples correct?

Question: The task is to find examples for the following relations on the set of  (and prove its correctness) :
1: antisymmetric and transitiv
2: antisymmetric and not transitiv (intransitiv)
3: not antisymmetric and transitiv
4: not antisymmetric and not transitive (intransitiv)
====================================================================
So far I got the following examples:
1: Relation: ≤ (smaller than or equal to)
Proof of antisymmetry through a truth tabel.
Proof of transitivity: not sure: definition: aRb and bRc => aRc
Question: Is this allowed: a = b = α and c = β : αRα and αRβ => αRβ ?
––––––––-–––––––––––––-–––––––––––––-–––––––––––––-–––––––––––––-–––––
2: Relation: "is direct predecessor of" (e.g.: nR(n+1) -> n is direct predecessor of (n+1))
Proof of antisymmetry through truth table
Proof of intransitivity through definition ()
––––––––-–––––––––––––-–––––––––––––-–––––––––––––-–––––––––––––-–––––
3: Relation: /, divided by (e.g.: aRb -> a divided by b
Proof of "not antisymmetric" by giving one example that does not hold for antisymmetry. (4/-4)
Proof of Transitivity: not sure how to prove it for everything. Maybe a truth table?
––––––––-–––––––––––––-–––––––––––––-–––––––––––––-–––––––––––––-–––––
4: Did not come up with a relation.
Question: Any tips that guide me in the right direction?
Answer: $1\require{cancel}$. Correct example. But I don't know what you mean by proving antisymmetry with a truth table. Both properties are almost too obvious to prove for relation $\leq$.
For any $a,b\in \mathbb{R}$ suppose we have both $a \leq b$ and $b \leq a$. This can only be true if $a=b$. Hence $\leq$ is antisymmetric.
For any $a,b,c\in \mathbb{R}$ suppose we have both $a \leq b$ and $b \leq c$. This implies $a\leq c$. Hence $\leq$ is transitive.
$\\$
$2$. Correct example, but you shouldn't call it "direct predecessor of" because the set is $\mathbb{R}$, not $\mathbb{Z}$. And $n$ is not a good variable name for a typical real number; $x,y,a,b$ are better.
Antisymmetry holds simply because there is no $a,b \in \mathbb{R}$ such that $aRb$ and $bRa$: if $a+1=b$ then $b+1=a+2 \neq a$.
Usually, proving a property doesn't hold is best done with a specific counterexample. So here, $0R1$ and $1R2$ because $0+1=1$ and $1+1=2$. But $0+1 \neq 2$ so $0\cancel{R}2$. Hence, $R$ is not transitive.
$\\$
$3$. I assume you mean "divides by" rather than "divided by", which is a binary operation, not a relation. But anyway, you seem to be thinking of integers rather than reals. The $|$ relation doesn't really make sense in $\mathbb{R}$ because every number divides every number except that $0$ doesn't divide any number.
Nevertheless, it is a valid example here, if you take $a|b$ on $\mathbb{R}$ to mean "$\frac{a}{b}$ is defined", which means $a\mid b$ for all $a,b\in\mathbb{R}$ where $a \neq 0$.
Then, $1|2$ and $2|1$ but $1\neq 2$ so "$|$" is not antisymmetric.
Now, suppose $a|b$ and $b|c$. Then we know $a\neq 0$, so $a|c$. Hence, "$|$" is transitive.
Having said that it's a valid example, still, you might want to find another because of the unorthodox usage of "$|$".
$\\$
$4$. You could use a simple example such as $R=\{(1,2),\; (2,1),\; (2,3)\}$. Or, perhaps a "better" example is the relation "is the negative of". That is, $R=\{(a,-a) \mid a\in\mathbb{R}\}$.
Neither of these relations are antisymmetric or transitive, which can be easily proved with simple counterexamples.


APC SmartUPS suddenly all lights flashing. What's going on?

Question: upsfault: I have a APC SmartUPS 2U 1500 somewhere in a rack far away. Batteries were replaced recently and UPS was working without issues for a long time.
Suddenly yesterday, the entire equipment attached to the UPS was off. I send someone there to see what's going on and all lights in front of the UPS were flashing. It did not beep.
According to the manual, a constant lit and beep would indicate a UPS fault. Furthermore, "Front Panel LEDs Flash Sequentially" would indicate that the UPS has been shut down remotely and will return when utility power returns. But it was not shut down and utility power never went out.
I told the person to push the off button. While this should turn off the UPS, it started the fan.
Then I told the person to push the on button. Now all connected devices powered up again but the relay sound is constantly audible.
I cannot connect to the UPS over USB (I use nut and I only get error: Driver not connected). It used to work.
What does that mean and what should I do?
Answer: It is telling you to RTFM and contact the manufacturer. Likely something with the batteries is wrong. That the batteries are new is "irrelevant" - they may well NOW be defective due to a production error.
Alternatively it basically blew the hardware.
What to do? STANDARD BUSINESS PRACTICE:

Replace the UPS with the spare you have for cases like that (because having spares for critical equipment = Standard Operating Practice)
Have UPS analyzed, possibly by manufacturer.

In MY case I would also:

Order ANOTHER space as the UPS once fixed is NOT going back into a remove location but stays is either staying as low priority thingy OR being sold on Ebay.


Testing whether a seasonal dip in a time series this year is abnormal compared to previous years

Question: Let's say I have sales data for each month of the year for the last few years. Sales tend to dip in the summer, and I want to determine if the dip this year (or for a given month) is abnormal.
<code>   month   2014     2015     2016
       1   7775     8454     7700
       2  12122    16229    20978
       3  11631    16308    21051
       4  11840    16004    21045
       5  12108    16800    21807
    ...
</code>
Would an F-test/ANOVA be appropriate for this kind of year-over-year data? If not, what might be?
Comment: You need to adjust for autocorrelation
Comment: The previous title ("Hypothesis testing for year-over-year data") was rather vague - it could have applied to almost any question about hypothesis tests for time series - and I don't think it captured the essence of your question. I have edited to make the title more specific - feel free to edit and improve it.
Answer: Fit a model from seasonal ARIMA family. Estimate the residual for a month of interest, and compare it to the error variance. This will give you an idea of whether the "dip" was larger than "normal".


Differentiability of $s=\sum\limits_{-\infty}^{\infty} {1\over (x-n)^2}$

Question: How do I show that $s=\sum\limits_{-\infty}^{\infty} {1\over (x-n)^2}$ on $x\not\in \mathbb Z$ is differentiable without using its compact form? I realize that the sequence of sums $s_a=\sum\limits_{-a}^{a} {1\over (x-n)^2}$ is not uniformly convergent.
I also tried to prove that it is continuous by using the usual $\varepsilon \over 3$ method. And it seems to apply because each $s_a$ is continuous and they converge pointwise to $s$. But then I realized that this should not be the right proof because I didn't use any special property of the given functions and the general case only works for uniform convergence. I am very confused. Please help!
Actually I do realize that if I could prove differentiability, continuity follows.
Thanks.
Answer: There's a theorem they teach in undergraduate analysis classes which says that if $\{f_n(x)\}$ are $C^1$ functions on an interval $[a,b]$ such that $|f_n(x)| \leq M_n$ and
$|f_n'(x)| \leq N_n$ where $\sum_n M_n$ and $\sum_n N_n$ are both finite, then $\sum_n f_n(x)$ is a differentiable function whose derivative is $\sum_n f_n'(x)$.
You can apply this result to your series on any interval $[k + \epsilon, k + 1 - \epsilon]$; if $n \geq 2|k| + 2$ for example ${1 \over (x - n)^2} \leq {4 \over n^2}$ and similarly the derivative ${2 \over (x - n)^3}$ is of absolute value at most ${16 \over |n|^3}$; these inequalities follow from the fact that $|x| \leq {n \over 2}$ and therefore $|x - n| \geq {n \over 2}$ when $x$ is in the interval $[k + \epsilon, k + 1 - \epsilon]$. (The terms for either series when $n < 2|k| + 2$ have uniform bounds on the interval simply because they're continuous. Hence these earlier terms don't affect the applicability of the result.)
Note the same argument applied repeatedly shows the limit function is $C^{\infty}$, and there is an analytic version of this that shows the resulting function is analytic except at the integers.
Comment: Indeed, there is such a theorem in complex analysis as well.  The domain of this function is $\mathbb C \setminus \mathbb Z$.  It converges uniformly on compact subsets of that domain.  So it is analytic on that domain.
Answer: OK, just to be exotic (?), let's see if we if we can get this from Morera's theorem.  Let $C$ be a simple closed curve neither winds around any integer nor passes through any integer.  Then
$$
\int\limits_C \sum_{n=-\infty}^\infty \frac{1}{(x-n)^2}\;dx = \sum_{n=-\infty}^\infty\  \int\limits_C  \frac{1}{(x-n)^2}\;dx = \sum_{n=-\infty}^\infty 0 = 0.
$$
The first equality follows from Fubini's theorem.*
The second equality follows from the fact that $C$ does not wind around any point where the holomorphic function $x\mapsto 1/(x-n)^2$ behaves badly (fails to be holomorphic).
Morera's theorem says that if the integral of a function along every simple closed curve that does not wind around any point not in the domain is $0$, then the function is holomorphic.
* Later note: Are the hypotheses of Fubini's theorem satisfied?  The terms of the sum are nonnegative and the sum converges to a finite number.  If one can show that it depends continuously on $x$, then the integral is that of a continuous function on a compact set, so that is also finite.
However, it now occurs to me that we don't need to go into that, because nonnegativity means we can cite Tonelli's theorem instead.  That says that one can interchange the order of two Lebesgue integrations for functions that are everywhere nonnegative, regardless of whether the value of the integral is finite or infinite.
Comment: Any proof that invokes Morera's Theorem gets a +1 from me.  But could you elaborate on how the first equality "follows from Fubini's theorem"?  That is, can you explain how we know that the hypotheses of Fubini's Theorem are satisfied?
Comment: +1. Just a little remark on notation... I think it is better to denote by $z$ rather than $x$ the integration variable.
Comment: @Jesse: I've added a later note on the Fubini step.
Comment: @Giuseppe: I appreciate your point, but it was called $x$ in the posted question, and changing the notation is sometimes confusing.


A peer-reviewed source/textbook about correlation between a nominal (IV) and a continuous (DV) variable

Question: I am having really hard time finding a citable source for the method described in the following link:
Correlation between a nominal (IV) and a continuous (DV) variable.
I found this method very useful and want to cite a peer-reviewed source. So far, I found the following:
(1) Salkind, Neil, ed. Encyclopedia of Research Design. Sage, 2010. pp. 422-425
https://methods.sagepub.com/Reference/encyc-of-research-design/n133.xml
(2) Witte, Robert S, John S. Witte. Statistics. Wiley, 2017. pp. 308-311
https://www.google.com/books/edition/Statistics/QpBEDwAAQBAJ?hl=en&gbpv=1&dq=S.+Witte.+Statistics&printsec=frontcover
However, the references above are about how to interpret ETA squared without discussing ways to fit categorical variables.
What I am looking for is something like this:
Cohen, Yosef, Jeremiah Y. Cohen. Statistics and Data with R: An Applied Approach Through Examples. Wiley, 2008.
https://www.google.com/books/edition/Statistics_and_Data_with_R/_N-W9beebKcC?hl=en&gbpv=1&dq=Statistics+and+Data+with+R&printsec=frontcover
The problem with this book is that it does not discuss ETA-squared as a measure of strength of association between a categorical independent variable and a continuous dependent variable.
I have searched more than 20 academic books but no success yet. I am new to this field, so maybe I am looking at wrong places. A non-peer-reviewed source that might be close to the method described by @Silverfish (users/22228) is the following:
http://www.sthda.com/english/articles/40-regression-analysis/163-regression-with-categorical-variables-dummy-coding-essentials-in-r/
Answer: Here is how you could have answered yourself: Some searching (install package sos in R, call ???"eta.sq" and look at the output) shows that there is a function eta.sq in package misty.  Install that, call ?eta.sq and you will find

References:
 Rasch, D., Kubinger, K. D., & Yanagida, T. (2011). _Statistics in
 psychology - Using R and SPSS_. New York: John Wiley & Sons.

Check that out on amazon.com or elsewhere, and it does indeed discuss eta squared. It indeed talks about it as Fishers eta squared, so this was maybe introduced by RA Fisher!  Searching for that leads to this book: Encyclopedia of Research Design, maybe a better reference.
Comment: Thank you very much! This is perfect. I found a relevant chapter on pp.330-335 in Rasch's book. I didn't know about the SOS package, and it's also wonderful! I also called ???"etasq" and found more packages, which include multiple references. I spent several weeks to find references regarding this method. Your answer really made my day!


Conclusion about Zeros of a polynomial ,when sum of it's coefficients is zero

Question: I have a polynomial of the form:
$$\sum_{m=0}^k\frac{(-1)^{m+1}(4k-2m)!x^{2k-2m}}{m!(2k-m)!(2k-2m+1)!}$$
or identically:
$$\sum_{m=0}^k\frac{(-1)^{m+1}(4k-2m)!(x^{2})^{k-m}}{m!(2k-m)!(2k-2m+1)!}$$
where we can see that the sum of the coefficients is always zero.
Now , my question is that :
what can be concluded from this (i.e sum of the coefficients being zero)  about zeros (roots) of the polynomial?
edit:
except the fact that 1 is a root.
Answer: The sum of the coefficients is zero if and only if $1$ is a root of the given polynomial.
Comment: right, but I mean more than that. (Indeed , $x$ here is $cos(\alpha)$ and other solutions( other than 1 and 0) are of interest to me.
Comment: from the fact that sum of coefficient is 0 you may conclude only that because of "if and only if"


GLM binomial with one category containing zero patients

Question: I have a data set where I performed a GLM in order to see what effect certain radiological parameters had on the end result.
<code>Call:
glm(formula = result ~ age_over_under_60 + Sex +
    radiological_parameter_1 + radiological_parameter_2 + radiological_parameter_3 +
    radiological_parameter_4 + radiological_parameter_4, family = "binomial",
    data = my_data)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-2.11049  -0.45486  -0.38344   0.00015   2.39896

Coefficients:
                                Estimate Std. Error z value Pr(>|z|)
(Intercept)                     -2.81958    0.61284  -4.601 4.21e-06 ***
age_over_under_60                0.52001    0.55278   0.941  0.34686
Sex                              0.08305    0.66897   0.124  0.90120
radiological_parameter_1         2.83452    0.67390   4.206 2.60e-05 ***
radiological_parameter_2         1.16334    1.13437   1.026  0.30511
radiological_parameter_3        -0.27375    0.58737  -0.466  0.64117
radiological_parameter_4        17.38227 1215.31571   0.014  0.98859
radiological_parameter_5         1.85178    0.62290   2.973  0.00295 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 162.43  on 137  degrees of freedom
Residual deviance: 101.48  on 130  degrees of freedom
  (7 observations deleted due to missingness)
AIC: 117.48

Number of Fisher Scoring iterations: 16
</code>
The data for parameter 4 is striking me as weird as 8 out of 8 patients who fulfilled this parameter had bad end results meanwhile 30/130 who did not fulfil it had bad results.
Can anyone help and explain the high p-value and possibly what I could do differently?
Thanks!
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Forget the p value.  Anything else strike you as weird?  The standard error and log odds ratio are enormous.
I take it that the variable is binary. If so I feel confident saying you are suffering from quasi/complete separation.  You'd be best to search this site for that term to find ways to combat this.


Jquery Selector em Tabela com bootstrap

Question: Tenho uma tabela em bootstrap e numa das colunas tenho um botão de gravar escondido.
Queria ao clicar no input existente, que esse botao aparecesse.
Ja estou farto de tentar fazer diversos metodos de selectores mas ate agora nenhum funcionou.
O que tenho actualmente é assim:

   5103

   1961-0679x
    Abraçadeira união escape
   Acessórios escapes cross

      <input class="form-control input-sm text-right" type="text" placeholder="19.99" value="19.99">

      <button class="btn btn-success btn-xs hidden btnGravar">Gravar</button>

No Jquery tenho:
$(function(){
    $(".input-group input").click(function(){
        $(this).select();
        $(this).next().next().removeClass('hidden');
    });
});

Mas não mostra o botão que esta hidden.
Aguma ajuda?
Answer: Você pode usar as funções "focusin" e "focusout":

$(function(){
    $(".input-group input").focusin(function(){
        $(this).parent().find('.btnGravar').removeClass('hidden');
    })
.focusout(function(){
        $(this).parent().find('.btnGravar').addClass('hidden');
    });
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

     5103

     1961-0679x
      Abraçadeira união escape
     Acessórios escapes cross

        <input class="form-control input-sm text-right" type="text" placeholder="19.99" value="19.99">

        <button class="btn btn-success btn-xs hidden btnGravar">Gravar</button>

Answer: Eu costumo ir para o parent() e depois dar um find() no elemento que precisa.

$(function(){
    $(".input-group input").click(function(){
        $(this).select();
        $(this).parent().find('.btnGravar').removeClass('hidden');
    });
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

     5103

     1961-0679x
      Abraçadeira união escape
     Acessórios escapes cross

        <input class="form-control input-sm text-right" type="text" placeholder="19.99" value="19.99">

        <button class="btn btn-success btn-xs hidden btnGravar">Gravar</button>

Jquery Selector em Tabela com bootstrap


pygame sound format differences

Question: For playing my sounds I have this working code:
<code>import pygame

pygame.init()
pygame.mixer.pre_init(44100, 16, 2)
screen = pygame.display.set_mode([100,100])
print(pygame.mixer.get_num_channels(),"cannels")
sounda = pygame.mixer.Sound("track.mp3")
print("Length",sounda.get_length())
print("Volume",sounda.get_volume())
channela = sounda.play()
while channela.get_busy():
   pygame.time.delay(100)
pygame.quit()
</code>
You can see I am mostly using .mp3 files.
But my problem is that it can play some sounds but others result the error which says that the sound can not be loaded. Are there any differences between mp3 files and do you know how to solve this problem?
Thanks in advance
Comment: With mixer.music I can play the sounds without any problems.
Answer: So I have found out there can be differences in one sound format so that pygame has problems with it. With the program ocenaudio I can manipulate and save my sounds in multiple types of the .wav format. Pygame can deal with one of them.
But loading music has never been a problem...
Answer: If Pygame is not loading your audio, there are 3 possibilities.
Possibility 1:
Pygame cannot find your file.  When saying the name of a file, make sure either the sound file is in the same directory as your program file, or you can give the entire file path instead (like '/home/person/sound.mp3', instead of just 'sound.mp3'.)
Possibility 2:
Your file is the wrong format.  Though it is called .mp3, it may be a different type.  Try using an audio conversion program.
Possibility 3:
Pygame just plain cannot read the file.  Pygame works best with .ogg files, but sometimes has issues with other types.  Just use an audio conversion program to convert it to .ogg, and it might work.
If none of these work, giving an exact error message would be appreciated.

pygame sound format differences


angular date time model gives 1 day less

Question: When i am binding date with angular model, the model variable gives value which is 1 day less from i actually selected, please see the code
<!DOCTYPE html>

         <input type="date" ng-model="ddd">
         {{ddd}}

Comment: IT could be the issue of timezone. Check if your filter set default or not.
Answer: Actually it is returning the correct date. To display correctly do
<input type="date" ng-model="ddd">
     {{ddd | date:'MM/dd/yyyy'}}

Here {{ddd}} shows just the date object. You have to filter it into correct format to display correctly


Does the product of N independent poisson distributions approach a gaussian distribution as N becomes large?

Question: This paper I'm reading claims that the answer to my question is yes, but I'm having trouble finding another source.

I know that a poisson distribution tends to a normal distribution as the mean becomes large, and that the product of independent poissons has a mean equal to the product of the independent poisson means, which could become large as N becomes large, but I don't think the product of poissons is itself poisson so I'm not sure the using the normal limit is appropriate.
Answer: Answering the question in title: no.
The product of positive variables tend to converge to log-normal distribution, since in log space we have central limit theorem. However, that is not the case for Poisson distribution, because it always has a finite probability of zero. So as the $N\to\infty$  the probability that one of the multiplicants is zero and this nullifies the whole product goes to $1$.
However, the paper states something different. It's not about convergence of Poisson distributions, it's about the convergence of posteriors, which is Gamma-distribution. And it's not about multiplication of random variables, but rather multiplication of distributions (otherwise you would have seen a lot of convolutions).
Comment: Is [this](http://www.math.wm.edu/~leemis/chart/UDR/PDFs/GammaNormal1.pdf) what you want?
Comment: Marked as answered due to answering what I actually asked. While I've got your attention, do you know any sources I could use to find the mean & variance of the gaussian that results from multiplying gamma distributions with given means and variances?
Comment: That is what I asked for, yes. Looking at it though, I'm realizing I asked the wrong question (again). What I really want is the mapping from the poisson means to the gaussian mean & variance in the segment of the paper referenced in my original question. As in, what are the mean & variance of the converged-to gaussian as a function of the poisson means $f_i(s)$, $i=1...N$


Two players are trying to figure out the binary code

Question: Two players guess code that is hidden in $2^n$ ($n\geq2$, n $\in$ $\Bbb N$) digits that each contain either 0 or 1 which makes a binary code that consists of zeros and/or ones, for example, '0010' is binary code, that has $2^2$ digits that consist only of 0's and 1's.
There are two players - first player and second player. The first player starts and guesses the digit. The second player only knows if the digit that was chosen by the first player contains 0 or 1 but the second player do not know which digit the first player chose. There are two rules that have to be followed:
A) If a player chooses digit and guesses right, he can choose three consecutive digits that contain one of the digits that he guessed this turn and send to other player those three consecutive digits as partial information.
B) If a player chooses digit and guesses wrong, he can choose two consecutive digits that contain one of the digits that he guessed this turn and send to other player those two consecutive digits as partial information.
After first player followed rules A and B, it is second player's turn and he does the same: guesses the digit, sends partial information by the rules A and B, but the difference is that the second player becomes the one that is sending information and the first player is the one who is receiving it. Then it is first player's turn again, then the second player's turn and so on until one of the players can tell whole code containing of $2^n$ digits of zeros or ones, but the player is considered to know the code when he knows all the digits for sure.
It seems to me that if we could find out strategy for trivial n=2 or n=3 we could just use the mathematical induction and prove that strategy works for all natural numbers n. Also, for clarification, by default first and last digit is not connected (the digits are not in a closed circle) - it would make the strategy more difficult or even impossible to find.
I probably should make myself more clear about the task.
Let us say we have 4 digits and the exact code is '0100'.
(I) First player guesses that 2nd digit is '1'.
Public info: the first player guessed right about the '1'.
Private info for first player: 2nd digit is '1'.
Public info: either 1st, 2nd or 3rd is the digit containing '1'
(first player guessed right so he chose 3 consecutive digits this way).
(II) Second player guesses that 1st digit is '1'.
Public info: the second player guessed wrong about the '1'.
Private info for second player: 1st digit is '0'.
Public info: either 1st or 2nd is the digit containing '0'
(it is forced to reveal this info because 1st digit is only near the 2nd)
(I) Since first player knew that 2nd is '1', so he already knows that 1st is '0' from the public info.
First player guesses that 4th digit is '0'.
Public info: the first player guessed right about the '0'.
Private info for first player: 4th digit is '0'.
Public info: either 2nd, 3rd or 4th is the digit containing '0'.
(II) Second player knows that 1st one is '0', either 2nd or 3rd is '1', either 2nd, 3rd or 4th is '0'.
Basically, second player knows almost nothing.
Public info: the second player guessed wrong about the '1'.
Private info for second player: 3rd digit is '0'.
Public info: either 2nd or 3rd is the digit containing '0'.
(I) Since the first player knew that 2nd digit contains '1', he knows then that 3rd contains '0'.
But he figures out the code that is '0100' and the first player wins.
Now, talking about the quantity of digits. $2^n$ is the reason because of forward-backward induction idea that involves such numbers because we have to first assume that from every natural number n it follows for $2^n$ is true and then we have to prove that if for all n is true then for all n-1 is also true.
It also is related to binary codes, so why not stick to $2^n$.
Comment: This is somewhat unclear. When players "guess a node" or "send a node", are they guessing/sending the node index or the value of the bit(s)? Examples would help.
Comment: I second the comment of @Karl.  This seems like a very interesting problem to work on.  However, I request that you provide several clear examples, to illustrate fully what you have in mind.  I suggest that you have one example with $2^1$ nodes, one example with $2^2$ nodes, and one example with $2^3$ nodes.  There is a separate question.  If I read the posting correctly, there seems to be the constraint that the number of nodes must be some element in $\{2,4,8,16,32, \cdots\}.$  **Why**?  Why is it necessary to disallow having (for example) $3$ nodes, or $6$ nodes?
Comment: Good evening, I tried to explain myself by editing the task.
Answer: This is not an answer but an attempt to rewrite the task/rules in a simpler form. I think there are some translation issues. OP, if you agree this is useful, please feel free to copy/paste, and I'll delete later.

The rules are thus: Two players are attempting to discover a binary code of $2^n$ bits, unknown to either. Each turn, one player is active and the other is passive. A turn plays as follows:

The active player chooses a bit, and guesses whether it is $0$ or $1$. The game system tells the active player whether their guess is correct or not.
The active player then chooses several consecutive bits containing the guessed bit: they choose three if they guessed correctly, two otherwise.
The game system then tells the passive player the true value of the guessed bit and the two or three bits selected by the active player.
This ends the turn: the active player becomes passive and vice versa.

The end result of a turn, in terms of revealed information, is that the active player learns the true value of one bit, and the passive player learns that one of two (or three) consecutive bits has that value. The game ends when one player can determine the code correctly; that player wins.
As an example: the hidden code is $0100$. We will call the players X and Y, and label the bits $ABCD$.

Turn $1$X: X guesses that bit $B$ is $1$, and is told this is correct. X chooses to reveal that one of the bits $A,B,C$ is $1$.
Turn $1$Y: Y guesses that bit $A$ is $1$, and is told this is incorrect. Y has no choice but to reveal that one of the bits $A,B$ is $0$.
X now knows the code is $01CD$. Y knows the code is $0BCD$, where either $B$ or $C$ is $1$.
Turn $2$X: X guesses that bit $D$ is a $0$, and is told this is correct. X has no choice but to reveal that one of the bits $B,C,D$ is $0$.
Turn $2$Y: Y, lacking information, guesses that bit $C$ is a $1$, and is told this is incorrect. Y chooses to reveal that one of the bits $B,C$ is $0$.
Y now knows that the code is $010D$. But X now knows the entire code, and wins.

The question is: How can one develop a strategy for this game, for larger $n$?


What is the real-world speed (stream, latency) of USB3 and USB2 over SATA?

Question: What is the real-world speed (stream, latency) of USB3 and USB2 over SATA?
It is easy to find streaming speed comparisons, but more difficult to find latency comparisons in the same setup.
Answer to follow in a momemt.
Answer: On an ASUS Z87 motherboard with an intel i7-4770K with gobs of memory and ubuntu 14.10, the rough performance comparison of a first-gen Intel 80gb SSD drive (X25-M), using the ioping utility on an ext4 filesystem, the following is a rough estimate of read-performance:
SPEC:  250MB/sec,
SATA:  240MB/sec, 1000 iops, 1ms latency
USB3:  190MB/sec, 750 iops, 1.3ms latency
USB2:  43MB/sec, 200 iops, 6ms latency

Of course, this will be different for different setups.  The point of this table was to add some latency and iops stats in a non-theoretical comparison.  The rest below are merely details on the above.

More Details follow
All Tests Run On An Intel 80GB First-Gen Drive, X25-M.
Direct-Access     ATA      INTEL SSDSA2M080 02HA PQ: 0 ANSI: 5

Intel Posted X25-M Drive Specs:

Read: 250MB/s
Write: 70MB/s
Latency Read: 65us
Latency Write 85us
IOPS: read=35k.  write=300 to 6600

Motherboard: Asus Z87 Gryphon w/ USB 3.0 port.

----------------------------------------------------------------

on the SATA bus:

# ioping -RL .
--- . (ext4 /dev/sdb1) ioping statistics ---
2.8 k requests completed in 3.0 s, 952 iops, 238.0 MiB/s
min/avg/max/mdev = 999 us / 1.1 ms / 2.1 ms / (85 us)

# ioping -RL .
--- . (ext4 /dev/sdb1) ioping statistics ---
2.8 k requests completed in 3.0 s, 956 iops, 239.2 MiB/s
min/avg/max/mdev = 1.0 ms / 1.0 ms / 7.6 ms / (149 us)

----------------------------------------------------------------

on the USB 3.0 superspeed bus:

Bus 003 Device 011: ID 152d:2509 JMicron Technology Corp. / JMicron USA Technology Corp. JMS539 SuperSpeed SATA II 3.0G Bridge

# ioping -R .
--- . (ext4 /dev/sdd1) ioping statistics ---
11.3 k requests completed in 3.0 s, 3.8 k iops, 14.8 MiB/s
min/avg/max/mdev = 247 us / 264 us / 4.6 ms / (49 us)

# ioping .
4.0 KiB from . (ext4 /dev/sdd1): request=1 time=1.6 ms
4.0 KiB from . (ext4 /dev/sdd1): request=2 time=333 us
... ^C
--- . (ext4 /dev/sdd1) ioping statistics ---
12 requests completed in 11.5 s, 2.3 k iops, 9.1 MiB/s
min/avg/max/mdev = 290 us / 427 us / 1.6 ms / (344 us)

# ioping -RL .
--- . (ext4 /dev/sdd1) ioping statistics ---
2.2 k requests completed in 3.0 s, 748 iops, 187.0 MiB/s
min/avg/max/mdev = 1.3 ms / 1.3 ms / 3.6 ms / (96 us)

----------------------------------------------------------------

on the USB 2.0 high-speed bus:

# ioping -R .
--- . (ext4 /dev/sdd1) ioping statistics ---
509 requests completed in 3.0 s, 170 iops, 42.6 MiB/s
min/avg/max/mdev = 5.8 ms / 5.9 ms / 6.3 ms / (67 us)

# ioping -RL .
--- . (ext4 /dev/sdd1) ioping statistics ---
510 requests completed in 3.0 s, 170 iops, 42.7 MiB/s
min/avg/max/mdev = 5.8 ms / 5.9 ms / 6.3 ms / (42 us)

----------------------------------------------------------------

USB3 Bridge Device

Bus 003 Device 011: ID 152d:2509 JMicron Technology Corp. / JMicron USA Technology Corp. JMS539 SuperSpeed SATA II 3.0G Bridge
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.10
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  idVendor           0x152d JMicron Technology Corp. / JMicron USA Technology Corp.
  idProduct          0x2509 JMS539 SuperSpeed SATA II 3.0G Bridge
  bcdDevice            1.00
  iManufacturer           1 JMicron
  iProduct               11 Usb production
  iSerial                 3 00A123456A8D
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           32
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          4 USB Mass Storage
    bmAttributes         0xc0
      Self Powered
    MaxPower                2mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass         8 Mass Storage
      bInterfaceSubClass      6 SCSI
      bInterfaceProtocol     80 Bulk-Only
      iInterface              6 MSC Bulk-Only Transfer
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x02  EP 2 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0
Binary Object Store Descriptor:
  bLength                 5
  bDescriptorType        15
  wTotalLength           42
  bNumDeviceCaps          3
  USB 2.0 Extension Device Capability:
    bLength                 7
    bDescriptorType        16
    bDevCapabilityType      2
    bmAttributes   0x00000002
      Link Power Management (LPM) Supported
  SuperSpeed USB Device Capability:
    bLength                10
    bDescriptorType        16
    bDevCapabilityType      3
    bmAttributes         0x00
    wSpeedsSupported   0x000e
      Device can operate at Full Speed (12Mbps)
      Device can operate at High Speed (480Mbps)
      Device can operate at SuperSpeed (5Gbps)
    bFunctionalitySupport   1
      Lowest fully-functional device speed is Full Speed (12Mbps)
    bU1DevExitLat          10 micro seconds
    bU2DevExitLat          32 micro seconds
  Container ID Device Capability:
    bLength                20
    bDescriptorType        16
    bDevCapabilityType      4
    bReserved               0
    ContainerID             {00010203-0405-0607-0800-000000000000}
Device Status:     0x0001
  Self Powered


How can I make these strings into decimals using map (GAS)?

Question: I'm trying to make sure that the resulting column will onlu contain numbers, but it keeps coming as string.
function moveColsWesbanco() {
  var ss = SpreadsheetApp.getActive();
  var sourceSheet = ss.getSheetByName('Sheet1');
  var destSheet = ss.getSheetByName('New Entry');
  var debitsCredits = sourceSheet.getRange('A7:D');
  var values = debitsCredits.getValues();
  let amounts2 = values.filter(o => o[0] != '').map(e => e[2] != '' ? e[3] = Number.parseFloat(e[2]) : Number.parseFloat(e[3]));
  let allTypes = [];
  for (val in amounts2) {
    allTypes.push(typeof val)
  };
  Logger.log('Types within it: ' + allTypes)
  return;
}

Here are the logs:

So...I wonder what I'm missing here. Thank you!
Answer: I think that when "for in" is used like for (val in amounts2) {}, val is the index. And, it's the string type. I think that this is the reason of your issue. In this case, how about using "for of" as follows?
Modified script:
for (var val of amounts2) {
  allTypes.push(typeof val)
};

References:

for...in
for...of
Comment: @santosOnit Thank you for replying. It's no problem. As the additional information, for example, when you want to retrieve `val` as the index of the number value, you can use. `for (var val = 0; val < amounts2.length; val++) { ,,, }` In this case, `val` is the index of the number type. Or, in your situation, I think that `map` can be also used. It's like `var allTypes = amounts2.map((value, index) => ({[value]: typeof value, [index]: typeof index}))`. In this case, both value and index can be retrieved.
Comment: Thanks! I'm still running into these silly mistakes.


Intonation when playing with a click track on one ear

Question: Recently I participated in a project where we played film music live with the film playing. We got an earbud that played the click track for one ear so we stayed in time.
Now this was an amateur project and my first time playing to a click track. It seemed to me that the click was more distracting than helpful. I started out by kind of trying to ignore it as much as I can because I had trouble hearing the orchestra clearly. As we practised more I got somewhat used to it and saw the advantages it brings, especially if you play along a film where you absolutely need to stay in time for the whole thing.
There was one issue I had until the very end though. I wasn't able to adjust the intonation as well as I usually would. I knew when the intonation was off but I was simply not able to know the cause. I usually can tell if I'm too high or low but with the earbud in I felt lost.
I put the earbud in my right ear and I was sitting slightly to the right of the orchestra so my left ear was directed more or less at the middle of the orchestra.
With some practise it got better but it was nowhere near playing without the click.
How do the pros handle this? Is it just a lot more practise with clicktracks or do they take out the earbuds for parts where intonation is very important? I imagine that intonation is much less of a problem at a certain level of play but I assume they still need to adapt their playing during a piece.
Comment: Pretty sure the pros follow the conductor, who follows the movie visually. Did you not have a conductor?
Comment: Yes we had one but he insisted on having (some) players have one too.
Answer: There are two problems here.
Firstly, if you find the click distracting, it's too loud. You need to find a level where you can hear the click without it getting in your way. Often that level is quiet enough that you can't hear the click when the orchestra is playing at full volume. If everybody is playing, but out of time, there's no way you can fix it by yourself.
Secondly, earbuds are not optimal for woodwind players because closing off the ear canal affects the way you hear sound resonance from your mouth. For a demonstration of the effect, try closing one ear with your finger and speaking. This adversely affects tone and intonation. Open headphones (just on one ear) are much better, particularly the type that just sit on the outside of the ear without enclosing it.
Answer: I suspect that earbuds themselves are not the problem. You are either being distracted by the click track or you are having difficulty hearing yourself.
If the earbuds had the click track overlaid on a monitor is suspect you would not have have been so lost. I experience something similar performing live with a band. If I could barely hear myself, getting intonation right was incredibly frustrating. I could tell I was off but too late to do anything about it.
On the other hand if the click track itself is distracting you then it is psychological and you just need to practice to get used to it. However I doubt that is the case. A click track is basically like a metronome and we all regularly practice with them right?
Next time if you are one of the specially selected people to listen to the click track ask if you can get your sound piped through as well. I think it would help you a lot.
Answer: Like everything in music, what you repeat, you learn. Intonation is an ongoing battle for anyone performing in large groups, especially with varied instruments. If you feel uncomfortable doing ANYthing, try recreating it in your practice time.
In this case, you could practice with a tuning track through speakers while listening to a metronome in earbuds. The closer you can get to creating the performance environment while practicing, the better off you'll be!
Another tip: Try to focus on how intonation feels in your body....without relying solely on your ears.
Answer: If sound is heard in only one ear it's perceived 10 dB more quiet in comparison to the same sound in both ears. That's a large difference. In order to hear the click in one only ear you need to have it 10 dB louder, which might feel weird, distract you, and in extreme case cause hearing damage.
Headphones for both ears would work better. If the other instruments become too quiet due to attenuation by the headphones, you also may need to have them mixed with the click track.


Algebra proof within relation problem

Question: I need to show an equivalence relation on $ℕ$ defined as follows:
$x$ ~ $y$ ⇔ $x \times y$ is a square
Reflexivity: $x \times x$ is a square, so $x$ ~ $x$, so ~ is reflexive
Symmetry: $x$ ~ $y$ implies $y$ ~ $x$, $x\times y$ is a square, so is $y \times x$
But for transitivity I need to show that if $xy$ and $yz$ are both squares, then $xz$ is also a square.
So I did this:
$xy = a^2$ and  $yz = b^2$, then $xz = \frac{a^2\times b^2}{y^2}$ and $xz = (\frac{ab}{y})^2$
But I don't think this works because there is a fraction. How else can I show that $xz$ is a square?
Comment: square of fraction + integer = square of integer
Answer: $$ xz y^2 = a^2 b^2 $$
So we know $a^2 b^2$ is divisible by $y^2$. In other words, $\dfrac{ab}{y}$ is an integer. So your solution is correct.
Answer: Let $x = \prod_{i=1}^n p_i^{c_i}$, $y = \prod_{j=1}^n p_j^{d_j}$ and $z = \prod_{k=1}^n p_k^{f_k}$, where $P = \{p_i \mid 1\leq i \leq n\}$ is a set of primes containing the primes that divide any of $x$, $y$, or $z$.  Then, since $xy$ and $yz$ are squares, writing the factorizations of $xy$ and $yz$ into primes in $P$, we obtain the relations \begin{align*}
c_i + d_i &\cong 0 \pmod{2}  \\
d_i + f_i &\cong 0 \pmod{2}
\end{align*}
for each $i \in [1,n]$.  Then \begin{align*}
(c_i + d_i) + (d_i + f_i) &\cong 0 \pmod{2}  \\
c_i + 2d_i + f_i &\cong 0 \pmod{2}  \\
c_i + f_i &\cong 0 \pmod{2}  \text{,}
\end{align*}
which says $xz$ is a square.

Algebra proof within relation problem