How do I interact with a child process pretending to be a terminal?

Question: I'm trying to interact with an NCURSES program.
As an example I'm using GNU Screen and run aptitude inside. (you could try it with mc instead.)
The program below starts a screen session with -x to connect to my session.
I want to navigate by pressing Arrow-down and Arrow-up.
If I send 'q' for quit I see a box pop up in my other screen session.
What do I need to do to get special keys like arrow keys working?
It currently seems to ignore the VT102 sequence I'm sending.
from twisted.internet import protocol, reactor

class MyPP(protocol.ProcessProtocol):
    def connectionMade(self):
        reactor.callLater(1.0, self.foo)

    def foo(self):
        self.transport.write('\033[B')

    def processExited(self, reason):
        print "processExited, status %s" % (reason.value.exitCode,)

    def outReceived(self, data):
        print data

    def errReceived(self, data):
        print "errReceived!", data

pp = MyPP()
command = ['screen', '-x']
reactor.spawnProcess(pp, command[0], command, {'TERM':'xterm'}, usePTY=True)

reactor.run()

UPDATE:

Ted told me walking in the command history with ESC [ A (up) and ESC [ B (down) works with bash.
Wondering why in aptitude it doesn't I've changed TERM=xterm to TERM=ansi which fixes it. Why xterm doesn't work still puzzles me.
Comment: That is pretty obvious, but have you diffed the terminfo for ansi and xterm?
Comment: This is a somewhat confusing question - are you asking how to send control keys, such as Arrow-down, across the network over Twisted?
Comment: Not across network. spawnProcess starts a process locally and wires up file descriptors so you can talk to it.
Comment: Is the ESC B in `foo` meant to be the down-arrow?  Down-arrow generates ESC [ B, not just ESC B.
Comment: @torek I updated it to ESC[B. Still doesn't work.
Comment: Can you reproduce the problem with a program that uses just readline?
Comment: @yaccz bash uses readline. I just found out that actually works. I still have a problem with TERM=xterm. (see update)
Answer:
I've changed TERM=xterm to TERM=ansi which fixes it. Why xterm doesn't
  work still puzzles me.

Using Ubuntu 13.04, it looks like the ansi and xterm control codes aren't quite the same.
$ infocmp ansi | grep cud
        cr=^M, cub=\E[%p1%dD, cub1=\E[D, cud=\E[%p1%dB, cud1=\E[B,
        kcud1=\E[B, kcuf1=\E[C, kcuu1=\E[A, khome=\E[H, kich1=\E[L,

$ infocmp xterm | grep cud
        cud=\E[%p1%dB, cud1=^J, cuf=\E[%p1%dC, cuf1=\E[C,
        kcub1=\EOD, kcud1=\EOB, kcuf1=\EOC, kcuu1=\EOA,

...so it looks like you need to send the string '\033OB' to emulate a down arrow with xterm.
The following code works for me...
import subprocess
import os
import time

# Set TERM=xterm in case it isn't already
os.environ['TERM'] = 'xterm'

# Spawn aptitude
p = subprocess.Popen('aptitude', stdin=subprocess.PIPE)

# Wait for a bit to let it load from cache
time.sleep(5)

# Control it using xterm control codes
p.stdin.write('\033OB') # arrow down
time.sleep(1)
p.stdin.write('\033OB') # arrow down
time.sleep(1)
p.stdin.write('\033OA') # arrow up
time.sleep(1)
p.stdin.write('\033OA') # arrow up
time.sleep(1)
p.stdin.write('q')      # quit
time.sleep(1)
p.stdin.write('y')      # confirm

...although it screwed up my terminal after completion, so I had to do...
$ stty sane

...to get it working again.

Update
Just found what might be an easier way to determine the correct control codes. If you load vi, go into insert mode, then press CTRL-V followed by the key you want to emulate, it shows the literal string sent from the terminal.
For example...
Down Arrow: ^[OB

Page Up: ^[[5~

...where ^[ is CTRL-[, i.e. '\033'.
Answer: A good method to obtain codes for particular terminal functions is using the tput command, for some particular terminal type with -T option.
In Python, use the curses module to obtain correct codes:
from curses import *
setupterm('xterm')

key_up = tigetstr("kcuul")
key_down = tigetstr("kcudl")

You can read about available capabilities by launching man terminfo. The example above may need savetty() before setupterm and resetty() after you obtain the key codes you are interested in. Otherwise, your terminal may be left in a bad state. In C it was good to have that in some exit handler as well, to reset terminal on error, but the Python module may handle that in its own.
This method, in contrast to hardcoding the terminal codes, has the advantage of being portable between systems, where terminfo for xterm may be different than that on current Linux distributions.
Answer: Perhaps something like Pexpect might by useful here:
https://pypi.python.org/pypi/pexpect
Its a python implementation of Expect, which basically watches input and based on patterns performs actions as if a person was sitting there interacting with the app.
Comment: I should have a closer look at pexpect. I'm interested in monitoring patterns in the vt102 codes. I'm now writing my own pattern matching, but I'd be interested to see if I can use pexpect somehow.


DropDownList lose index after PostBack

Question: I have a dropdown which I fill with data from a SQL server.
I fill the dropdown dynamically in the Page_Init() Event.
Depending on the Value, a ListItem is selected.
Now the problem is, that when I select another Item in the dropdown, that after the postback the selection is reset to the first item in the dropdownlist.
This here is a basic version of my code which does not work:
        ArrayList AD_Group_Members = ActiveDirectory.GetMemberOfGroup("AD-Group");
        ArrayList ListMachines = SQLQuery.Read("Database", "SELECT idVM, RandomString, Computername, Owner, FROM VM ORDER BY Computername");

        for (int i = 0; i < ListMachines.Count; i++)
        {
            String RandomString = ((Hashtable)ListMachines[i])["RandomString"].ToString();
            String Owner = ((Hashtable)ListMachines[i])["Owner"].ToString();
            DropDownList DropDownList_Owner = new DropDownList();
            DropDownList_Owner.ID = "DropDownList_Owner_" + RandomString;
            DropDownList_Owner.Width = Unit.Percentage(95);
            DropDownList_Owner.AutoPostBack = true;
            DropDownList_Owner.EnableViewState = true;
            DropDownList_Owner.SelectedIndexChanged += DropDownList_Owner_SelectedIndexChanged;
            Div_Test.Controls.Add(DropDownList_Owner);
            for (int y = 0; y < AD_Group_Members.Count; y++)
            {
                ListItem ListItem = new ListItem();
                ListItem.Value = Owner;
                ListItem.Text = ((Hashtable)AD_Group_Members[y])["GivenName"].ToString() + " " + ((Hashtable)AD_Group_Members[y])["Surname"].ToString();
                if (((Hashtable)AD_Group_Members[y])["Username"].ToString().Equals(Owner))
                {
                    ListItem.Selected = true;
                }
                DropDownList_Owner.Items.Add(ListItem);
            }
        }

Where is the issue in my code, that it doesn't work but the example.
Thank in Advance
Answer: You have to populate your dropdownlist under this condition on pageload.
Because on every post back your ddl is populated again and loses its selected index.
if (!IsPostBack)
{
    //PopulateYourDDL here
}

Comment: Ok, that helped me, but now I have following problem:
After I changed the selected Item "User A" to "User B", in the SelectedIndexChanged Event is still the "User A" as SelectedValue
Comment: quote your populate function and remove unnecessary code from your question.
Comment: I tried it now in my real code and there is now the problem, that after the Change of the selected Item all items are away and the SelectedIndexChanged Event does not trigger.Request clarification or suggest improvements.
Comment: store your selectedIndex in a hidden field and on postback reselect that selected index. `Or` debug and see where it is selecting value `A`
Answer: You filled dropdown in Page_Init() which gets called in every postback and refill your dropdown and hence loses selectedindex.So you have to fill your dropdown inside !ispostback block
if (!IsPostBack)
{
   //fill your dropdown here
}

Answer: I think the you should have unique values for the dropdown. Also as you have duplicate values in data value field the problem is occurring. It is looking for the first match and selecting it. You could try to fabricate the values which you could uniquely identify. Something like below:
COLUMN_NAME  DATA_TYPE
a            a_decimal
b            b_decimal
c            c_decimal
d            d_int
e            e_int
f            f_varchar
g            g_varchar
h            h_varchar
i            i_varchar
j            j_varchar

Check out this Useful Source!!!
I hope it helps!!! Have a close look at those comments in the accepted answer section !!!
Also avoid using SelectedIndex_Changed() functions while dealing with Dynamically generated Web controls. Bind the DropdownList under Page_Init() or Page_PreInit(). If you want to perform some functions upon DropDownlist Selection Check out this! to determine the WebControl ID which is triggered and then perform an unique function in the Page_PreInit() or Page_Init().

DropDownList lose index after PostBack


Sum law of limits

Question: I know that the sum law of 2 limits
$$  \lim_{x \to \infty} f(x) = A \quad \text{and} \quad  \lim_{x \to \infty} g(x) = B \quad \longrightarrow \quad \lim_{x \to \infty} f(x) + g(x) = A+B$$
applies if both A and B are constants, or if one of them is constant and the other it $\pm \infty$,
but what happens if both of them are $\pm \infty$?
Are $(\infty \pm \infty)$ indetermint? In this case is the sum law useless?
Comment: The problem is that, in the real numbers, infinities are merely directional and not actually values.  Therefore, while $\infty + \infty \to \infty$ and $-\infty -\infty \to -\infty$, $\infty - \infty$ is indeterminate.  If you were using hyperreal numbers (rare), then you can often make sense of infinite elements.
Answer: If both $A$ and $B$ are $\infty$ then the implication is still true with $A + B = \infty$.
If however $A = -\infty$ and $B = \infty$ then there is no such theorem. The last limit could be anything or it might not exist in that case. For example:

If $f(x) = -x + \pi$, $g(x) = x$, then $\lim_{x\to\infty} f(x) + g(x) = \pi$.
If $f(x) = -x$, $g(x) = x^2$, then $\lim_{x\to\infty} f(x) + g(x) = \infty$
If $f(x) = -x + \sin x$, $g(x) = x$, then $f(x) + g(x)$ doesn't converge.

Sum law of limits


Adding background color to table rows

Question: I was wondering if it is possible to change the background color of a table row.
I want to display certificate files, and if that certificate is going to expire in longer than 30 days the color green would be good. If it is less then 30 days color orange and if it's expired color red.
I tried finding it on the internet but I can't find anything like this.
This is how my current column data looks like.
<code>'c3' => array(
        'data' => array('#type' => 'item', '#markup' => t('@uploaded', array('@uploaded' => date('d-m-Y', $val->upload_date)))),
    ),
</code>
I already tried adding '#class' => array('bgcolor' => '#ffffff'), or just 'bgcolor' but that doesn't work.
Thanks in advance!
Complete code
<code>$qry = db_select('push_notifications_api', 'n');
$qry->join('push_notifications_certificates', 'u', 'n.ios = u.cert_id');
$cert_table = $qry
->fields('n', array('app_name', 'ios'))
->fields('u', array('cert_id', 'cert_name', 'upload_date', 'expiration_date'))
->OrderBy('u.expiration_date', 'ASC')
->execute();

$form['certificates']['table'] = array(
 '#theme' => 'table',
 '#header' => array(t('Application'), t('Certificate'), t('Uploaded'), t('Expiry Date')),
 'rows' => array(),
 '#weight' => 30,
);

foreach($cert_table as $key => $val) {

$form['certificates']['table']["#rows"]["'r$key'"] = array(
    'c1' => array(
        'data' => array('#type' => 'item', '#markup' => t('@app_name', array('@app_name' => $val->app_name))),
    ),
    'c2' => array(
        'data' => array('#type' => 'item', '#markup' => t('@cert', array('@cert' => $val->cert_name))),
    ),
    'c3' => array(
        'data' => array('#type' => 'item', '#markup' => t('@uploaded', array('@uploaded' => date('d-m-Y', $val->upload_date)))),
    ),
    'c4' => array(
        'data' => array('#type' => 'item', '#markup' => t('@expiry', array('@expiry' => date('d-m-Y', strtotime($val->expiration_date))))),
    ),
);
}
</code>
Comment: As side note, you are missing a _#_ in `'rows' => array()`.
Comment: The table is working correct but I'll check it. Thanks!
Comment: It works because in the loop you use `$form['certificates']['table']["#rows"]`. It is only a detail, not something that explains why the code doesn't work as expected.
Answer: You can add class for the row and add background for this class via the css
<code>$row = array(
  array(
    'data' => array(
      array( 'data' => 'cell1'),
      array( 'data' => 'cell2'),
      array( 'data' => 'cell3' ),
    ),
    'class' => array('my-class'),
  )
);

print theme('table', array('rows' => $row));
</code>
Comment: Okay. And how to add a class to 1 complete row instead of 1 column?
Comment: I updated my answer. Try it.
Comment: Unfortunately that also doesn't work. I edited my post with the complete code of the $form['table']. Already thanks for helping!
Comment: I updated my answer and checked it. It works for me.

Adding background color to table rows


Lilypond avoid \melisma code

Question: To align lyrics to music properly, instead of using \melisma and \melismaEnd, I found this method:

\version "2.20.0"

...

\addlyrics {
  Che -- _ _ _ ta -- na __ _ _ _
}

Is this ok? or is better to use the melisma code?
Comment: here a more clear example: http://lilybin.com/w9sh7s/1
Answer: It depends on the situation. You have three paradigms: One is using either slurs or beams or using \melisma (which basically just sets melismaBusy to true). The other one is manually skipping notes using _ in the lyrics. The last paradigm is to not actually have the lyrics follow a voice, but to manually specify the duration of each syllable like
Che1*2 -- ta2. -- na(whatever duration that has)

The third way is usually only preferable if lyrics and notes are somewhat separate things, so usually you do not need it. Then usually the first method is less chaotic, as the music defines where a melisma is, so you do not need to specify this information in the lyrics. This also means that when the notes change you do not need to change the lyrics.
The second way can save some time, so when you've got a lot of rather uncomplicated melismas (like 2-note melismas) this is quite viable. In your case I think this is not the case though.
The second case can also be very important if you have music with multiple lyrics where melismas do not align. Like when you have multiple stanzas, and some stanzas have two notes syllabic, some melismatic. In this case you want to handle this yourself using _.

Lilypond avoid \melisma code


Satterthwaite degrees of freedom in a mixed model change drastically depending on the DV

Question: I have a couple of MLM models created using lme4:
y1 ~ x1 + x2 + x3 + x4 + (1+x4|id)
y2 ~ x1 + x2 + x3 + x4 + (1+x4|id)

notice that the only difference between them is the DV.
When I use lmerTest to get p-values I notice that my degrees of freedom for some of the predictors changes quite drastically between the 2 models. For example, in model 1 x4 df might be 38.50, while in model 2 df for the same predictor might be 260.50
Is that expected behavior?
Given that my predictor variables are identical in both cases (i.e. this can't be a case of one model having more missing data than the other), why is there such a difference in the degrees of freedom when only the DV is changed?
Is there something about the Satterthwaite approximation that takes into account the DV, and hence degrees of freedom are expected to be so different?
EDIT
comparing Satterthwaite and Kenward-Roger (Id prefer to use regular summary(model) as it gives me more information, like random effects estimates and beta estimates)
Im not sure why there are minor fluctuations in df across the board between the 2 models (for both Satterthwaite and Kenward-Roger), but more importantly, notice how the x4 df is 10x larger in model 2 when using Satterthwaite
model 1:
model <- lmer(step_mean ~ x1 + x2 + x3 + x4 + (1+x4|id), data=df, REML=T)

summary(model)

Fixed effects:
                     Estimate Std. Error        df t value Pr(>|t|)
(Intercept)          -0.06003    0.12845  35.07528  -0.467 0.643161
x1                    0.49117    0.12548  35.12842   3.914 0.000398 ***
x2                   -0.01394    0.01225 259.84143  -1.138 0.256368
x3                    0.01414    0.28512  34.47940   0.050 0.960745
x4                   -0.04091    0.01086  25.53492  -3.767 0.000874 ***

anova(model, ddf='Kenward-Roger')

Analysis of Variance Table of type III  with  Kenward-Roger
approximation for degrees of freedom
                     Sum Sq Mean Sq NumDF   DenDF F.value    Pr(>F)
x1                  0.47355 0.47355     1  35.119 14.5328 0.0005336 ***
x2                  0.04145 0.04145     1 259.955  1.2721 0.2604083
x3                  0.00007 0.00007     1  34.435  0.0023 0.9621706
x4                  0.43630 0.43630     1  27.832 13.3899 0.0010463 **

model 2:
model <- lmer(stride ~ x1 + x2 + x3 + x4 + (1+x4|id), data=df, REML=T)

summary(model)

Fixed effects:
                     Estimate Std. Error        df t value Pr(>|t|)
(Intercept)          -0.05924    0.09010  35.35792  -0.657    0.515
x1                    0.08257    0.08865  34.98204   0.931    0.358
x2                   -0.03555    0.05087 295.62573  -0.699    0.485
x3                    0.08774    0.20271  35.43835   0.433    0.668
x4                    0.02290    0.04407 260.86367   0.520    0.604

anova(model, ddf='Kenward-Roger')

Analysis of Variance Table of type III  with  Kenward-Roger
approximation for degrees of freedom
                     Sum Sq Mean Sq NumDF   DenDF F.value Pr(>F)
x1                  0.52223 0.52223     1  34.736 0.82341 0.3704
x2                  0.29974 0.29974     1 294.418 0.47260 0.4923
x3                  0.11041 0.11041     1  35.005 0.17409 0.6791
x4                  0.15516 0.15516     1  24.510 0.24464 0.6253

Comment: See my edit. Satterthwaite df increases drastically for one of the predictors between the 2 models. but kenward-roger remains somewhat consistent, but there are still minor fluctuations in df across models
Answer: The Satterthwaite method depends on the dependent variable through the Hessian of the (reml) log-likelihood/deviance function with respect to the variance-parameters (there is also a gradient involved), so it is not surprising if the denominator degrees of freedom change with a change of the dependent variable.
In this concrete case x4 enters in the random-effects as well as fixed-effects, which explains why the denominator df for the fixed effect of x4 changes between the models while the denominator df for the other fixed effects are not (as) affected (but also note the denominator df for x2).
Three things inhibits further exploration of this concrete example:

The contrasts may or may not differ between summary and this type III anova so we may not be comparing like with like if we compare the concrete examples of Satterthwaite and Kenward-Roger (KR) methods. Use summary(model, ddf="Kenward-Roger") if you want to use KR df in summary. Also note that while the Satterthwaite implementation is the same for t and 1 df F tests, they actually do differ for KR which can lead to additional differences between summary and anova outputs.
The implementation was completely rewritten in lmerTest version >= 3.0-0 so knowing which version is being used is relevant (please include a sessionInfo()). On closer inspection of the output I think you are actually using an old version of lmerTest, so I suggest you upgrade as a first move (cf. https://github.com/runehaubo/lmerTestR).
Seeing the estimates of the variance parameters is relevant here (in addition to potential convergence warnings), so please include the complete outputs of summary.

Cheers
Rune
Comment: +1. Welcome to CV. It's great to see one of the authors of `lmerTest` here; we sometimes have questions about it and it would be great to have additional expertise. I remember some interesting questions that remained unanswered, can try to find them and give you some links later.
Comment: Thanks. I'm happy to help so just let me know if there are unanswered questions where I can assist. I suppose there is a way to receive notifications about (new) questions on selected topics- I'll see if I can turn that on.
Comment: There is this "fundamental" question https://stats.stackexchange.com/questions/108161 that would really benefit from having an authoritative and comprehensive answer. I am happy to put a bounty there if you decide to post one. Apart from that, I remember a bunch of questions about analyzing balanced designs suitable for RM-ANOVA where Satterthwaite dfs were giving seemingly very wrong numbers, while K-R gave sensible results (similar to RM-ANOVA). E.g. https://stats.stackexchange.com/questions/84268 (see the end of Ben Bolker's answer and my last comment underneath about his `model2`).


What does $u_x v_y=u_y v_x$ actually mean?

Question: Here is my approach to find a criterion to determine whether the equation $\alpha u_{tt}+\beta u_{tx}+\mu u_{xx}=0$ can be transformed into a wave equation $v_{tt}-c^2v_{yy}=0$.

Suppose there is a coordinate transformation $u(t,x) \mapsto v(s,y)$ such that $u(t,x)=v(s,y)$ and $v_{ss}-c^2v_{yy}=0$.
Then since $$v_{ss}=(u_{xx}x_s+u_{x}t_s)x_s+u_xx_{ss}+(u_{tx}x_s+u_{tt}t_s)t_s+u_tt_{ss}$$ and $$v_{yy}=(u_{xx}x_y+u_{xt}t_y)x_y+u_xx_{yy}+(u_{tx}x_y+u_{tt}t_y)t_y+u_tt_{yy}$$, we have $$v_{ss}-c^2v_{yy}=(t_s^2-c^2t_y^2)u_{tt}+2(t_sx_s-c^2t_yx_y)u_{xt}+(x_s^2-c^2x_y^2)u_{xx}+(x_{ss}-c^2x_{yy})u_x+(t_{ss}-c^2t_{yy})u_t=0$$. So we get $$\alpha=t_s^2-c^2t_y^2$$ $$\beta=2(t_sx_s-c^2t_yx_y)$$ $$\mu=x_s^2-c^2x_y^2$$ $$x_{ss}-c^2x_{yy}=t_{ss}-c^2t_{yy}=0$$. Then $\frac{1}{4}\beta^2-\alpha\mu=c^2(t_sx_y-t_yx_s)^2\geq 0$.

Here, I am curious about the case of $t_s x_y=t_y x_s$ so that $\beta^2-4\alpha\mu=0$. Intuitively, it may reach to contradiction if $\beta^2-4\alpha\mu=0$, since it means $\alpha u_{tt}+\beta u_{tx}+\mu u_{xx}=\left(\partial_t +\frac{\beta}{2\alpha}\partial_x\right)^2u=0$ which is not a wave equation. But I cannot find any clue. Also, I have no information for the condition $x_{ss}-c^2x_{yy}=t_{ss}-c^2t_{yy}=0$. To solve this, I have to bring out some relations between $s$ and $y$ from $t_s x_y=t_y x_s$ first. Would you give me any help?
Answer: The short answer to your title question is that the Inverse Function Theorem does not apply to the mapping $(x,y)\to(u(x,y),v(x,y))$. Such a mapping has derivative matrix
$$ \begin{bmatrix} u_x & u_y \cr
                   v_x & v_y \end{bmatrix}. $$
The IFT says that if this matrix is continuous and is invertible at one point then the mapping is invertible in a small neighborhood of that point. This is certainly what you want as a change of variables $(x,y)$ to $(u,v)$.
So I think what you have shown so far is that to convert your PDE to the wave equation you need to have $\tfrac{1}{4}\beta^2-\alpha\mu>0$.  Beyond that you need express, for example,
$$ \mu = x_s^2-c^2x_y^2 $$
for some solution $x$ of the wave equation $x_{ss}-c^2x_{yy} = 0$. But all solutions of that are expressible as
$$ x(y,s) = f(y-cs)+g(y+cs) $$
for some functions $f$ and $g$. Similar requirements for $\alpha$ and $\beta$, pretty involved.
You might want to look at the discussion of normal forms for certain PDEs in Courant and Hilbert, Methods of Mathematical Physics Vol II, page 154.
Comment: Thank you! But I have one more question: Is there any contradiction if IFT does not apply to the mapping $(x,y)\mapsto (u,v)$? I understood that if the equation is elliptic, i.e. is a wave equation, then $\beta^2-4\alpha\mu>0$, but not the converse. Could you give me gsome intuitive or direct evidences?
Comment: A standard example is the Tricomi equation $u_{xx}+xu_{yy}=0$ with $x$ negative.  It is hyperbolic (you meant hyperbolic above) but is a well-studied equation that I do not believe is reducible to the standard wave equation.
Comment: A simpler example is $u_{xx}+u_{xy}=0$. The solutions are $f(x-y)+g(y)$, not all waves.


Is the whenChanged Active Directory attribute editable?

Question: I've been searching for tools to change Active Directory object attributes, and I noticed the tools and articles and found so far are explicitly not mentioning capability to edit the whenChanged attribute.
It would be logical to assume that it's not editable at all, since it would reduce the value of system auditing services provided by Active Directory.
So the question: is the whenChanged attribute on an Active Directory object directly writable/editable?
Answer: No, System-only attributes are not writable.  I also don't think there would be a reasonable business need to do so.
Answer: The whenChanged attribute is system-only; it can never be updated by user action.  You'd need to directly manipulate the database to change it.
Comment: I need 4 more points to upvote. Thank you.


Ruby - Finding the data in specific field/key of hash

Question: I collected a list of all tags of my github repo using github api. Suppose I store it in a variable named 'released_tags'.
Eg: Data in 'released_tags' would be something similar to data displayed in https://api.github.com/repos/fastly/epoch/tags
I have a number 0.3 and I wish to find it in the value of the name field of this data and want the last/latest containing/matching name.
Expected result: This data has 0.3.5, 0.3.4, 0.3.3, 0.3.2, 0.3.1 and 0.3.0 which contains 0.3. I am trying to work on a logic/easy way in which a search is made through name field for 0.3 and I get the latest i.e. in this case the output of the logic should be 0.3.5 since thats the latest/highest number. If the name field just had 0.3 or 0.3.0, then the output should be 0.3 or 0.3.0
EDIT: I was able to get to the solution, but is there any easy/short way to do it? Here is my solution:
 tag_names = Array.new

  released_tags.each do |tag|
    if tag['name'].include? '0.3'
      tag_names << tag['name']
    end
  end

 p tag_names.first

Answer: Given that you always need the first result that matches, you could use find:
released_tags.find { |tag| tag['name'] =~ /^0\.3/ }

or, if you don't like regular expressions:
released_tags.find { |tag| tag['name'].start_with?("0.3") }

Comment: Also, if you just need the tag name itself you can do this: `released_tags.map {|tag| tag['name'] }.grep(/0\.3/).first`
Comment: ...though that's probably less efficient =/


theme_debug doesn't work

Question: I wrote into my settings.php file (into default.settings.php file too):
$conf['theme_debug'] = TRUE;
$settings['theme_debug'] = TRUE;
$settings['theme_auto_reload'] = TRUE;

(These files have 777 permission.)
I have the "Theme developer" module.
I cleared all cache.
But the suggestions doesn't appear.
What else should I do?
(I have Drupal 7.)
Comment: Is this what the documentation for that module says you should do?
Comment: This might sound funny but did you enable the module and its dependencies ? It has a few dependencies from what I recall.
Comment: Are you talking about Theme developer? I enabled it.
Answer: People have been facing issues with Theme Developer module. If you installed this module just to get template suggestions, you might want to uninstall it and use theme_debug (only for d7) variable instead.
Enable this variable by adding $conf[theme_debug] to your settings.php or drush vset theme_debug 1
Then Perform a element inspect (or) view page source to get template suggestions. You may find this article on drupal and the answer in this post helpful- self promoting my answer.
Comment: I disabled the Theme Developer. This solved my problem.
Answer: In some installations the minifyhtml module is used. If this is the case, the option "Strip comments from the source HTML" under /admin/config/development/performance/minifyhtml must be deactivated.

theme_debug doesn't work


Acessar Variável local em JavaScript e armazenas em variável PHP

Question: Boa noite!
Como eu poderia armazenar os dados da variável "teste" em "$variavelphp". Da maneira como esta o código hoje a variável "teste" não esta acessível.
Caso não seja possível como eu poderia acessar o valor da variável "teste" em "teste2" em outra parte do código.

                var ref = firebase.database().ref('Profissionais').orderByChild('Nome');

                //var u = 0;

        ref.on('child_added', function (snapshot) {
            var profissional = snapshot.val();
            if (profissional.provider == "usuarios" || profissional.provider == "Facebook" || profissional.provider == "Firebase" || profissional.provider == "Usuarios") {
                 teste =  "
" + snapshot.key + "	" + profissional.Nome + "	" + profissional.Email + "	" + profissional.provider + "	Consultar
";

            }

            });

</script>

    <?php
        $variavelphp = "";

        ?>

Comment: Praticamente o  mesmo problema que respondi aqui ontem: [Salvar ID do click do botão numa sessão PHP](https://pt.stackoverflow.com/questions/338529/como-salvar-id-do-click-no-bot%C3%A3o-numa-session-php/338595#338595)
Comment: Não é possível. [**Recomendo**](https://pt.stackoverflow.com/questions/25136/igualar-vari%C3%A1vel-php-a-uma-vari%C3%A1vel-javascript)
Answer: Bom dia, amigo.
Sugiro, após pegar o dados do Firebase, você fazer um post/get para uma página em PHP e pegar o dado da requisição em si.
Se for GET, seria assim:
$variavel = $_GET['teste'];

Se for POST:
$variavel = $_POST['teste'];

Dessa forma, você consegue passar as informações de Javascript para o PHP. Mas, só com requisições: POST, GET, PUT, etc..
Espero ter ajudado.
Comment: Olá, jovem. Bem-vindo ao Stackoverflow. Isso não responde ao que foi perguntando. Parece que o Autor da Pergunta está tentando acessar uma variável Javascript pelo PHP, isso não é possivel e, como já foi indicado acima nos comentários, existem várias respostas no site sobre o assunto.


Change Exchange 2010/domain member server SID

Question: Background:
5 ESXi servers running in DRS, ~20TB storage.  Loads of virtual servers including DC's/child DC's/member servs all 2K8 and Exchange 2010 servers.
Majority deployed from a template (not joined to domain), renamed and then joined to domain.
I'm pretty sure 90% of my machines have the same SID, at the very least I know my 3 Exchange 2010 servers have same SID (1 CAS/HUB, 2 MBX in DAG).
I know I can change the SID of my machines using NewSID, my question is can I do this to a machine already joined to the domain, let alone an Exchange 2010 server.
Any insight is helpful, thanks!
Answer: Exchange servers are very sensitive to domain membership and computer name, so I'd guess they are very sensitive to their SIDs, too; anyway, changing a machine's SID effectively breaks its trust relationship with the domain, so it will require to be de-joined and re-joined; and that's definitely something that you don't want to do to an Exchange server.
If you are really serious about this, then creating new servers (with new SIDs...), moving roles to them and removing the old ones would be your best approach here. Anything else might work, but it's practically guaranteed to get you into lots and lots of troubles.
Answer: Sysprep does alot more than just changing the SID. You should not deploy a non-syspreped image.   Once domain joined I'm not sure what the behavior is if the sid changes.  If you have already deployed a non-syspreped image I would urge you to come up with a rebuild plan.
Comment: It will need to be re-joined. Sysprep should never be executed on domain-joined machines, if you want them to be still working (as much as domain access is concerned) after it.
Comment: Yes sysprep will break the domain membership.
Answer: Are you seeing any specific issues from this situation?
I'd recommend using sysprep in your procedure of deploying from a template, the "Customization Specifications" of the template deploy wizard will do this for you.
That said, duplicate machine SIDs alone shouldn't break anything; the domain RIDs of the computers are already different from each other because they were independently joined to the domain.  See this article for too much information.
Comment: @Holocryptic, I really don't see how a duplicated SID could cause messages being stuck in the Drafts folder (and be resolved by moving the active DB copy around). There *are* some known SID-related issues in Exchange 2010 SP1 (SP1, not RTM), but those don't affect message delivery. I'm not saying the issue here **can't** be caused by the duplicated SIDs... but I think it's much more likely to be caused by something else.
Comment: This doesn't seem to be even *remotely* related to SIDs.
Comment: Specific issue I am seeing is that all the sent items of a user is sitting in Drafts.  This issue occurred the other day for the entire org, I moved the active copy of the DB to the other server of the 2 MBX servers and it resolved the issue.  Other than that I don't see any other issues.
Comment: @Massimo, it is related.  However the takeaway in this case is that as long as the SID of the joined computer isn't the same as the SID of the DC that first joined the domain he shouldn't have a problem (allegedly).  If it is, then he's got larger problems.
Comment: @Massimo, sorry.  I was reading this in the middle of doing a bunch of other stuff and misunderstood your comment.  For whatever reason I thought you were saying the article had nothing to do with SIDs.  Or something like that...  It's been a long day.
Answer: If you are referring to the issue described to here:
http://msexchangeteam.com/archive/2010/09/01/456094.aspx
My opinion if something goes wrong and you need to engage Microsoft for support, you probably should not be using tools that are not supported.  NewSID was retired a while back, that is not something I would run on a server that is already in production.  I would agree with Massimo, turn up fresh servers and move resources to them, then after you have the old servers unplugged from the network for a while you can decommission them.


What does this construction means?

Question: class Test
{

    struct
    {
      unsigned has_some_value1: 1;
      unsigned has_some_value2: 1;
    } info;
};

What does  unsigned has_some_value1: 1; means?
Should be the following statement true:  sizoef(type) == bit1 + ... + bitn ?
Comment: http://stackoverflow.com/questions/1604968/what-does-this-c-code-mean
Answer: These are called "bit fields". has_some_value1 occupies one bit. has_some_value2 also occupies one bit—maybe the next physical bit in memory, or maybe not (depends how your compiler is configured to handle bit field alignment).
Comment: sizeof() will obviously, at a very minimum, round up the size to the next whole number of *bytes* after adding up the bit widths and dividing by 8. But it may also be more, due to architecture- and compiler-specific struct alignment issues.
Answer: A bitfield in a nonstatic instance of an un-named struct called "info", which is itself a member of "Test".

What does this construction means?


Error connecting with RDP between Mac and Win2k3 server

Question: I have an iMac running Mac OS X 10.5.8 and the RDP Connection Client 2.0.1.

When I try to connect to a Windows 2003 Server on the same network I get a dialog saying "Remote Desktop Connection cannot verify the identity of the computer that you want to connect to".

And when I press the Connect-button in the previous dialog I get the same message in another dialog:

I can connect to the Win2k3 server from a Vista machine, and it used to work from the Mac as well. I stopped working from the Mac after I did some configuration on the win2k3 server, removed and added the the connection in the Terminal Services Configuration:

What do I need to do to be able to connect from the Mac again?
Comment: The first dialog is definitely expected, since you are connecting to a 2003 server.
Answer: In Remote Desktop on your Mac open Preferences -> Security.
Make sure that the first 'Always Connect' option is chosen.
After that, you might want to try CoRD (http://cord.sourceforge.net/), which is an open-source Remote Desktop client that has some better tweaks and error messages.
Comment: I tried selecting "Always Connect" in the Remote Desktop Client but still couldn't connect (the same message). Then I tried CoRD as you suggested, but when trying to connect nothing happens, no dialog no nothing...
Comment: Remote Desktop Client didn't work at all.. but CoRD did, thanks!!
Answer: CoRD solved my problem, and some other minor problems too :) I recommend it!
Answer: We just had this same issue with a WS2008R2 and a Mac.
Connected from mac via microsofts RDP program. Suddenly disconnected with that message.
Subsequent attempts at logon from Mac gave same message and immediate disconnection.
Settings on the server were as user23294 mentioned, set to compatible, and the setup has worked fine up till now (many months).
Solution was to logon from a windows client, close programs and log user off.
Then the user could again log on from a Mac.
Apparently the user session became corrupted somehow, preventing access from a Mac, but not from another Windows client.
Answer: Solved it, I changed encryption level on the connection in the Terminal Services Configuration dialog to "Client Compatible".
http://salle.dyndns.org/misc/rdp_problem_solution.png
Answer: I was having the same problem. The authentication would fail if the user had the password saved in the settings. It's a security risk having the password saved but the error message is so cryptic and my users just can't get the hang of not saving their password when it asks to save the connection at the end of the session.
If you can accept the security risk of a saved password on the client end, then I turned off the "Always prompt for password" on the "Log On Settings Tab" in "RDP-Tcp Properties" of "Remote Desktop Session Host Configuration" -- Windows 2008 R2.
This resolved the problem for me but it's a security compromise to not alienate the Mac people.


Como obter a soma de três tabelas no sql

Question: Possuo 3 Tabelas, sendo elas:

Escola: id, id_escola e nome_escola;
Professor: id, id_escola e nome_professor;
Alunos: id, id_escola, sala_aula e numero_alunos;

Tenho conhecimento dos joins, count's, e sum's porém não estou conseguindo montar o SQL.
Eu preciso retornar uma linha de uma escola específica com o nome da escola, quantidade de alunos, quantidade de salas e a quantidade de professores.
Como montar essa query ?
Answer: Tenta essa consulta.
Mas assim... você pode melhorar a estrutura da suas tabelas.
A tabela escola não precisa de duas chaves primárias a não ser que seja necessário.
Na tabela alunos não precisa da coluna numero_alunos.
SELECT
    NOME_ESCOLA,
    NOME_PROFESSOR,
    COUNT(ALUNOS.ID) AS TOTAL_ALUNOS
FROM
    ESCOLA
INNER JOIN
    PROFESSOR ON PROFESSOR.ID_ESCOLA = ESCOLA.ID_ESCOLA
INNER JOIN
    ALUNOS ON ALUNOS.ID_ESCOLA = ESCOLA.ID_ESCOLA
GROUP BY
    NOME_ESCOLA, NOME_PROFESSOR

Answer: Caso não seja do seu interesse alterar o modelo de dados, com subqueries funciona assim:
SELECT
    e.nome_escola,
    (SELECT COUNT(p.id) FROM Professor p WHERE p.id_escola = e.id) AS professors_count,
    (SELECT COUNT(a.id) FROM Alunos a1 WHERE a1.id_escola = e.id) AS students_count,
    (SELECT COUNT(DISTINCT a2.sala_aula) FROM Alunos a2 WHERE a2.id_escola = e.id) AS rooms_count,
FROM Escola e;


How to alter a form element's properties before rendering?

Question: Here's a simple task.
For accessibility reasons, from a custom module I need to perform alterations on textfield based form elements (such as email, textfield, etc ...) on custom forms displayed to front users.
These forms extends the Drupal\Core\Form\FormBase class.
The alterations I need to perform would be for exemple to automatically and programmatically copy the value of the field's placeholder text and put it in the field's title attribute (not the field's label, I'm talking about the HTML title attribute).
So the field's markup would look something like this :
<input type="email" placeholder="Email" title="Email" />

I want to check all custom forms for the entire website.
I tried different methods :

hook_field_widget_form_alter : doesn't fire for fields on custom
forms because they are not widgets.
hook_preprocess_form_element : It's too late to perform these changes. The values just won't take effect on the field.
hook_form_alter : Well it's just too general, I find it a bit dodgy to parse the entire Render Array, check for fields, etc ... but may be it is the only way..

I looked into the Form API, Render API, Plugins API, I looked into services, nothing seems to offer any solution, unless of course I missing something, and I probably do.
Has anyone any idea on how to achieve this in the best Drupal 8 way?
Comment: Please don't add [solved] to the title and post an answer in the question body, you're able to answer your own questions here if you have a resolution. Thanks!
Answer: In hook_template_preprocess_form_element the (input-)tags is already rendered.
You can use
function hook/template_preprocess_input(&$variables) {
  $variables['attributes']['title'] = 'my-title';
  $variables['attributes']['placeholder'] = 'my-placeholder';
}

to alter the input tag. use the same method for all other desired tags.
Here's a nice tutorial.

You could make use of hook/template_preprocess to go a more generic
  way.
Comment: None of $variables['attributes']['title'] or $variables['element']['#attributes']['title'] work...
Comment: I don't want to have the code in my theme. I want to generate a module for generic accessibility use cases.
Comment: use hook_ (in modules) or template_ (in themes) - not matter here ;)
Comment: I tried hook_preprocess_input along with with hook_preprocess_form_element but the changes won't take effect...
Comment: can you show some code pls - have you tried hook_preprocess
Comment: Yes I've tried hook_preprocess as well... here is a piece of code :
Comment: Sorry for the delay... why would you set the title and placeholders key to be arrays in the $variables['attributes'] variable ?
Comment: Yes $variables['attributes']['title'] without extra [] works !!! Can you edit your code to $variables['attributes']['title'][] = 'my-title';
Comment: sorry for the typo ..
Answer: here is a piece of code :
function MODULE_preprocess_input(&$variables) {
    if (!\Drupal::service('router.admin_context')->isAdminRoute()) {
        $field = $variables['element'];
        if ($field['#type'] == 'email') {
            if (isset($field['#attributes']['placeholder'])) {
                $placeholder = $field['#attributes']['placeholder'];
                $variables['element']['#attributes']['title'] = $placeholder;
            }
        }
    }
}

Answer: None of above works for me. There is no 'title' field which can be changed, but instead there is a TranslatableMarkup object inside $variables["attributes"]["value"]
For me this works:
function MODULE_preprocess_input(&$variables)
{
  if ($variables['attributes']['class'][0] == 'delete-order-item') {

    $variables["attributes"]["value"] = new \Drupal\Core\StringTranslation\TranslatableMarkup("X");
  }
}

Basically I'm changing name of "Remove" button to just "X" and title really is replaced, but problem is that with new name (value attribute actually) delete action is not working any more. But title is replaced successfully.


Python KeyError after returning the value (also error_id 502)

Question: I'm  using stackoverflow's API and want to use the 'quota_remaining' so I can perform pagination.
But when I try to print the 'quota_remaining' I am getting a KeyError after the print. So it prints the value but I am not able to store it in a variable because it throws a KeyError afterwards.
This is my code:
# Get data
users_url = 'https://api.stackexchange.com/2.3/users?page=1&pagesize=100&order=desc&sort=modified&site=stackoverflow&filter=!56ApJn82ELRG*IWQxo6.gXu9qS90qXxNmY8e9b'

# Make the API call
response = requests.get(users_url)
result = response.json()

print(result)
print(result['quota_remaining']) # line 33
quota_remaining = result['quota_remaining']

And this is what is returned (I included a sample of the print(result)):
{'items': ['badge_counts': {'bronze': 6, 'silver': 0, 'gold': 0}, 'view_count': 21, 'answer_count': 2, 'question_count': 14, 'reputation_change_quarter': 0, 'reputation': 75, 'user_id': 2498916, 'link': 'https://stackoverflow.com/users/2498916/oscar-salas', 'display_name': 'Oscar Salas'}], 'has_more': True, 'backoff': 10, 'quota_max': 300, 'quota_remaining': 261, 'page': 1, 'page_size': 100}
261
1
{'error_id': 502, 'error_message': 'Violation of backoff parameter', 'error_name': 'throttle_violation'}
Traceback (most recent call last):
  File "test.py", line 33, in <module>
    print(result['quota_remaining'])
KeyError: 'quota_remaining'

I also don't understand why I am getting the error 502, what am I violating? What is the backoff parameter?
Comment: You are making too many requests to the API in a short time period and have exceeded the quote_remaining limit
Answer: Change variable name, try this:
users_url = 'https://api.stackexchange.com/2.3/users?page=1&pagesize=100&order=desc&sort=modified&site=stackoverflow&filter=!56ApJn82ELRG*IWQxo6.gXu9qS90qXxNmY8e9b'

# Make the API call
response = requests.get(users_url)
result = response.json()

print(result)
print(result['quota_remaining']) # line 33
quota_remaining1 = result['quota_remaining']

Answer: Okay I've figured it out. I was making too many requests as @SimonT pointed out.
The backoff parameter meant I had to wait that many seconds before hitting the same method again. I'm my case I had a backoff = 10 so I set up a time.sleep(10) between requests.
This is actually my full code (I had only a sample in the question as I did not understood the keyError was actually because of the throttle violation - a rookie mistake):
while quota > 240:
    # Get data
    users_url = f'https://api.stackexchange.com/2.3/users?page={page}&pagesize=100&order=desc&sort=modified&site=stackoverflow&filter=!56ApJn82ELRG*IWQxo6.gXu9qS90qXxNmY8e9b'

    # Make the API call
    response = requests.get(users_url)
    result = response.json()

    print(result['quota_remaining'])
    print(result['page'])

    # Update counters
    quota = result['quota_remaining']
    page = result['page']

    # Save users in a list
    for user in result["items"]:
        user['_id'] = user.pop('user_id')
        results.append(user)

    if result['has_more'] == True:
        time.sleep(10)
        page += 1
    else:
        break


Formula 1 season with highest number of DNF's?

Question: I'm interested in knowing, which Formula 1 season had the most number of DNF's (Did Not Finish)?
Comment: I'll do some proper research later but I would expect this to be a season when there were more cars entering, probably in the 1950s
Comment: Define "crash" and do you mean the number of cars involved or incidents?
Comment: @davidjwest Sir anything that make driver dnf because of involvement and incident just not mechanical failure getting into pit. And sir if you get the idea do edit the question.
Comment: Not an answer yet as still looking but the 1998 Belgian GP had 12 retirements due to accidents out of 20 starters https://en.wikipedia.org/wiki/1998_Belgian_Grand_Prix
Comment: @davidjwest Sir what about [1996 monaco grand prix](https://en.wikipedia.org/wiki/1996_Monaco_Grand_Prix), and for 1998 belgian gp just because of that one race will it be a season with highest crashes.
Comment: I've edited the question for clarity - Monaco '96 had 12/13 DNFs due to accidents, there's a query over Luca Badoer as he retired with an electrical problem after a collision.
Answer: There are various reasons for a driver being classified as a DNF at a GP, including the following:

Mechanical DNF
Accidents
NC (Not Classified)
DSQ (Disqualified)
DNQ (Did Not Qualify)
WD (Withdrawn)
DNS (Did Not Start)

I have therefore gathered data from the 1992 season to the 2016 season from various sources to answer your question and also to show everyone some interesting stats about the evolution of F1 since the 1990s.

Let's start by answering your question. Based on the following chart, the season with the most DNF's (between 1992-2016) seems to be the 1992 season with 264 total DNF's, followed closely by the 1994 season with 239 total DNF's:

You really realise with the trendline y = -6.96x + 219 on the chart just by how much the number of accidents and mechanical failures decreased over the years, especially in 1996 and in 2003. I guess this shows how the cars evolved over the years and became much more reliable.

Now for the more interesting bit, here is a comparison chart showing the:

Total number of DNF's
Total number of classified finished
Percentage of DNF's (based on all total possible finishes)
Percentage of classified finishes (based on all total possible finishes)

I find it quite interesting to see the percentage of drivers who actually finished the races in the 1990s compare to the 2010s.
Looking at the columns, you can see the increasing gap between the orange column (total DNFs) and the blue column (total classified finishes). In the 1990s there were seasons (1992 & 1994) where the were more DNFs than classified finishes! Also looking at the blue and orange lines you can again see just how much they diverge after 2002.
Comparing the season with the most DNF's (1992 - 264 DNF's) and the one with the least (2013 - 52 DNF's), 87.6% of the drivers who participated at a GP were classified finishers in 2013, whereas in the 1992 season only 44.9% of the drivers actually finished the race!

Finally, here is the table where I gathered all the data for you to see the details:

If anyone finds any mistakes in my data, please let me know so that I can make the changes. If you want access to the Excel spreadsheets I used to gather my data, send me a message so I can email it to you.
Sources:

F1 Fanatic Season statistics: Racefans (look at individual seasons)
FIA Formula One individual season summaries on Wikipedia (change the year in the link to get all the years)


SoundCloud API returning 0 tracks despite user having tracks

Question: I'm trying to get the tracks of specific users but for some users, even though they have tracks, the SoundCloud API return an empty list.
For example, the following user has 17 tracks as you can see from his track_count
http://api.soundcloud.com/users/1250904?client_id=XXXXXX

If I try to get his tracks it returns an empty list
http://api.soundcloud.com/users/1250904/tracks?client_id=XXXXXX

Is it possible for users to make their songs not available via API? Is there a field on the user that can distinguish this?
Comment: @tristan Their support team answers questions using StackOverflow - https://developers.soundcloud.com/support
Comment: This sounds like a question for SoundCloud's support team.
Comment: Oh cool, I didn't know that; thanks.  That's one of the better "we'll crowdsource and get free work" implementations I've seen.
Comment: SoundCloud shouldn't be doing this.  See [Why can't I ask customer service-related questions?](http://meta.stackoverflow.com/a/255746)
Comment: @YinYang did my answer help?
Answer: This is very interesting.  Using a normal CLIENT_ID I generated myself, I get the same results you do.  Additionally, if I try to hit the API for information about a specific track, I get a 403 Forbidden error:
HTTP GET https://api.soundcloud.com/tracks/149151252.json?client_id=XXXXXX

There could be a few reasons why this is occurring:

The user has hit their download limit for all of their tracks.
The user has disabled oEmbed, causing the API requests to 403 (see this post).
The user has somehow managed to block normal API access to their tracks.

I'm leaning on choice 3 here.  I've done some testing with some other CLIENT_IDs in this question trying the CLIENT_ID used by the youtube-dl application.  Using their _IPHONE_CLIENT_ID, I was able to see information for all 17 tracks.  If my understanding of that key is correct, it is a master API key used by SoundCloud for their iOS application, which would explain why that key works and others do not.
This user must have some setting enabled to block standard API access to their tracks.
Comment: @rifflock Yeah, looks like that old iOS key isn't working anymore.  Try one of the newer keys in [this issue](https://github.com/rg3/youtube-dl/issues/12376) or grab it from SoundCloud's app.js web player.
Comment: That's is a very interesting find. I just hope the `_IPHONE_CLIENT_ID` works in the long run as well.
Comment: I should note that it is against SoundClould's TOS to use someone else's API key or to reverse-engineer their endpoints.  So you don't want to rely on someone else's API key for your application.
Comment: I know this is a bit old at this point, but I've hit this issue with Soundcloud's APIs and that `_IPHONE_CLIENT_ID` no longer works (and isn't really a viable solution).
I did some testing with a Soundcloud account and I could find no combination of privacy settings that would allow a track to show up in the UI but not in the API return. I also emailed email@example.com, but received no response.
I don't suppose any of you have found documentation of different API key access levels?


Ansible same host on different groups with group_vars

Question: I have an Ansible inventory like the following:
[group1]
host1.mydomain

[maingroup:children]
group1

[group2]
host1.mydomain

I need to declare the same host on different groups since in this host there are two similar services collocated.
In order to distinguish between the two services, I have created the following group vars:
group_vars/maingroup
---
servicepath: /service1/path

group_vars/group2
---
servicepath: /service2/path

When I first run a playbook with hosts: maingroup, then the same playbook with hosts: group2, it used the correct servicepath variable value each time (first run=/service1/path, second run=/service2/path).
However, in all subsequent retries when I run a playbook with maingroup I got the value servicepath: /service2/path
I only managed to run the playbook with correct variables with  --extra-vars=@group_vars/group2 ansible-playbook parameter.
Could this be an Ansible bug or am I missing something?
Comment: could you show your ansible playbook?
Comment: This [reading](https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable) might help, especially the note at the end of the chapter.
Comment: Just add a custom name for host and bind to ip using ansible_host. The response is here. https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#hosts-and-non-standard-ports
Comment: @MihaiR Thanks. This could be a solution, although not so elegant.
Answer: The fact is that ansible binds the value of variables to the host, not to the group. That is, there can be only one value for one variable on one host.
Try this just to override the value of the variable on the host everytime:
---
- hosts: "{{ hosts }}"
  vars_files:
    - group_vars/{{ hosts }}.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

- hosts: "{{ hosts }}"
  vars_files:
    - group_vars/{{ hosts }}.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

where {{ hosts }} = "maingroup" or "group2"
Example:
---
- hosts: "maingroup"
  vars_files:
    - group_vars/maingroup.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

- hosts: "group2"
  vars_files:
    - group_vars/group2.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

- hosts: "maingroup"
  vars_files:
    - group_vars/maingroup.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

Comment: That works, but is much error-prone.

I'd recommend to use a random and unique hostname, combined with `ansible_ssh_host`, pointing to the real server.

```
[db_gmbh_prod]
db_gmbh_prod_ ansible_ssh_host=188.8.131.52 ansible_ssh_user=root
```


Should I listen to bowed note or released note when tuning?

Question: When I am tuning my double bass using harmonics, the note sounds like it changes intonation when I release the note compared to when I am bowing. I think this has something to do with the bow action forcing "pure harmonics" but I'm not sure.
So: does the intonation of the harmonic actually change when I release it, and why?
If they are different, should I try to tune the harmonics based on the bowed note? Or should I try to tune to the released note?
Comment: Which do you want to be in tune, the bowed note or the released note? ;)
Comment: Could you clarify your question please?  Also, what do you mean by 'when I release the neat'.
Answer:
So: does the intonation of the harmonic actually change when I release it,

Yes.

and why?

Because the pressure of the bow on the string changes the tension (and, microscopically, the length) of the string.  It's not dissimilar to a guitarist who bends pitch by sliding the string laterally on the fretboard.  I suppose that the action of the bow driving the string's vibration has an additional impact on the pitch, but I'm less sure of that.
When I was in grad school, one of the professors, a lutenist, was very vocal about string players who play lightly when they're tuning their instruments.  He said that they should play at full volume when they tune because otherwise they would not be tuning the actual pitches they would be playing in the performance.

If they are different, should I try to tune the harmonics based on the bowed note?  Or should I try to tune to the released note?

If you're playing mostly with the bow, yes, tune the pitch you hear when you're bowing.  If you're playing mostly pizzicato, it probably makes more sense to tune the pitch you hear when you let the string vibrate freely.
Comment: @CarlWitthoft though on an instrument like the guitar it might make sense to tune on the louder end because a flat note can easily be made sharper whereas a sharp note can't be made flatter on guitar.
Comment: Your professor was half-right, and half-wrong.  The pitch changes as you go from ppp to fff, so it makes sense to tune at, say, mf .  You have to be aware of the pitch change and constantly adjust fingering as the dynamics change.  // Also: the pitch changes as a function of amplitude, bowed or plucked.
Comment: It's also really important to note that when playing in a group and tuning together that you should be playing around the same dynamic which should also be a dynamic that allows each player to tune to each other.
Comment: Thanks for your answer! I think I will eventually edit my question to ask this, but will playing simultaneous notes with the bow affect the intonation as well? I want to know because I often listen to the interference beats to make sure it's in tune. Or should make a separate question for that?
Comment: @awelotta I'd make that a separate question.
Comment: @CarlWitthoft any deficiencies in the paraphrasing are mine, not my professor's.  He had a very successful career behind him, so I doubt he was wrong about much of anything.  It was many years ago, and I am not a string player, so I probably remember it imperfectly.  Nothing you say is inconsistent with anything he said.  The occasion for his remark was a master class in which a player was checking tuning by playing so quietly as to have to hold the instrument to his ear to hear it.


How to pass negative values to config-set

Question: It seems that we can't set negative values with config-set:
drush cset block.block.myblock_name weight '-1' --format=string -y

doesn't work
Answer: The (ugly) work-around is:
echo '-1' | drush cset block.block.myblock_name weight - -y

You don't need to specify that format is string as that is the default.
This seems to be a general problem with Drush commands; values starting with a dash is interpreted as arguments. See bug report for similar issue with vset - https://github.com/drush-ops/drush/issues/378


Uploaded my app without "com." in its bundle identifier

Question: So instead of my new app's bundle ID being "com.myName.myAppName", it is "myName.myAppName". I have another app in the app store with the "com." ID.
Will they reject this new one? Should I reject it myself and reupload it?
Thanks
Comment: Are these two different apps?
Comment: Even if they do not reject, I would re-submitt using a proper identifier. You'll be happier later.
Comment: I'm voting to close this question as off-topic because it concerns the policies and procedures of app distribution services, rather than programming. Please refer to: [Are developer-centric questions about application stores on topic?](https://meta.stackoverflow.com/q/272165), [Why can't I ask customer service-related questions?(https://meta.stackoverflow.com/a/255746)
Comment: yes, the first is approved and has the full bundle ID: "com.myName.myAppName". the second one i just uploaded and it has the short bundle ID: "myName.myAppName"
Answer: While we create new Application Identifier, Its more preferred to use the pattern like com.companyname.appname. However there is no hard or mandatory rules that you must follow such patterns.
So even if you are not using such pattern there is no chances or case to lead your application rejected.
Specifically in iOS bundle name is not getting displayed anywhere on the store to the users. Only developers can view it & its specifically created to uniquely identify your applications on your store.
Hope this helps to everyone.


Composition of flat morphisms is flat

Question: I do not understand in the snippet below why the composition of flat morphisms is flat. The full text (though in Czech) is given here.
I do not understand these step given in bold, beginning from $q\cdot u=0$ implies
$q\cdot p_2\cdot g=0$, so $q \cdot p_2\cdot g=0$ so $q\cdot p_2=h\cdot p_3$ for some $h$.
 Then $$h\cdot v \cdot p_2=h\cdot p_3=q\cdot p_2$$ then $h\cdot v=q$.
Comment: I think you're more likely to get a response if you just translate the whole argument into English
Answer: I believe, after we have proven that $u$ is injective, we want to realise $C/A$ as an extension of flat modules $B/A$ and $C/B$. To this end, we first prove that $u$ is injective and then consider the quotient map $q\colon C/A\to C/B$. As $q\circ u= 0$ by construction, $0= q\circ u\circ p_1 = q\circ p_2\circ g$. Therefore $q\circ p_2$ vanishes on the image of $B$ in $C$ under the inclusion $g$ and hence factorises through $C/B$, so $q\circ p_2 = h\circ p_3$ for some $h\colon C/B\to C/B$.
Now, $h\circ v\circ p_2 = h\circ p_3 = q\circ p_2$. As $p_2$ is an epimorphism, it can be cancelled if it is the rightmost morphism, so $h\circ v = q$. This realises $C/A$ as an extension of flat modules $B/A\to C/A\to C/B$ with the inclusion map $u$ and the quotient map $q$.
Comment: I'm trying to orient myself in your arguments. $p_2$ is a projection, how this implies it is an epimorphism ? Is every projection an epi ? Can you type $\to$ into your last sentence so that I understand what is an extension and what is a quotient ?
Comment: Yes. In fact, in every concrete category (one whose underlying objects are sets) every morphism $f\colon X\to Y$ which is surjective on the level of sets is an epimorphism. Indeed, if $g_1\circ f = g_2\circ f$, then $g_1$ and $g_2$ coincide on the image of $f$ which is by assumption the whole of $Y$, so $g_1 = g_2$.
Comment: How do we need $h\circ v=q$ to see that the inclusion map is $u$ and the quotient map is $q$ ?
Comment: Well, $q$ is by construction the quotient map associated to the injection $u$, but we want to deduce that this very quotient coincides with $C/g(B)$ which we know is flat. This is achieved by factoring $q$ as $h\circ v$ which maps to $C/g(B)$ by construction.
Comment: There is a typo here: what we want to deduce is that $C/A$ (more pedantically, $C/g\circ f(A)$ is flat as the claim is that the composition $g\circ f$ of two flat inclusions is flat.
Comment: Sorry, where exactly is the typo. In your comments, answer or snippet in the Czech ?
Comment: In the snippet: the last sentence of the proof should claim that $C/A$ is flat, not $B/A$.
Comment: I do not follow one more detail. How factoring $q$ as $h\circ v$ helps us ? Shouldn't $q$ be $g$ somewhere?
Comment: Well, from the definition of $q$ it doesn't a priori follow that the quotient is isomorphic $C/g(B)$ of which we know that it's flat. To see that this is the case one needs this factorisation.
Comment: What I do not understand is that $g$ **never appears** in this sentence: "$q$ factorizes as $h\circ v$" .
Comment: It does in a way: $C/B$ has to be read as $C/g(B)$, so all these morphisms act on modules constructed with the use of $g$.
Comment: One small detail yet: from where do we know that $(u,v)$ in the Czech snippet is a short exact sequence? Once we know that we can use the comment [here](https://math.stackexchange.com/questions/3496527/why-this-s-e-s-splits) `Jan 3 20:41` to see that $C/A$ is flat from the fact that $C/B$ is flat, right ?
Comment: I think that formally speaking the proof uses $(u,q)$ as the short exact sequence instead.I also think that the way the proof is written is actually unnecessarily complicated: a) there is no need to discuss amalgamated products because one can directly show that $u$ is injective: it is induced by the map $g$, and if $g(b) \in g(f(A))$, then $b\in f(A)$ by injectivity of $g$; b) one can indeed show directly that $v$ is the quotient map corresponding to $u$. Indeed, $v$ is induced by the injection $f\colon A\to B$, so it is automatically surjective, and its kernel coincides with $[g(B)]=u(B/A)$.
Comment: So in the end you're right: one could use $(u,v)$ as the short exact sequence which makes things work.
Comment: How do we know that the **entire** diagram in the snippet commutes ?
Comment: Well, both parts (the 4-gon and the triangle) commute by construction, so the whole thing commutes.

Composition of flat morphisms is flat


Como salvar Disicplina?

Question: Tenho o seguinte problema na minha aplicação.A tabela curso é relacionada com a tabela Disciplina, ou seja, 1 Disciplina pertence a vários curso, e na hora de  cadastrar um curso e adicionar mais disciplinas a este curso eu não consigo realizar esta ação.
Print das telas:

[Controller]
public ActionResult AddDisciplina(int id, Curso curso) {
    @ViewBag.id = curso.CursoID=id;
    ViewBag.d = new SelectList(db.disciplina, "DisciplinaID", "nome");
    return View();
}

[HttpPost, ActionName("AddDisciplina")]
[ValidateAntiForgeryToken]
public ActionResult AddDisciplina([Bind(Include = "CursoID,DisciplinaID")]Curso curso)
{
    return View();
}

[View]

AddDisciplina

         <input type="hidden" id=" cursoID" name="cursoID" value="@ViewBag.id">
         @Html.DropDownList("d", null, htmlAttributes: new { @class = "form-control" })

          <input type="submit" value="Create" class="btn btn-default" />

Comment: Você pode colocar na sua pergunta o código que realiza essa inserção?
Comment: Cadê a `Action` que persiste os dados? Dica: Também chama `AddDiscipina`, mas tem um `[HttpPost]` em cima.
Answer: Não tem nada na sua Action pra salvar. Obviamente não vai funcionar.
Tem que ser algo assim:
[HttpPost, ActionName("AddDisciplina")]
[ValidateAntiForgeryToken]
public ActionResult AddDisciplina([Bind(Include = "CursoID,DisciplinaID")]Curso curso)
{
    if (ModelState.IsValid)
    {
        var disciplina = db.Disciplinas.SingleOrDefault(d => d.DisciplinaID == DisciplinaID);
        var curso = new Curso {
            Disciplina = disciplina
        };

        context.Cursos.Add(curso);
        context.SaveChanges();
    }

    return View();
}

Como salvar Disicplina?


Using an ideal as an index set

Question: In Algorithmic Algebra by Mishra, the sum and intersections of submodules of $M$ (an $S$-module) are defined using an ideal $I \subseteq S$ as an index set for a family of submodules, $\mathcal M = (M_i)_{i \in I}$.
i.e
$\sum_{i \in I} M_i = \{\sum_{i \in I} x_i \mid \text{all but finite $x_i \in M_i$s are 0}\}$
and
$\bigcap_{i \in I} M_i $ (defined the usual way).
To me using an ideal as an index set is quite a weird/counter intuitive idea. Is there a place where this could be useful/desirable?
Answer: Sum and intersections are defined for modules indexed by an arbitrary set $I$. An ideal $I$ is more than just a set with extra properties; it comes with extra structure and therefore is not just a set. Every ideal $J$ has an underlying set $|J|$ and of course with respect to that set we can define families of modules etc., but this has nothing to do at all with the ideal structure because it has been forgotten.
Simple example: $\sum_{x \in |J|} R \cdot x = J$.
Comment: Thanks for the answer. So what you are saying is that using an ideal $I$ or rather $|I|$ as the index set, doesn't have an extra benefit over using an arbitrary index set? (What I wanted to know was, whether there was a benefit the structure of the ideal can give but an arbitrary index set can't.)
Comment: I don't see any difference.
Comment: Thank you for clarifying that.

Using an ideal as an index set


How to read server response in netty channel pool?

Question: I am using channel pool API in my client, to connect to server. When i send request to server it accept & work on it successfully but when server replies my client doesn't get that data.
Client Channel Pool:
group = new NioEventLoopGroup();
final Bootstrap b = new Bootstrap();
b.group(group)
  .channel(NioSocketChannel.class)
  .option(ChannelOption.SO_KEEPALIVE, true)
  .handler(new ClientInitializer());

poolMap = new AbstractChannelPoolMap<InetSocketAddress, SimpleChannelPool>() {

@Override
protected SimpleChannelPool newPool(InetSocketAddress key) {
  return new SimpleChannelPool(b.remoteAddress(key), new SimpleChannelPoolHandler());
}
};

ClientInitializer
private static final StringDecoder DECODER = new StringDecoder();
private static final StringEncoder ENCODER = new StringEncoder();

private static final ClientHandler CLIENT_HANDLER = new ClientHandler();

@Override
public void initChannel(SocketChannel ch)
{
  ChannelPipeline pipeline = ch.pipeline();

  // Add the text line codec combination first,
  pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
  pipeline.addLast(DECODER);
  pipeline.addLast(ENCODER);

  // and then business logic.
  pipeline.addLast(CLIENT_HANDLER);
}

ClientHandler
public class ClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        System.out.println(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

Sending data to server using channel pool:
final SimpleChannelPool pool = Client.poolMap.get(addr);

        Future<Channel> f = pool.acquire();

        f.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(Future<Channel> f) {

                if (f.isSuccess()) {

                    Channel ch = f.getNow();

                    ChannelFuture lastWriteFuture = null;
                    try {

                        lastWriteFuture = ch.writeAndFlush(my data here;

                         // Wait until all messages are flushed before closing the channel.
                        if (lastWriteFuture != null) {

                            lastWriteFuture.sync();
                        }
                    } catch (JsonProcessingException | InterruptedException e) {

                        e.printStackTrace();
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    // Release back to pool
                    pool.release(ch);
                }
            }

        });

if i do not use channel pool then all work fine & i get the proper response in ClinetHandler class.
Any suggestion where i am breaking ?
I am using Netty 4.0.28 final.
Comment: can you post the code where the server sends the response?
Answer: i got the answer on the #netty IRC channel
so i need to remove this line
.handler(new ClientInitializer());

And whatever my ClientInitializer is doing, i need to do that in the SimpleChannelPoolHandler channelCreated method.


Is it harder to play in a key with more flats or sharps?

Question: This is a very naive question, but I tend to perceive a song with a key signature that has more flats or sharps to be more difficult than the same song written in a key with fewer flats or sharps.
Is this the typical case and if so why do the sharps and flats make the song more initially intimidating?
Comment: Not if you transpose it :-)
Comment: Related answer of mine: http://music.stackexchange.com/a/4097/28
Comment: It's not a naive question, but it's a beginner's question.  Is "cat" an easier word than "elephant" because it's shorter?  Maybe, to a beginner reader.  You soon get past that point.
Comment: Actuslly, on piano, the easiest key to play in is possibly F# major. Self-taught 'pub pianists' often use this key. As it's based around all 5 black notes, there's a lot less chance of hitting a wrong one, at least when staying close to the tonic tonality. Try it, you'll see what I mean! It's obvious why a beginner would see a 'big' key signature as harder of course.
Comment: I think this should be on-topic, as it can be explained with ergonomics of specific musical instruments, a decidedly not opinionated set of information.
Answer: Every instrument has keys that are easy to play and and keys that are not very easy to play in. There are even transposing instruments that are built to play in a certaint key natrually that isn't in the key of C so for some instruments playing in the key of C, which has no sharps or flats, is actually harder. For example the first instrument I learned was the trumpet which is a Bb instrument so for me the first songs I learned were in Bb which were very easy to play on the trumpet.
There's another side of this question that I can understand especially when I was first learning to read music which is as you deal with more accidentales pieces get harder to read and that is understandable especially when you have a lot of accidentals outside they key you are in. As you get more comfortable reading music, a piece that you thought was in a harder key to play might have just been harder for you to sight read initially and is actually easier to play then something in then a key with less accidentals.
Answer: Yes, I think it's generally true for a simple reason: we all (well just about all) learn to read the notes of the staff initially in their default, natural position.  We learned our "Every Good Boy Does Fine" and so forth before we learned our sharps and flats.  When we do learn about sharps and flats, they're presented as exceptions to what happens normally. Which is baked right into our notational system: "This line is B. Except when it's got this doohicky on it, then it's a B flat."
So when we read a score in some key that has sharps and flats (i.e. not C maj, A min, etc.) we treat the sharps and flats as exceptions to the rule we learned.   "Ah, we're in G major, so I have to keep track of the fact that every time I see something that looks like a note on F, it should actually be played as an F#."  And here's the thing: remembering exceptions to a rule increases the cognitive load of a task by a whole bunch.
It may not be any harder to play once you have it down, and, say, have it memorized. But getting it off the page and into your instrument in the first place will always take at least a little bit more cognitive effort than it would to read something with fewer sharps and flats, even if one is very fluent at reading.  If one is not very fluent at reading, every additional black note is going to increase the cognitive load by quite a bit.
Answer: I can definitely understand why some keys appear to be more intimidating than others, but  this intimidation is most likely caused by a lack of familiarity. For example, consider the sentence "I adumbrated a plan so vague that my fellow politicians slapped my back in approbation." This sentence seems fairly intimidating, especially if you aren't familiar with the words adumbrated and approbation, but as you get more familiar with these words they seem less intimating and hopefully become a part of your vocabulary. In other words as you get more familiar with different keys they will become part of your vocabulary so to speak and unsurprisingly like these words it takes some time to get familiar with them.
Comment: Yes, this is true. Beginner French horn students read in the key of F a lot, so when they read the key of C, they tend to accidentally play Bb. On the other hand, beginner orchestra members (orchestras favor sharp keys) who read in the key of F will likely have to consciously remind themselves to play Bb and not B natural. It's all about what you're used to working in, because you're technically just working from a mental "default" and altering that whenever you play in a key with more sharps or flats than you are accustomed to.
Answer: What key signatures are "easier" can depend on what instrument you're playing
and on whether you mean "easy to read" or "easy to sound the notes".
It may also depend on what you're used to.
On the piano, I like pieces with a few sharps or flats in the key signature
because it is easier to pass the thumb under when you are going from a black
key to a white key than going from white to white.
The C major scale may be the easiest to learn, but I find it the hardest
of all the major scales to play well.
It's also easier to strike a black key than a white key
at the upper or lower end of a chord without also striking an adjacent key,
or to strike two adjacent black keys reliably with one outstretched finger while
not accidentally striking a third key.
Once I am familiar with a certain key signature, I don't find it significantly
harder to read than C major, because I have learned through practice to
associate a note written on a particular line of the staff with a particular
key on the keyboard, which may be one of the black keys.
What is more difficult sometimes is to change
from one key to another in the middle of a piece, even if the change
is to a key with fewer sharps or flats.
But if you have only ever played pieces written in C major on a piano,
and you are suddenly presented with something written in A-flat major
(four flats), of course it will be intimidating.
Individual sheet music for some band instruments is often written in
a different key than the key in which the music is actually played.
For example, if the piece the band is playing is actually in E-flat major,
some instruments will be playing from sheet music with no flats at all,
that is, the music is written in C major but the instrument itself
transposes the notes to E-flat major.
That is, the musicians are taught to finger the instrument in a certain
way when they read the note C on the sheet music, and the actual sound
produced is an E-flat.
(Another instrument from the same series, fingered the same way,
will produce a B-flat.)
If the band actually plays a tune in C major, the E-flat instruments
will be reading music with three sharps in the key signature, and their
fingerings may be more difficult. So those instruments may be significantly
easier to play in keys with three or four flats (considering the key in
which the actual sounds of the music are produced) than in keys with
no more than one sharp or flat.
Answer: I believe this is very subjective and varies from musician to musician. To give you an example, I play the trombone (Bb key) and while learning the instrument flats where more common than sharps, so that's what I grew more used to it. In fact, I wouldn't even say it's hard to play the sharps. What is hard is reading when there are a lot of sharps in there, so it's really more about what's more common in your perspective. After all, for every flat, there's a corresponding sharp and vice versa.
Answer: You can achieve a certain paradigm shift when you realise that scales are just a series of notes a set amount of semitones / intervals from the root note.
The Major scale for instance has it semitones between the 3/4 and 7/8 scale degrees. So if you have 8 notes starting and ending on the same letter name with semitones at these places then you have a Major scale.
That being said there should be no need for this to be difficult if your theoretical foundations are well met. Reading the OP makes me feel that this is the root of your problem.
Answer: I hope these assumptions for what makes a piece with several accidentals in its key signature harder to read (and therefore harder to play) apply to pretty much everyone who reads music with key signatures:

Due to their rarity, double sharps and double flats make music hard to read.
Due to how unintuitive they are, notes that are enharmonic with white notes but have accidentals on them (e.g. E#, Cb, Fb, B#) make music hard to read.

Now to find various reasons why either of the above can occur in music, and therefore, whether music with several sharps in the key signature or several flats is harder to read:

Dominant of minor key: The moment you hit F sharp minor, you already need an E# in order to spell out its dominant triad (C#-E#-G#). Even worse, G sharp minor needs a double sharp to spell out its dominant triad (D#-Fx-A#). Thus, this makes music in key signatures with several sharps harder to read.
Secondary dominant: V/V, V/vi, and V/ii all require more sharps than their home key normally has. For example, V/V of C major is the D major chord, which contains an F#, unlike C major. This runs into the same dangers of needing double sharps and stuff-like-E# as dominants of minor keys do. Therefore, this makes music in key signatures with several sharps harder to read.
Borrowing from tonic minor: The key signature of the tonic minor of a major key is 3 flats further on the circle of fifths than the major key's key signature. This shows when you borrow chords from the tonic minor (such as bVI and the widespread vii°7)--you suddenly need to write more flats (or naturals). This can reach the point where you need double flats (for example, vii°7 of D flat major is C-Eb-Gb-Bbb). Thus, this makes music in key signatures with several flats harder to read.
Neapolitan chord: This is otherwise known as bII (or bII6). It sounds just like bVI/iv, so there's more bias towards double flats. (For example, the Neapolitan of A flat major is Bbb-Db-Fb.) Thus, this makes music in key signatures with several flats harder to read.

We'll need to analyze how often the four are used in music--and how often people just use enharmonic equivalents instead (such as A-C#-E for the Neapolitan of A flat major)--to fully determine whether music in key signatures with several sharps or with several flats is harder to read overall.
Answer: This depends on what you are used to. When playing in orchestra, it is often so that the most common keys are with 2, 3 or 4 flats (Bb, Eb and Ab). This cause many flute players to be more comfortable with having some flats, than playing in C that is without any flats or sharps.
That said, I play in a wind orchestra where we often play with pop artists, and our conductor arrange the music for the orchestra. For pop/rock music, it is more common with sharps in the signature, because this is more easy for guitar players, where common keys are G, D, A and E.
So we have actually become quite familiar with playing pieces with a lot of sharps, which become A LOT of sharps for Bb instruments (clarinets, trumpets etc.) and Eb instruments (saxophones)...
Answer: I feel the same as Codeswitcher:
For me, remembering which of the black notes to play when dealing with more than 3 or 4 sharps or flats has always been tough. I would appreciate any suggestions in learning how to read the music while my brain is also interpreting each note that should be a sharp or flat. (Other than manually adding the sharps and flats next to every note in the piece).  I feel the same way when trying to think ahead more than 3 or 4 moves in chess.
Comment: Practice your scales.  Parallel motion and contrary motion.  Yes its a bit boring but you might be surprised how quickly you learn which notes are in which keys.


how to click button using find_element_by_xpath with inner html in selenium webdriver python3.7

Question: first_click_content = driver.find_element_by_xpath("//div[@class='recent-report-wrapper']/div[2]/div/div[6]/div[2]")

print(first_click_content.get_attribute('innerHTML')

The above code give the result like this:
<button class="buttonWhite js-report-rerun">Re-run</button>
<button class="buttonWhite marginLeft js-report-edit">Edit</button>
<button class="buttonWhite marginLeft js-report-remove">Remove</button>
<button class="buttonWhite marginLeft js-report-save" style="display: none;">Save </button>
<button class="buttonWhite marginLeft js-report-view-errors" style="display: none;">View Errors</button>
<button class="buttonReportGreen marginLeft js-report-view" style="display: none;">View</button>
<button class="buttonReportGreen marginLeft js-report-download" style="display: inline-block;">Download</button>

I want to click the first button, how can I do that?
Answer: As the all the buttons are JavaScript enabled element you need to induce WebDriverwait for the desired element to be clickable and you can use either of the following solutions:

CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.buttonWhite.js-report-rerun"))).click()

XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='buttonWhite js-report-rerun' and contains(.,'Re-run')]"))).click()

Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


How to check if an edited form is editing a translated node

Question: I have a content type named film.
Original language of a film is FR.
Let say I have 2 translatable fields on a total of 10 fields in film.
I am using this code to alter the add/edit form of film:
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'node_film_edit_form': // edit
    case 'node_film_form': // Add
      alter_film($form, $form_state, $form_id);
      break;
    ...
  }
}

In the alter_film function, I would like to add a custom submit only if the edited form is for French (Original language)
function alter_film(&$form, FormStateInterface $form_state, $form_id) {
  ...
  //HERE IS MY PROBLEM:
  //HOW TO KNOW IF IT IS TRANSLATED FILM
  if (! $is_translated_film){
    $form['actions']['submit']['#submit'][] = "submit_film";
  }
  ...
}

The question is: what check could be made to know which form is edited: the original language form (10 fields) or the translated language form (2 fields)
As a side question, I don't understand why there is no difference in the dpm($form); output if I execute one in the French form and the other one in the English form.
I am asking this, because in /admin/config/regional/content-language, I have checked Hide non translatable fields on translation forms.
And I would expect to have 10 fields in the french form array and only 2 (translatable) fields in the translated form array.
In the translated form, only 2 fields are displayed as expected, but I am wondering why the 10 fields are included in the array.... I ask that just out of curiosity
Comment: **All fields are included** because it is decided later when the form is processed and rendered which fields are displayed. You can use the same tactics for your custom submit. Attach it in any case and then check when the custom submit is called whether you have an original or translated entity in $form_state (with the code from your own answer).
Answer: I could answer myself for the first question. The following line will give me the edited language.
$form_state->getFormObject()->getEntity()->get('langcode')->value;

But, maybe, the following is better:
$is_original_language = $form_state->getFormObject()->getEntity()->get('default_langcode')->value;

It is better, because original language could vary. In this case on the Add/Edit Node, Add new translation and Edit translations the return value can be parsed directly. Add Node or add new translation returns a Boolean while the edit forms return an int (1/0).
Comment: This was a life saver for me just now.  Cheers. :)


Rubik's Cube: Number of Permutations of the Corner Position Orientations

Question: The Rubik's Cube has 8 corners, and each corner has 3 stickers.  A corner can be in 1 of 3 orientations, i.e. any of the three stickers can point up, giving $3^8$ possible permutations of the corner orientations.
However, 1/3 of those permutations are unreachable (more detail here).  It's not possible, for example, to disorient one corner.  So, there are $3^7$ reachable permutations of the corner orientations.
As an aside, there are 8! arrangements of the corners, so there are $8!*3^7$ possible permutations of the positions and orientations of the corners.
What I can't figure out is how many ways the pieces in the corner positions can be oriented.  Instead of looking at the ways the corner pieces--the red-blue-yellow, red-green-yellow, red-green-white, etc.--can be oriented, I want to know how many ways the pieces in the up-left-back, up-right-back, up-right-front, etc. positions can be oriented.
As an example, I'll arbitrarily define a corner cubie as "oriented" if it has a red or orange sticker facing up or down, rotated once if it has a yellow or white sticker pointing up or down, or rotated twice if it has an blue or green sticker pointing up or down.  Thus, rotating the UP or DOWN face does not change the orientation of any corner cubies, whereas twisting any of the other four sides changes the orientation of four corner cubies.
I'll also arbitrarily index the corners cubies and positions as follows:
0   1   2   3   4   5   6   7
ULB URB URF ULF DLF DLB DRB DRF
RBY RGY RGW RBW OBW OBY OGY OGW

(In the solved state, the up-left-back position is occupied by the red-blue-yellow cubie, ..., and the down-right-front position is occupied by the orange-green-white cubie.)
So, twisting the FRONT face 90 degrees changes the orientation of four corners, 2, 3, 4, and 7.  Subsequently twisting the TOP face 90 degrees, note that the permutation of the orientations of the corner cubies remains the same; however, the orientations of the positions change.  E.g. the RBY (0) cubie is still oriented, but the cubie in position ULB (0) is now disoriented.
By position, then, how many ways can the orientations be permuted?  For what it's worth, I've empirically found the number to be 6,513.  I would like to verify mathematically that that number is correct.
Edit: Here's a snippet of code that illustrates what I'm looking for.
    // Permutation of the orientations of the pieces occupying the
    // 8 corners.
    array<uint8_t, 8> cornerOrientations =
    {
      iCube.getCornerOrientation(CORNER_POSITION::ULB),
      iCube.getCornerOrientation(CORNER_POSITION::URB),
      iCube.getCornerOrientation(CORNER_POSITION::URF),
      iCube.getCornerOrientation(CORNER_POSITION::ULF),
      iCube.getCornerOrientation(CORNER_POSITION::DLF),
      iCube.getCornerOrientation(CORNER_POSITION::DLB),
      iCube.getCornerOrientation(CORNER_POSITION::DRB),
      iCube.getCornerOrientation(CORNER_POSITION::DRF)
    };

    // Treated as a base-3 number, converted to base-10.
    uint32_t permInd =
      cornerOrientations[0] * 2187 +
      cornerOrientations[1] * 729 +
      cornerOrientations[2] * 243 +
      cornerOrientations[3] * 81 +
      cornerOrientations[4] * 27 +
      cornerOrientations[5] * 9 +
      cornerOrientations[6] * 3 +
      cornerOrientations[7];

    return permInd;

Versus:
    // Permutation of the orientations of the 8 corner pieces.
    array<uint8_t, 8> cornerOrientations =
    {
      iCube.getCornerOrientation(CORNER_PIECE::RBY),
      iCube.getCornerOrientation(CORNER_PIECE::RGY),
      iCube.getCornerOrientation(CORNER_PIECE::RGW),
      iCube.getCornerOrientation(CORNER_PIECE::RBW),
      iCube.getCornerOrientation(CORNER_PIECE::OBW),
      iCube.getCornerOrientation(CORNER_PIECE::OBY),
      iCube.getCornerOrientation(CORNER_PIECE::OGY),
      iCube.getCornerOrientation(CORNER_PIECE::OGW)
    };

    // Treated as a base-3 number, converted to base-10.
    uint32_t permInd =
      cornerOrientations[0] * 2187 +
      cornerOrientations[1] * 729 +
      cornerOrientations[2] * 243 +
      cornerOrientations[3] * 81 +
      cornerOrientations[4] * 27 +
      cornerOrientations[5] * 9 +
      cornerOrientations[6] * 3 +
      cornerOrientations[7];

    return permInd;

Note the CORNER_PIECES and CORNER_POSITIONS.  For CORNER_PIECES I calculate (and empirically find) $3^7$ permutations.  For CORNER_POSITIONS I empirically find 6513 permutations with a breadth-first search to depth 9, but don't understand why.
Comment: Your last edit switches the direction of the twist as you've defined it, but thankfully it doesn't invalidate my answer. Corner pieces that belong at diametrically opposite locations have their colours ordered in opposite directions, so will rotate in opposite directions when you increase their twist.
Answer: That's a strange definition of orientation you are using. Half the corner pieces turn clockwise if you change it from oriented to twisted once, and the other half turn anti-clockwise.
With the normal definition of orientation, only $3^7=2187$ orientations are possible instead of $3^8=6561$ since the total twist of the pieces must be zero modulo 3. With your definition, you negate the twist of any four of the locations. They can indeed be any four, since all permutations are possible making any arrangement of the two types of corner pieces possible. This original twist constraint no longer holds, but instead you have the constraint that you can split them into two sets of four locations with the same total amount of twist mod 3.
It turns out that with this new definition, only $48$ of the $6561$ orientations cannot be reached. These are the configurations where there are 7 locations with one twist value and the 8th location with a different value. Whichever way you split this into two sets of four, the two sets will have different total twist values. There are 8 possibilities for the odd-one-out location, and 3 twist values it can be, and 2 twist values for the rest, giving a total of $8*3*2=48$ impossible configurations.
Proving that all other arrangements are reachable is a bit of case work, but it can be reduced by realising that

the order of the locations does not matter,
twisting all the locations by the same amount is possible (since four pieces are twisted in opposite directions to the other four), and
we can negate all the twists.

From this we can assume without loss of generality that there are at least as many 0s as 1s, and at least as many 1s as 2s. That leaves only the following cases to check:
00000000 = 0000+0000
00000001 = (impossible)
00000011 = 0001+0001
00000012 = 0000+0012
00000111 = 0000+0111
00000112 = 0011+0002
00001111 = 0011+0011
00001112 = 0001+0112
00001122 = 0000+1122
00011122 = 0011+0122
Comment: @benbotto The correct way to define twist would only look at one pair of opposite colours, say white/yellow that belong on the U/D faces. Untwisted obviously means white/yellow is in the U/D face. Twisted once means it is twisted clockwise from that, so for the URF location that means the white/yellow is in the R face, for the UFL location it means the white/yellow is in the F face, for DFR in the F face, DLF in the L face,  and so on.
Comment: Thank you.  This is a great answer and I understand now why my search came up with 6,513 permutations (3^8 - 48).  But more importantly, it shows that I have a fundamental misunderstanding of corner orientations in my program (which I'm struggling to tackle).  As a side note, I've spent an unhealthy amount of time on your puzzle page over the years, and I really appreciate your work.
Comment: I wonder if I could bother you with some questions about the correct definition of corner orientation.  I created a chat room if you have time: https://chat.stackexchange.com/rooms/119982/rubiks-cube


Which test would be best for my thesis study with 2 variables and 2 levels? I'm considering to run on SPSS, 4 separate correlation tests, OR a MLR

Question: My thesis questions on whether a certain type of thoughts are associated with stress levels. There are two types of thoughts and two different levels. What should I use? The first variable is the direction of thoughts (upwards vs downwards) and the controllability of thoughts (controllable vs uncontrollable). I also considered doing stepwise regression to talk about the potential interactions.
This is a psychology study. Really appreciate the help :)
Comment: do you have a regression problem (e.g. a response variable and some covariates) or do you want to test for association between two qualitative variables?
Comment: Hi Utobi, thank you for your response. I'm simply testing for the association. So the plan is really to look at whether upward comparative thoughts were associated with higher levels of stress, and whether downward comparative thoughts were associated with lower levels of stress. Same goes for the controllability of it. I had surveyed stress levels on a Likert scale of 1-5. :)
Comment: If you found my answer useful, please consider accepting it by clicking on the tick mark. Thank you.
Comment: you may have a look at this `R`-based (though not `SPSS`) answer https://stats.stackexchange.com/questions/591851/using-chi-squared-test-to-compare-distributions-in-r/591955#591955
Comment: hmm... in that case, will cramer's V work? Since I will need to use SPSS?
Comment: Cramer's V is a normalized version of the chi-squared statistic and is useful for measuring the strength of the association. It can also be to test for the presence of association but it shouldn't add very much to the chi-squared test https://stats.stackexchange.com/questions/585828/how-are-the-confidence-interval-of-cramers-v-and-the-chi-square-statistic-relat
Answer: If the sample size is small it is advisable to use Fisher's exact test which provides an exact p-value.
With large samples, you may use a chi-squared test or the G-test.
I'm not familiar with SPSS but by searching the web, I think you will be able to find tutorials on how to run Fisher's exact test and the chi-squared test in SPSS.
Comment: here is a tutorial on Fisher's exact test in SPSS https://www.scalestatistics.com/fishers-exact-test.html