Key choice for brass instruments

Question: I've been told several times that brass instruments prefer to play in keys with flats, rather than sharps. As a trumpet player myself, I cannot relate to this preference. E major is just as easy or hard as A flat major. I interpreted it as being the playing key, not the concert key.
I'll take that the preference is true, since I've heard it from several trustworthy sources, but why is that? I have several hypotheses:

Tradition. Bands (brass bands especially?) usually play in keys with flats, therefore that is what the players are used to, and more comfortable with. But how did the tradition start?
Intonation. The construction of valve instruments make the intonation better in keys with flats. For example in A major: the low C# of the trumpet is naturally high, whereas a good intonation should have it low as the third of a major chord. I cannot think of a counterexample right now.

I welcome guess answers, but please mention that you are just guessing if you do not actually know for a fact.
Comment: Are you asking about the preference of the instruments, or their players? I always thought it was because it's easier to make a given note flat on a brass instrument, as opposed to easier to make a note sharp on a guitar. Guess, therefore comment.
Comment: I also think your statement concerns concert key, not written. I think it simply has to do with the number of sharps or flats, and since many brass instruments "naturally" play in flat keys (concert!), those are the easiest and sound the best. See here: [Good keys / Bad keys](http://www.musicarrangers.com/star-theory/p21.htm)
Comment: My first reaction was that they meant concert key, but these sources replied that they did mean playing key.
Comment: @Gauthier This preference has to do with the fundamental resonant frequency of the instrument. For trombone and tuba (non-C non-transposing instruments, Bb is first position (tbn.) and can be open for tuba (BBb Tuba), for trumpet, Bb is open as well. Since the open, resonant frequency of the instrument is set in a "flat" key, music written in flat keys will sound more resonant than music written in keys that doesn't naturally resonant with the instrument (E major), thus, brass players see more music written in flat keys, thus, brass players favor flat keys. Sharp keys are harder to tune also.
Comment: @jjmusicnotes: this assumes concert key. I am talking about playing key. "Sharp keys are harder to tune" is very much of interest, could you develop this?
Comment: @Gauthier Trumpet is the only brass instrument you need to transpose, and even then, trumpets very commonly read in flat keys. As I mentioned in my other comment, sharp keys are harder to tune because those keys don't naturally resonate with the fundamental of the instrument. Thus, since you're fighting the natural tendency of the instrument, which resonates more freely in flat keys, tuning intervals and pitches in sharp keys will be more difficult. Also, FWIW, much band music is written in flat keys while much orchestral music is written in sharp keys - it's easier for the strings.
Comment: @jjmusicnotes? Only instrument, how about French horn, tubas? I'm not sure why flat keys resonate better with the fundamental of the (open?) instrument? Why would written Bb major (one whole tone below open) resonate better than A major (one and a half tone), and A major worse than Ab major?
Comment: @Gauthier Oh! I *completely* forgot about horns!! Yes, obviously horns are included as transposing instruments. Tubas are non-transposing. Yes, even if the tuba is F, Eb, Bb, or C, none of them transpose. With the exception of C tubas, flat keys resonate more fully because of the open tube. Because most brass instruments are pitched in flat keys (tpt, horn, tbn, euph, most tubas) they use *less* tubing when playing in flat keys, thus, the intonation is better and the instrument resonates more freely. With brass instruments, the more tubing you add, the more out of tune / stuffy the sound goes.
Comment: @Gauthier For example, on a CC tuba, F and Bb scales most just use 1st, 2nd, and open valve combinations creating a very open, resonant sound. A major on the other hand uses no open valves. It's still a very friendly key, but less so than F or Bb. On my tuba, Db is just a very stuffy key. Obviously, you can play devil's advocate with enharmonics (Db/C# or Gb/F#), but the reasoning for flats used here may be more psychological than acoustic. Putting the keys in flat can make people think of "darker" sounds or reduce key-signature anxiety. As a friend of mine said, "A# is *not* the same as "Bb".
Comment: Reading all the theory about resonance makes me ask the question - is it not possible to make some of these brass instruments of a slightly different length/bore, so as to allow them to play more in tune in sharp keys? Or is it that we're just too far down the line, (too many standard ones exist), and it would only be an academic type excercise?
Comment: @tim, the horns sound best in their open position, and the more valve tubing added, the worst they sound. I guess it has to do with where vibration nodes and bellies appear on the instrument. As soon as you add a valve, the shape of the instrument becomes more complex, nodes are at suboptimal places, and the instrument sounds worse. I guess you could make an instrument optimized for the all valves in position, though. But the shape of the tube being less "natural" than open, I suppose the all-pressed position on that wouldn't sound as nice as current instruments in open.
Comment: @Gauthier - what I meant was - if a trumpet, for example, was made so open it was D rather than Bb, surely it would sound better in that key - but not so good in Bb?
Answer: Adding to the narrative in other answers,
here is a chart that might help further explain why brass players
tend to prefer sheet music written in keys with flats.
As is shown, written keys that exclude the
"worst-to-play usual notes" (elaborated below)
on common brass instruments (except French horn)
are overwhelmingly keys with flats.
This is especially true for almost all lower-brass parts,
in which even the written-and-concert key of C, with no flats,
includes the worst-to-play notes for all but C tuba and triggered trombone.
The specific keys mentioned in the
question as being equally playable on
B♭ trumpet—written keys
E and A♭ —serve
well to demonstrate this chart.
The row for B♭ trumpet recognizes
the note scored as C♯ or D♭ as the most troublesome to play,
so keys with at most 1 sharp or 3 flats
are likely to be favored because they exclude C♯/D♭.
The aforementioned keys of E and A♭, however,
contain 4 sharps and 4 flats, respectively,
and thus include C♯/D♭ and are equally disfavored here.
If you are comfortable with music in these keys,
you are no doubt an experienced musician.
Not only are both keys relatively difficult to play
but trumpet music in A♭
(concert key G♭) is also quite rare.

                                                                   Written keys WITHOUT
                                                Worst-to-play         worst-to-play
  Name of        Version of      Open key         usual note           usual note
 instrument      instrument    ------------    ----------------     ------------------
  on score       considered    Con-   Writ-    Writ-    Valves/     How many  How many
                               cert    ten      ten    position      sharps    flats

F French horn      4-valve      F      C       G#/Ab     2-3         2,1  0  1,2
 Bb Trumpet        3-valve      Bb     "       C#/Db    1-2-3          1  0  1,2,3
Baritone T.C.         "         "      "         "        "            1  0  1,2,3
Eb Mellophone         "         Eb     "         "        "            1  0  1,2,3
Alto/Tenor horn       "         "      "         "        "            1  0  1,2,3
    Tuba            C tuba      C      "         "    1-2-3, 2-4       1  0  1,2,3
    Tuba           Eb tuba      Eb     Eb       E/Fb      "          6,7       2,3,4,5,6
    Tuba           Bb tuba      Bb     Bb       B/Cb      "            7     1,2,3,4,5
Baritone horn      4-valve      "      "         "        "            7     1,2,3,4,5
  Euphonium           "         "      "         "        "            7     1,2,3,4,5
Baritone horn      3-valve      "      "         "      1-2-3          7     1,2,3,4,5
  Euphonium           "         "      "         "        "            7     1,2,3,4,5
  Trombone        slide only    "      "         "       7th           7     1,2,3,4,5
  Trombone        F trigger     "      "    C#/Db,F#/Gb  5th              0  1,2,3

"Worst-to-play usual note"
is an ad hoc designation
likely to find agreement among many players due to some of these factors:
•
  The note is in the range usually scored for the instrument.
•
  With 3 valves but no fingered slide,
  timbre is compromised when a note is lipped into tune.
•
  With 3 valves and a fingered tuning slide,
  coordinating the slide quickly is difficult.
•
  With an in-line 4th valve, pinkie-vs-ring-finger agility
  is anatomically hampered.
•
  With an opposite-hand 4th valve, coordinating the hands quickly is difficult.
•
  On a trombone, a quick slide excursion is a gymnastic feat.
•
  French horn players have a right to complain too.

Admittedly:
•
  Some fingering/position sequences and almost-worst notes
  play circumstantial roles as well.
•
  Some rarer fingerings/positions are worse than those shown,
  but tend to also avoid flat keys.
•
  A trombone's 7th position is the worst of the worst.
  An F attachment/trigger alleviates this.
•
  As French horn typically plays high in its range,
  its usual worst fingering is relatively benign.
Have another usual note that you least favor
or instrument that would help to mention?
Please comment or edit.

This comes from a community band and orchestra member
who fills for whatever non-percussion parts are needed during rehearsals,
playing the most appropriate brass instruments
that happen to be along or available.
Comment: Excellent answer!  It's worth noting that the octave makes a difference in the "awkwardness" of a key.  On a trombone, a B♮2 has to be played in 7th position (without an F attachment), but a B♮3 can be played in 4th position and a B♮4 is usually played in 2nd position.  This means that a piece in D major (say) is easier to play on the trombone if it doesn't go much below G3.
Comment: Also, a related aside:  as a trombonist, I harbor a grudge against Aaron Copland for how he wrote the last movement of his Third Symphony.  The trumpets get to do the "Fanfare for the Common Man" theme in B♭, with lots of nice open fingerings.  Then the trombones have to play it in B♮.
Comment: Can you add the F tuba please?
Comment: Thank you for the difference an octave can make, @Michael Seifert. Thank you for playing trombone! And curse you, Copland, I never suspected that a composer would write a trombone passage in B♮. Was it because this instrument sounds broader in the long throw?  (Also _praise_ you, Copland, for other reasons.)
Comment: Dear @Elements in Space , F Tuba is my alter ego.  Will add details to post after  analysis.  For now, refer to F horn.
Answer: Most wind instruments transpose in a way that adds sharps.  Horn and English horn are in F (add 1 sharp); trumpets, and half of the clarinets and saxes in Bb (add 2 sharps), and the other clarinets and saxes in Eb (add 3 sharps).  The low brass reads concert pitch, but tenor trombones and euphoniums are actually Bb instruments as well.  Bassoons are sort of in F by this same logic.  Tubas come in C, but also in each of the 3 listed transpositions.  Aside from some very esoteric instruments, nothing transposes the other way.
So if, for whatever key you choose for your composition, the winds are mostly adding sharps, then flat keys are friendlier.  Concert C puts trumpets in D and alto saxes in A.  So while E major might seem like a perfectly reasonable key for strings or piano, your trumpets end up in F# and alto saxes in C#.  Of course, a good player should be able to play in any key, but it's just not as easy.
Furthermore, brass instruments work by adding tubing to lower the pitch, so unless you're already at the bottom of the partial, you can always flatten a note.  But on trumpet, even just C -> C# or G -> G# is crossing over a break, going from the highest note of one partial into the bottom of the next.  And then there are the tuning issues you already mentioned.
Comment: I like the concept 'adds sharps'. Makes it easy to understand. 'Takes away flats' would work if the key is already a flat key. Same thing really.
Comment: I am on page with that concept, but I am sure my references did mean playing key.
Comment: I'm not sure about your "crossing breaks" reasoning. I understand that you mean that playing G to G# jumps from one partial to another, but we're talking keys here. You have either a G or a G#. If it's a G you have such a break to the A (or Ab), if it's a G# you have such a break to the F#.
Answer: I interpreted it as being the playing tonality, not the concert tonality.
There is your mistake.  As a comment about brass players, this statement is for the benefit of those not playing the instrument and consequently is about concert pitch.
Indeed, it does not make much sense to speak about playing pitch in this context since the playing key differs even within the brass section.
Comment: As @MattPuman wrote, most of them are still adding sharps. Besides, my question is about preferred keys, a given arrangement might fail to make everybody happy.
Comment: The wording of the question has changed from using "tonality" to "key".
Answer: All answers (and their up-voters) up till now fail to take into account this essential parameter: I am talking about playing key, not concert key. A comment from @jjmusicnotes made me think of this possibility (a wild guess):
For the same amount of flats or sharps, more flat keys feature the open C and G.
F major or G major have both C and G, so they're not relevant.
2: Bb major has both C and G, while D major misses the open C (it has the middle E though, which Bb major lacks).
3: Eb major has C and G, A major has neither.
4: Ab major has both, E major has none.
5: Db major has C, not G, B major has no open tone.
The hypothesis is that the keys that feature open tones are preferred because the instruments resonate better on open tones.
Answer: This seems much more of a worry to composers/arrangers than to brass players!  OK, ask for a preference, we'll come up with one.  But it's not important.
There are two notes on trumpet that require all three valves to be depressed.  Written low C# and the F# below.  All but the cheapest student instrument have the technology to extend the 3rd (and sometimes 1st) valve slides so as to play them in tune.  They aren't hard to play.  But that range of the trumpet has neither the brightness of a trumpet's higher notes or the appealing flatulence of a trombone's low register.  Write it if you want, but know what you'll be getting.
Comment: It is from the viewpoint of the arranger that I am asking the question. It is important for the arranger to know what brass players prefer, if given the choice, the arranger could make the one that is easy on the players. I play the trumpet, and when arranging for trumpets I do try to avoid the low C#, because even if it's manageable, depending on the trumpeters' level, its intonation doesn't often get the attention it should. I am guilty of that as a player myself.
Comment: Interesting that we (as I suspect most trumpertrs would) are referring to that note as C#, not Db.
Comment: Which partial a tone builds on is nothing you think about when you play, especially if you've been playing since you were a kid. C# comes earlier than Db in the list of key signatures.
Answer: Here's the test - ask a bunch of brass players to first sight-read a passage with n sharps in the key signature and then a different passage of similar difficulty with n flats in the key signature. Count the number of errors for each performance and collate the results.
My expectation (contrary to the received wisdom quoted in the OP) is that the accuracy would fall as the n increases, but would not depend on whether the key contained sharps or flats.
My feeling is that brass players, in common with most other musicians, prefer keys with few sharps or flats. Keys with lots of sharps or flats aren't innately harder to play - but because they often get less practice they're less familiar and so don't fall automatically under the fingers.
Answer: My preference ,as a tuba player, I can't really read more than two sharps. Yet I can read down to all flats fairly easy. Its just much more common to see flats than sharps. This is of bably likely do the jump from bass clef to treble. I only have a sharp if say like a sax has four sharps.

Key choice for brass instruments


Fieldable entity issue

Question: I currently have an event entity, which is fieldable. My question is, how do I make it appear under admin/structure, and how can I access the Manage Fields page from the admin menu? Is there a tutorial on this? Any help is highly appreciated since I could not find anything related.
Answer: You'll need to provide a menu item and page that lists information about your entity type (typically settings). If you provide multiple bundles you'll need to provide a page for each bundle.
After you've done that you can add a simple snippet to your hook_entity_info similar to the foreach loop at the bottom of node_entity_info(). Specifying the 'admin' info under your bundles will provide the "Manage Fields" and "Manage Display" tabs for the path specified. Note that if you do not have multiple bundles, the only two required keys under the 'admin' section are 'path' and 'access arguments'
Keep in mind that the path referenced in the ['bundles'][BUNDLE_NAME]['admin']['path'] section has to exist and be defined elsewhere in your hook_menu. Field module will only take care of the two tabs and the pages they link to.

Fieldable entity issue


How do I redirect users from the registration page to Paypal?

Question: Only users with a "Sign Up Code" are allowed to sign up to the website. If they provide a valid signup code, they will be directed to a sign up page where they can provide user information, and PayPal processing is used to process the fee. On completion of payment an account is created.
How can I redirect user to Paypal?
How can I check the payment is paid by user?
How can I create the account if the user paid?
Comment: This is a very broad question.  I would advise revising it into several specific smaller questions.
Comment: you changed the question completely !!!
Answer: Use the Drupal Commerce module.

Add the Paypal payment method module; hook the login/register form to provide a different redirect page, or use the Rules module.
You can look at the generated transaction.
I would create the account anyway; set a flag, or something, for payed accounts.
Answer: My suggestion for you is to use hook_user($op) implement it in your module, and work with <code>$op</code>.
I personally have done work like you want with that hook.
Answer: I guess using Drupal commerce will be extra load(not sure).

Custom Way:

Over ride drupal registration form with your custom form
submit handler of your custom form will keep all submit value in session

How can I redirect user to Paypal?

You can create a custom payment script
commerce paypal module will be helpful to see the payment process.commerce paypal module has both off-site and on-site payment options.

How can I check the payment is paid by user?

IPN is what paypal returns after a payment(success or failure).
You can check IPN response to get the payment status.
How can I create the account if the user paid?
If successful payment is done create user from session values using user_save() .


Find the exact distribution of the MLE estimator and $n(\theta-\bar{\theta})$ exact and limiting distribution

Question: I have another problem and the density is something like this:
$$f(x,\theta)=\frac{1}{\theta} \text{if }0\le x\le\theta \text{ for some }\theta>0$$
$$f(x,\theta)=0 \text{ otherwise}$$
Given the sample $X_1,...,X_n$ be iid.
I found the MLE to be $X_n$ which is the the maximum of the sample.
I'm supposed to find the exact distribution but I'm not sure what do they want? Do I derive the density and CDF of a sample maximum?
Lastly I'm supposed to find the exact distribution and asymptotic distribution of
$$n(\theta-\hat{\theta})$$
I know about Lindeberg Levy-Central Limit Theorem but I'm not sure how to apply that into this case or deriving the exact distribution.
Comment: Yes you need to calculate the distribution of the sample maximum, which, since the $X$'s are Uniform $(0,\theta)$, is easy. Start with the cdf. for the second question apply the change-of-variables formula to see what happens.
Comment: I know the change of variables formula but does that mean I set thetabar=n(theta-thetabar)?.
Comment: You define a new random variable, say $Z = n(\theta-\hat \theta)$ and find the distribution of $Z$ wich is a function of $\hat \theta$.
Comment: ...and you won't need the CLT for the asymptotic distribution. Think $e$, when the time comes.
Comment: e as in the exponential right?.
Comment: Yes. The base of natural logarithm.
Answer: The OP correctly found the MLE of $\theta$ to be the maximum order statistic. The $X$- r.v.'s here are $U(0,\theta)$. The distribution function and the density function of the maximum of an i.i.d. sample is here
$$F(\hat \theta) = [F_X(\theta)]^n = \left(\frac {\hat \theta}{\theta}\right)^n,\qquad f_{\hat \theta}(\hat \theta) = n\frac {\hat \theta ^{n-1}}{\theta^n}$$
Define the random variable $Z = n(\theta-\hat \theta)$ (note that $Z\ge 0$, since $\hat \theta$ never overestimates $\theta$). Then applying the change-of-variable formula we have
$$\hat \theta = \theta - \frac 1n Z, \qquad \left|\frac {d\hat \theta}{dZ}\right| =\frac 1n $$
So
$$f_Z(z) = \frac 1n n\frac {(\theta - \frac 1n z)^{n-1}}{\theta^n} = \frac 1{\theta}\left(1+\frac {(-z/\theta)}{n}\right)^{n-1}$$
Asymptotically we have
$$\lim_{n\rightarrow \infty}f_Z(z) = \lim_{n\rightarrow \infty}\frac 1{\theta}\left(1+\frac {(-z/\theta)}{n}\right)^{n-1} = \lim_{n\rightarrow \infty}\frac 1{\theta}\left(1+\frac {(-z/\theta)}{n}\right)^{n}\cdot \left(1+\frac {(-z/\theta)}{n}\right)^{-1}$$
The rightmost term goes to unity, and using the limit representation of the base of the natural logarithm, we arrive at
$$\lim_{n\rightarrow \infty}f_Z(z) = \frac 1{\theta}e^{-z/\theta}$$
which is an exponential distribution.


How start new activity with click on table rows and pass data to new activity in EditText

Question: Following is my code and I have already set OnClickListener with each table row,it is working. Now I want to start a new activity when user click on any row and also I want to pass the data of row to new activity in a textedit.
            Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+docno.getText()+"'", null);

                  int rows = c.getCount();
                  table_layout.removeAllViews();
                  c.moveToFirst();
                  for (int i = 0; i < rows; i++) {

                      String rollno  = c.getString(0);
                      String name    = c.getString(1);
                      String marks   = c.getString(2);
                   TableRow row = new TableRow(this);
                   row.setClickable(true);
                    row.setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            v.setBackgroundColor(Color.GRAY);
                        }
                    });

                   row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT));

                    TextView et = new TextView(this);
                    TextView name1 = new TextView(this);
                    TextView marks1 = new TextView(this);

                    name1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));

                    et.setGravity(Gravity.CENTER);
                    et.setTextSize(10);
                    et.setText(rollno);

                    name1.setGravity(Gravity.CENTER);
                    name1.setTextSize(10);
                    name1.setText(name);
                    name1.setBackgroundColor(0xFF00FF00);
                    name1.setHeight(20);
                    name1.setWidth(180);

                    marks1.setGravity(Gravity.CENTER);
                    marks1.setTextSize(10);
                    marks1.setText(marks);

                    row.addView(et);
                    row.addView(name1);
                    row.addView(marks1);

                   table_layout.addView(row);
                   c.moveToNext();

                  }

Answer: http://developer.android.com/training/basics/firstapp/starting-activity.html
Particularly the "Start the second activity" section seems to be precisely what you are looking for. Grab the relevant data from the selected row and then use intent.putExtra(key, value) to send it to the next activity.
Answer: There are a number of ways to do this, a few are described below.
You can use the putExtra method for your new intent.  You can either do this by passing the data as text or you can expose the Cursor and simply pass the row number.  To pass the data as text, in your onClick:
Intent intt = new Intent(this,NewActivity.class);
intt.putExtra("rollno",rollno);
intt.putExtra("name",name);
intt.putExtra("marks",marks);
startActivity(intt);

Then in your NewActivity
Bundle extras = getIntent().getExtras();
if(extras != null) {
    // Use extras.getString("rollno") in your setText method in your new activity
    // Use extras.getString("name") in your setText method in your new activity
    // Use extras.getString("marks") in your setText method in your new activity
}

You could also expose your Cursor by declaring it inside your class, but outside/before your onCreate method.
public static Cursor c;

Then in your onCreate remove the 'Cursor' keyword at the start.  You can then pass the data in as a row number in your onClick as such:
Intent intt = new Intent(this,NewActivity.class);
intt.putExtra("rownum",i);
startActivity(intt);

Then in your new activity:
Bundle extras = getIntent().getExtras();
int rownum;
if(extras != null) {
    c.moveToPosition(extras.getInt("rownum"));
    et.setText(MainActivity.c.getString(0));
    name1.setText(MainActivity.c.getString(1));
    marks1.setText(MainActivity.c.getString(2));
}

You could even simply skip passing the data through the intent, in the onClick:
c.moveToPosition(i);
Intent intt = new Intent(this,NewActivity.class);
startActivity(intt);

Then when you reference MainActivity.c (your cursor object) using getString() in your NewActivity, the correct row will have already been set for you.  However, this requires that you always call moveToPosition
Id also like to suggest a few other tips.  You should use a different naming convention for your layout objects.  Using variables such as name, name1, marks, marks1 will lead to confusion.  Instead use name, nameText or marksString, marksTextView.
Also for your db query, you should use query() method.  Instead of:
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+docno.getText()+"'", null);

Use:
c=db.query("student","rollno="+docno.getText.toString(),null,null,null,null,null);

This also assumes you have declared 'c' as a Cursor already as explained above.  You also cannot guarantee that your columns will be exactly where you expect them to be, so instead of using
c.getString(0)

to retrieve column 0, instead you should instead use:
c.getString(c.getColumnIndex("columnName");

Where 'columnName' is the name of the column in the table.
Comment: you advice me about two method to pass the data with putExtra ,data as text or expose the Cursor, which is the best method forever actually I am new in android.
Comment: This depends entirely on what your end goal is. Ideally your new activity shouldn't be handling the Cursor directly from your main activity. You also may want to start with empty values or a different Cursor, so pass your Strings in the bundle. When you get more complex records you may look at creating a Class for each record and referencing it by Class. (Imagine a C-style struct that implements its own private methods).
Comment: Dear Dvaey, I also want to disappear selected row, but if data successfully enter to database. can you please help me ?


Multiple forms on page

Question: I am trying to get multiple forms to work in a views display. All of the forms uses AJAX, but they appear to be interfering with each other.
One form is the Views Bulk Operations form that turns the views table into a 'viewsForm'. The second form is a 'quick edit' form available on each row in the view. The problem is when I submit any of the forms from the quick edit, it tries to also submit the 'viewsForm' form (which it shouldn't be doing), resulting in validation errors on that form. It's also not picking up my ajax callback for my custom form, as witnessed by the 'ajax callback is empty or not callable' in the dblog.
If I disable views bulk operations, this works as intended, but with multiple forms on the page, I can't figure out how to tell the 'submit' button I am using to only submit the form belonging to the submit button.
I have provided my formbuilder class for reference
<?php

namespace Drupal\request_system\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\HightlightCommand;

/**
 * Provides a Request System form.
 */
class QuickEditForm extends FormBase {

  public $sub_id = 0;
  public $entity_id = 0;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'request_system_quick_edit-' . $this->sub_id;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $entity = \Drupal::entityTypeManager()->getStorage('lms_request')->load($this->entity_id);

    $options = [];

    $options['_none'] = '- Select One -';

    if ($entity->bundle() == 'book_request') {
      $statuses = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties([
        'vid' => 'book_request_status',
      ]);
    }

    // Only show 'available from vendor' and 'Pending'
    foreach ($statuses as $status) {
      if ($status->getName() == 'Pending' || $status->getName() == 'Available From Vendor') {
        $options[$status->id()] = $status->getName();
      }

      if ($status->id() == $entity->field_request_status->getString()) {
        $options[$status->id()] = $status->getName();
      }
    }

    $form['quick_edit'] = [
      '#type' => 'container',
      '#id' => 'quick-edit-wrapper-'. $this->sub_id,
    ];

    $form['quick_edit']['status'] = [
      '#type' => 'fieldset',
      '#title' => 'Status Updates',
      '#name' => 'update-wrapper',
    ];

    if (!$entity->field_aph_shipment_number->isEmpty() || !$entity->field_library_shipment_number->isEmpty()) {
      $form['quick_edit']['status']['value'] = [
        '#type' => 'item',
        '#title' => 'Request Status: ',
        '#markup' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($entity->field_request_status->getString())->getName(),
      ];

      // Display message indicating item is part of a shipment
      $form['quick_edit']['status']['shipment_number'] = [
        '#markup' => 'This request is part of a shipment.',
      ];
    }
    else {
      // Disable this field if the request status is not 'Pending' or 'Available from Vendor', or if the item belongs to a shipment
      $form['quick_edit']['status']['value'] = [
        '#type' => 'select',
        '#title' => 'Status',
        '#options' => $options,
        '#default_value' => $entity->field_request_status->getString(),
      ];

      if ($entity->field_request_status->getString() != \Drupal\request_system\Controller\RequestSystemController::getStatus('Pending') && $entity->field_request_status->getString() != \Drupal\request_system\Controller\RequestSystemController::getStatus('Available From Vendor')) {
        $form['quick_edit']['status']['value']['#disabled'] = TRUE;
      }
    }

    $form['quick_edit']['status']['message'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Message'),
    ];

    $form['quick_edit']['status']['notify_user'] = [
      '#type' => 'checkbox',
      '#title' => 'Notify Borrower',
    ];

    // Allow editing of the APH catalog #

    $form['quick_edit']['other'] = [
      '#type' => 'fieldset',
      '#title' => 'Other',
      '#name' => 'other-wrapper',
    ];

    $form['quick_edit']['other']['aph_catalog_number'] = [
      '#type' => 'textfield',
      '#title' => 'APH Catalog #',
      '#default_value' => $entity->field_attached_copy_aph_number->getString(),
      '#description' => $entity->field_attached_copy_main_record->isEmpty() ? '' : 'Unable to change APH catalog number when a main record is assigned.',
      '#disabled' => $entity->field_attached_copy_main_record->isEmpty() ? FALSE : TRUE,
    ];

    $form['quick_edit']['id'] = [
      '#type' => 'hidden',
      '#value' => $this->entity_id,
    ];

    $form['quick_edit']['actions'] = [
      '#type' => 'actions',
    ];
    $form['quick_edit']['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#ajax' => [
        'callback' => '::quickEditAjax',
        'wrapper' => 'quick-edit-wrapper-'. $this->sub_id,
      ],
      '#validate' => '::validate',
      '#limit_validation_errors' => [['id'],['status']],
      '#submit' => ['::quickEditAjaxSubmit'],
    ];

    // $form['quick_edit']['actions']['cancel'] = [
    //   '#type' => 'submit',
    //   '#value' => 'Cancel',
    // ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    $entity = \Drupal::entityTypeManager()->getStorage('lms_request')->load($values['id']);

    if ($values['status'] == \Drupal\request_system\Controller\RequestSystemController::getStatus("Shipped From Loan Library")) {
      if (count($entity->field_imcid->referencedEntities()) == 0) {
        $form_state->setErrorByName('status','Cannot mark this item shipped since no library item is attached.');
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

  public function quickEditAjax(&$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    if ($form_state->hasAnyErrors()) {
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -1000,
      ];
      $form['#sorted'] = FALSE;
    }

    $response = new AjaxResponse();

    $status = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($values['status']);
    $response->addCommand(new ReplaceCommand('.request-status-'. $values['id'],$status->getName()));
    $response->addCommand(new ReplaceCommand('#quick-edit-wrapper-'. $this->sub_id,$form));
    $response->addCommand(new HightlightCommand('#row-'. $values['id']));

    return $response;
  }

  public function quickEditAjaxSubmit(&$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    // First load the entity
    $entity = \Drupal::entityTypeManager()->getStorage('lms_request')->load($values['id']);

    $entity->set('field_request_status',$values['status']);
    $entity->save();

    $form_state->setRebuild();
  }

}

And the way I am rendering the form is via
$form = \Drupal::classResolver()->getInstanceFromDefinition('Drupal\request_system\Form\QuickEditForm');
$form->sub_id = $entity->id();
$form->entity_id = $entity->id();
$build['form'] = \Drupal::formBuilder()->getForm($form);

It appears that when the view is rendered, it's combining all of the forms into a single , so when you click 'Save' on the sub-form, it's actually submitting the views bulk operations form. I am not sure how to resolve this or to get it to stop doing this.
I have been banging my head on this for two weeks trying to get this resolved, and can't figure out what the problem is.
Any help would be GREATLY appreciated.
EDIT: I have attached a screenshot of what we are trying to achieve. Checkbox on the left is views bulk operation, 'quick edit' form is on the far right via 'expandable table column'
Comment: Having a `` inside another `` is invalid HTML, it's up to the browser what happens in that situation. I think I'm right in saying all modern browsers will just ignore the inner ``s, and any nested inputs will implicitly be made part of the outer form (which would match your description of events). You might have to think about altering the VBO form instead of creating your own if you want to keep the VBO functionality (or alter the VBO functionality in such a way that it doesn't wrap the table with a ``)
Comment: VBO isn't wrapping the table in a form, views does it using the viewsForm method it exposes, so it would most likely require altering how Views works to do something like that. I am already using form_alter on the form to change some of the stuff that VBO does, but it does it at the view level, not individual row level which is what I need it to do.
Comment: Ok plan B is probably out of the window then, that would be a pain to re-implement. The row level must be available though, as VBO uses it - I'm guessing there's a field handler which uses the module's API to get a form context so it can render the checkbox per-row. Perhaps your approach could be the same. You'd need to make your functionality operate within the VBO form and possibly alter its validation/etc, but given the nature of the implementation and what HTML allows, I'm not sure what the alternative would be
Comment: By "VBO form" I mean "the form which VBO convinces Views to create via `ViewsBulkOperationsBulkForm::viewsForm`". I'm just looking at the code and I can see why you're stuck
Comment: Yeah, it doesn't look like what we are trying to achieve is possible. VBO uses viewsForm to create a form element of type #checkbox in the column location it's set to in the view, but that's not ideal as that is not what we want to do, as the column for the quickedit is in an entirely different column, and ideally would work independent of the views bulk operations functionality.
Comment: I updated my question to include a screenshot of what we are trying to achieve.
Comment: I'd be tempted to abandon the traditional form route altogether and use JS to submit the data to a route in your custom module which performs the save. Unless there's something obvious I'm missing, it looks to be technically possible, but probably not worth the effort to do it the normal way
Comment: I'm not sure what you mean by that. I haven't worked with submitting forms through Drupal using Javascript before. As I am mainly a backend developer, I don't have much experience with the front end happenings of Drupal.
Answer:
If I disable views bulk operations, this works as intended, but with
multiple forms on the page, I can't figure out how to tell the
'submit' button I am using to only submit the form belonging to the
submit button.

Without reviewing the entire code, if you have multiple Ajax forms on a page it should help to use unique submit form keys the same way you do this for the wrapper:
$form['quick_edit']['actions']['submit' . $this->sub_id] = [
  ...
  '#ajax' => [
    'callback' => '::quickEditAjax',
    'wrapper' => 'quick-edit-wrapper-'. $this->sub_id,
  ],

In the other case, you can't nest forms as discussed in the comments.
In general you need to place your form elements inside the existing form, which then can do their own thing using submit and ajax callbacks and ignoring the rest of the form. This can be done in a simple form alter hook or a more complicated system. For entity forms Drupal has subforms implemented in field widget plugins, for Views bulk forms field plugins implementing viewsForm($form, $form_state).
If you use one of those then go along with the way they do it.
Comment: I am using hook_form_alter right now to alter the VBO operations and workflow. I attempted to use that to add individual per row fields to the form, but it doesn't place them in the correct column/field location that it should, and doesn't render all of the form fields, either. I am currently using a custom views field plugin to render the forms in their correct table column, but the ajax submit handlers and buttons when clicked are actually triggering the vbo submit handler and validation.

Do you have a link to Drupals documentation for subforms? I can't find anything to demonstrate its us
Comment: Subforms? They are automatically built for field widgets. Which would be a completely different approach, not using a Views bulk form, but displaying entities in a grid where you could attach an entity form for each entity.
Comment: I am using VBO for different functionality. I am essentially trying to build two different forms on the page. One so you can perform quick actions on individual row items inline, and one so you can select multiple rows and perform different 'bulk actions' on them.

It doesn't appear like I can do what I want to do as long as views bulk operations is in place, which stinks. I will have to come up with another solution.
Comment: The form I am rendering right now on each row is a custom views field that uses the rendering code above to render a new form on each row. The field plugin is a 'fake' field that just renders output and a form to the row in the appropriate field column in the table. There doesn't appear to be a way to create a views field widget, or if there is I am missing it in the documentation.

Multiple forms on page


Moving a single Windows 2008 box to a clustered implementation?

Question: I have a system that currently runs on a single box, Windows 2008 Enterprise.  This is just used as a web server.
What is involved in creating a cluster?  Basically doing this for availability reasons - the load on the system will be pretty light.
Answer: There's a good article on IIS and Failover Clustering in 2008
Comment: That article works. We're using it for static web-serving, and it works great.


Yet another interchange of limit and sum (revised)

Question: A revised version of a similar question I asked before.
$S_n$ are finite sets containing rational numbers in [0,1] for which $S_n\subset S_{n+1}$ and $\lim_n S_n = \mathbb{Q}\cap [0,1]$.
$f_n:S_n\to\mathbb{R}$ are uniformly-bounded functions that converge to a continuous function $f$, that is $\lim_{n\to\infty} f_n(x)=f(x)$ for all $x\in S_n$.
Is it true that
$$
\lim_{n\to\infty} \frac{1}{|S_n|} \sum_{x\in S_n} f_n(x) = \int_0^1 f(x)\, \mbox{d}x
$$
Comment: Hint: What happens for $f_n = f$ for all $n$?
Comment: @guest, if $f_n=f\equiv1$, then the limit is infinite but the RHS is one. You should introduce some normalization to your limit of sums over growing finite sets to keep it finite.
Comment: @PhoemueX if $f_n=f$ what we get is a Riemann integral so it should be ok. So I may guess there must be a positive answer to my question?
Comment: @JoonasIlmavirta yes my goodness, of course I forgot the normalization. I made the edit,
Answer: If the points in $S_n$ are not chosen uniformly enough, it may well happen that your limit is the integral of $f$ against a nonconstant weight function. The claim is false even for $f_n=f$ if you don't make more assumptions. Consider for example the sets
$$
S_n=\{0,\frac1{4n},\frac2{4n},\dots,\frac{2n-1}{4n},\frac12,\frac{n+1}{2n},\frac{n+2}{2n},\dots,\frac{2n-1}{2n},1\}.
$$
The two thirds of the points are uniformly distributed on $[0,\frac12]$ and one third on $[\frac12,1]$. Thus the limit for a Riemann integrable $f$ is
$$
\lim_{n\to\infty} \frac{1}{|S_n|} \sum_{x\in S_n} f(x)
=
\frac23\int_0^{1/2} f(x)\, \mbox{d}x
+
\frac13\int_{1/2}^1 f(x)\, \mbox{d}x.
$$
Keep in mind that in the Riemann sums you also need the lengths of the intervals. If they are not uniform, an unweighted sum does not approximate the integral.
Comment: Thanks. So at least I could realize in advance that I need at least the same assumptions required by the Riemann integral... beyond those, I wonder whether the uniform boundedness and the pointwise convergence of the $f_n$'s are enough


Python retorna "Morto" ao tentar ler json > 240mb

Question: O problema ocorre em um server CentOS versão 6.8 final.
O mesmo script com outro arquivo menor funciona perfeitamente.
Teste efetuados em Ubuntu 16.04 o processo ocorre com sucesso.
Alguma solução? Segue abaixo o code.
código no gist
Comment: Valeu... funcionou... https://gist.github.com/vanessasoutoc/e82a76fc7d3e45dade9ca4315c0e4b40
Comment: Sua pergunta não está clara o suficiente. Esclareça seu problema específico ou acrescente outros detalhes para destacar exatamente o que precisa. Do modo como está escrito aqui, é difícil saber exatamente o que você está perguntando. Consulte a página [Como perguntar](https://pt.stackoverflow.com/help/how-to-ask) para obter ajuda no esclarecimento desta pergunta.
Comment: Outra dica é: cole diretamente seus códigos na sua pergunta. E de preferência, somente o trecho onde o erro aparece. Acredito que seja difícil alguém parar para ler e entender suas 250 linhas de código.
Comment: Pensando um pouco aqui, como seu json eh um pouco grande, talvez ao tentar lê-lo na memória, seu PC trave. Tente altera a linha onde você lê o json (`jsonToPython = json.load(data_file)`) para utilizar a biblioteca como a [ijson](https://pypi.python.org/pypi/ijson/) ou a [json-streamer](https://github.com/kashifrazzaqui/json-streamer)
Comment: Que bom que conseguiu! :) Se a resposta solucionou seu problema, você deve [aceitar a resposta](https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta) para marcar sua pergunta como "já respondida".
Answer: Como seu JSON eh um pouco grande, ao tentar lê-lo na memória, seu PC pode travar por falta de memória.
Sendo assim, tente alterar a linha onde você lê o JSON:
jsonToPython = json.load(data_file)

para utilizar uma biblioteca como a ijson ou a json-streamer, que são específicas para manipulação de arquivos com grande volume de dados.


Can't get JSON to deserialize into a list?

Question: I'm working on a bot that will pull from a list of trivia questions stored in JSON, but it seems to not be able to recognize the JSON as a list, even though I THINK I have it said up correctly.
Pertinent Code:
C#:
class Question
{
    public string Catagory { get; set; }
    public string QuestionText { get; set; }
    public string Answer { get; set; }
    public int Points { get; set; }
    public bool asked { get; set; }
}

class TriviaGame
{
    public List<Question> QuestionList = new List<Question>();

    public TriviaGame()
    {
        QuestionList = JsonConvert.DeserializeObject<List<Question>>(File.ReadAllText(@"filepath"));
    }

JSON:
{
    "Question" : [
    {
        "Catagory": "text",
        "QuestionText": "text",
        "Answer": "text",
        "Points": integer,
        "Asked": false
    },
    {
        "Catagory": "text",
        "QuestionText": "text",
        "Answer": "text",
        "Points": integer,
        "Asked": false
    },
    {
        "Catagory": "text",
        "QuestionText": "text",
        "Answer": "text",
        "Points": integer,
        "Asked": false
    }]
}

Replaced the text in the JSON file with placeholder text but the values aren't the problem it verifies fine.
Replaced the actual filepath with the word filepath for privacy reasons but the filepath works because it DOES pull up the file before throwing the error.
Error Given:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[TriviaBot.Question]' because the
type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To
fix this error either change the JSON to a JSON array (e.g. [1,2,3])
or change the deserialized type so that it is a normal .NET type (e.g.
not a primitive type like integer, not a collection type like an array
or List) that can be deserialized from a JSON object.
JsonObjectAttribute can also be added to the type to force it to
deserialize from a JSON object. Path 'Question', line 2, position 13.'
Comment: Does this answer your question? [Deserialize Json to List C#](https://stackoverflow.com/questions/37612787/deserialize-json-to-list-c-sharp)
Comment: In case you're interested, that's a DataSet, with a DataTable named `Question`. So, you can deserialize it as `JsonConvert.DeserializeObject(...)` If you replace those `integer` things with an actual value, that is.
Comment: Or DataTable directly: `var q = JsonConvert.DeserializeObject(JObject.Parse(json).SelectToken("Question").ToString());` or a List of Question objects, just replace DataTable with `List`.
Answer: The problem is in the JSON file; it describes a map and not an array.
Try deleting
{
"Question" :

at the start and deleting the } at the end.
Answer: The JSON structure you have has a property named Question that has an array of items, not an array of questions.
As Roy Cohen's answer states, you could modify your JSON file and remove the Question property.
Alternatively, if you can't modify that structure (for example if you get it from a service that you don't own), you can modify your class definition as follows:
class Items
{
    public List<Item> Question {get;set;}
}
class Item
{
    public string Catagory { get; set; }
    public string QuestionText { get; set; }
    public string Answer { get; set; }
    public int Points { get; set; }
    public bool asked { get; set; }
}

And then to load the object, use this code:
public List<Item> QuestionList = new List<Item>();

public TriviaGame()
{
    var deserialized = JsonConvert.DeserializeObject<Items>(File.ReadAllText(@"filepath"));
    QuestionList = deserialized.Question;
}


PIVOT and insert every N rows

Question: There are two tables:
First table has two columns with the following data:
[col1] [RowIndex]
apple  1
10     2
red    3
pear   4
20     5
yellow 6

Second empty table has 3 columns:
[FruitType] [Weight] [Color]

I wish to load the first table's [col1] data into the second one but "rotated" and without any aggregation.
Result would would look like this:
[FruitType] [Weight] [Color]
apple        10       red
pear         20       yellow

How can i insert data to the second table? I tried PIVOT but cannot wrap my head around.
Comment: How could you know which row match which colunm? is there any order in you first table?
Comment: First you are going to have to normalize that column... don't worry about pivot yet. Define how you associate red to apply and 1 to apple
Comment: You can't, unless there is a way to associate the different records.
Comment: @D-Shih I have edited the question. I have a rowindex (provided by application) in the first table. So the order is always strictly according to that column.
Answer: A conditional aggregation in concert with row_number() should do the trick
Example
Declare @YourTable Table ([RowIndex] int,[col1] varchar(50))
Insert Into @YourTable Values
 (1,'apple')
,(2,'1')
,(3,'red')
,(4,'pear')
,(5,'2')
,(6,'yellow')

Select [FruitType] = max(case when col=1 then Col1 end)
      ,[Weight]    = max(case when col=2 then Col1 end)
      ,[Color]     = max(case when col=0 then Col1 end)
 From (
        Select *
              ,Grp = (Row_Number() over (order by [RowIndex]) - 1) / 3
              ,Col =  Row_Number() over (order by [RowIndex]) % 3
         From @YourTable
      ) A
 Group By Grp

Returns
FruitType   Weight  Color
apple       1       red
pear        2       yellow

NOTE:
If RowIndex is truly sequential, you can remove the row_number() function and simply use RowIndex
Comment: @Avithohol Great!  Then you can replace Row_Number() over (order by [RowIndex]) with [RowIndex]
Comment: Thanks. Yes the RowIndex is truly sequential.
Answer: You can try to use ROW_NUMBER window function with some calculation
insert into SecondTable ( FruitType,Weight,Color)
SELECT FruitType,Weight,Color
FROM (
    SELECT MAX(CASE WHEN  rn % 3 = 1 THEN [col1] END) FruitType,
           MAX(CASE WHEN  rn % 3 = 2 THEN [col1] END) Weight,
           MAX(CASE WHEN  rn % 3 = 0 THEN [col1] END) Color
    FROM (
       SELECT *,ROW_NUMBER() OVER(ORDER BY RowIndex) rn
       FROM FirstTable
    ) tt
    GROUP BY (rn - 1) /3
)tt

sqlfiddle

PIVOT and insert every N rows


How to prevent java.util.logging.Logger to display messages on standard output?

Question: I am using java.util.logging.Logger
But with storing messages in a log file, it also writes messages to the standard output (console).
How can I disable the logger to display messages on standard output?
Comment: which configuration file? I am new to logging. I have instantiated a Logger object and have started writing msgs to a log file using the Logger's methods. I haven't configured any config file.
Comment: http://www.hildeberto.com/2009/04/using-java-logging-configuration-file.html see here
Answer: If you're new to logging you should read Java Logging Overview.
You should also post your configuration
This snippet shows how to write log messages into a file:
<code>public static void main(String[] args){
    Handler fh = new FileHandler("%t/wombat.log");
    Logger.getLogger("").addHandler(fh);
    Logger.getLogger("com.wombat").setLevel("com.wombat",Level.FINEST);
    ...
}
</code>


How do you set an environment variable in a subroutine when setlocal is enabled?

Question: I am trying to use setlocal/endlocal to use some environment variables internally in a script, but then I do want the script to ultimately save some environment variables as output (i.e., that do take effect in the calling environment).
I thought I could simply have a setlocal at the beginning, and then wrap any set commands I want to do outside the script with an endlocal before and setlocal after. But it seems to have different behavior if done inside a subroutine vs. outside.
This script should have %var1% == test1 in the calling environment, but not have %var2% == test2.
@echo off

:main
setlocal
call :set_var1
set var2=test2
exit /b

:set_var1
endlocal
set var1=test1
setlocal
exit /b

However, when I run this, I see:
D:\>set var1=

D:\>echo %var1%
%var1%

D:\>set var2=

D:\>echo %var2%
%var2%

D:\>test.bat

D:\>echo %var1%
%var1%

D:\>echo %var2%
%var2%

So the script failed to set %var1%.
If I "inline" the code (i.e. cut and paste the code inside the subroutine in the same spot as the subroutine call, and delete the subroutine call), so the script should do the same thing, then it works:
@echo off

:main
setlocal
endlocal
set var1=test1
setlocal
set var2=test2
exit /b

The output looks like:
D:\>set var1=

D:\>echo %var1%
%var1%

D:\>set var2=

D:\>echo %var2%
%var2%

D:\>test.bat

D:\>echo %var1%
test1

D:\>echo %var2%
%var2%

So now %var1% was correctly set to test1 by the script.
I'm wondering if the exit /b that returns from a subroutine has some effect on setlocal/endlocal. I don't see anything in the /? usage about this.
How do you selectively have a few environment variables created, or modified, in the batch script, take effect in the calling environment, but in general have most of the variables used for intermediate steps, discarded (i.e., treat them as local to the script)?
Comment: The standard trick is: start :set_var with `setlocal` and terminate it with `for %%v in (%var1%) do endlocal & set "var1=%%v"`, that is, in the subroutine _first_ close the environment with `endlocal` and _then_ assign the variable in the _calling_ environment. The value is held in the FOR parameter...  A simpler method is enclose between parentheses these lines: `endlocal` and `set "var1=%var1%"` that have the same result
Answer: I suggest following:
@echo off
setlocal EnableExtensions DisableDelayedExpansion

:main
call :set_var1
set "var2=test2"
rem Other commands which define other environment variables like:
set "var3=test3"
endlocal & set "var1=%var1%" & set "var3=%var3%"
exit /B

:set_var1
set "var1=test1"
goto :EOF

There is defined once completely the required execution environment at top of the batch file with the first two command lines. Read this answer for details about the commands SETLOCAL and ENDLOCAL.
The command line with endlocal is parsed by the Windows Command Processor cmd.exe as described by How does the Windows Command Interpreter (CMD.EXE) parse scripts? The environment variable references %var1% and %var3% are replaced by the current values of these two environment variables in local environment of the batch file.
The finally executed endlocal command line does not contain anymore environment variable references. The command line on execution is:
endlocal   & set "var1=test1"   & set "var3=test3"

The additional spaces are inserted by cmd.exe on parsing the command line.
There is first restored the initial environment on starting the processing of this batch file and then is defined the environment variable var1 with the string test1 and next var3 with the string test3 in that environment.
See also:

Why is no string output with 'echo %var%' after using 'set var = text' on command line?
Single line with multiple commands using Windows batch file
Where does GOTO :EOF return to?

There is used goto :EOF to exit the subroutine set_var1 and exit /B to exit the processing of the batch file. The reasons are:

The usage of exit /B for exiting batch file processing and goto :EOF for exiting processing of a subroutine makes it easier to see which processing is exited – a subroutine or the batch file processing. It makes it easier finding the exit points of the batch file.
The command goto :EOF does not work with disabled command extensions. The second line of the batch file explicitly enables the command extensions. goto :EOF works for that reason always for the subroutine. But it could not work for exiting the batch file processing after the command line with endlocal on command extensions are disabled for whatever reason in initial environment on starting the processing of the batch file.
The command exit /B always works even with disabled command extensions. It would be even better to use exit /B 2>nul to suppress the error message output because of missing label EOF on running exit /B in initial execution environment with disabled command extension. However, command extensions are enabled by default on nowadays used Windows versions. There is really no reason to disable them ever, except a batch file is written on Windows XP and newer Windows versions for usage on MS-DOS, Windows 3.1, Windows 3.11, Windows 95/98/ME with COMMAND.COM as command interpreter instead of the Windows Command Processor cmd.exe.
Comment: Maybe this doesn't matter, but with `exit /B <code>` to return from a subroutine instead of `goto :EOF`, the caller will have access to an exit code, for use in `if errorlevel` or checking `%errorlevel%`. You would also be able to set environment variable(s) though, which the caller could access, which could be non-integer values. That would be somewhat analogous to a function setting global variables before it returns in other programming languages.
Comment: @RichJahn That is right. But I write batch files since more than 30 years and wrote thousands of batch files on which I have never needed to exit a subroutine with an exit code at all. Yes, `exit /B <code>` can be used to return an exit code from a subroutine to calling code and `if errorlevel` or `if not errorlevel` can be used in the calling code to evaluate the exit code of the subroutine, but I have never needed that in my batch files. There can be used an environment variable to return something from subroutine to calling routine which is much more often used as not limited to a number.


useEffect is causing error because of variables?

Question: I just finished a project in react. But the only error that I couldn't solve was the function below:
useEffect(() => {
        if (guessedLetters.length
            === uniqueLetters.length){

            startGame({
                score: score + points
            })
        }
    }, [guessedLetters.length])

Error: React Hook useEffect has missing dependencies: 'points', 'score', 'startGame', and 'uniqueLetters.length'. Either include them or remove the dependency array  react-hooks/exhaustive-deps
What would be the best way to solve this problem?
Comment: [guessedLetters.length, points, score, startGame]  you can include it
Answer: Two ways to resolve this issue. But there maybe side-effects due to this. Side-effects include unnecessary re-rendering or no rendering at all.
First: Make the dependency array empty.
useEffect(() => {
        if (guessedLetters.length
            === uniqueLetters.length){

            startGame({
                score: score + points
            })
        }
    }, [])

Second: Include all the variables that you have used inside the use Effect.
useEffect(() => {
        if (guessedLetters.length
            === uniqueLetters.length){

            startGame({
                score: score + points
            })
        }
    }, [guessedLetters.length, uniqueLetters.length, points, score, startGame])

Alternatively, you can also use useCallback hook.
Comment: Your answer was very complete. Thanks.
Answer: useEffect(() => {
        if (guessedLetters.length
            === uniqueLetters.length){

            startGame({
                score: score + points
            })
        }
    }, [guessedLetters.length, points, score, startGame, uniqueLetters.length])

will get rid of the warnings, but you probably have a problem in the way your app mechanics are built if you're depending on so much stuff for the useEffect, the simple fact of adding the deps will probably introduce new bugs


Cannot use extra_option with path django

Question: I don't understand why I cannot use the path() method as documented here: https://docs.djangoproject.com/en/2.0/topics/http/urls/#passing-extra-options-to-view-functions in my apps urls.py.
Here is the code I have:
from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path
from . import views as AliasViews
from permissions import views as PermissionsViews

    urlpatterns = [
    ...
        path(r'^user/(?P<alias_id>\d{1,})/members/?$',
             AliasViews.UserAliasMember.as_view(),
             name='useralias_member', {'alias_type':'UserAlias'}),
    ...
    ]

I get this error: SyntaxError: non-keyword arg after keyword arg.
Answer: This has nothing to do with the path function. As the error says, Python syntax does not allow keyword arguments - eg name='useralias_member' - before non-keyword arguments. Your extra dictionary should be before that name argument.
Note however that you're also confusing path with url. The new path function doesn't use regexes, it uses the special <arg:type> format. If you want to use regexes, switch back to url.
Comment: Thanks so my path call should look like this:         "path('/user//members/', AliasViews.UserAliasMember.as_view(), {'alias_type':'UserAlias'})" right?
Comment: hmmm I made the suggested code change now I get an error message: "ImportError: cannot import name path"
Comment: Are you actually using Django 2.0?
Comment: Thanks Daniel ... looks like I am running django 1.11.


windows - how to make some file impossible to remove/rename for all users via commandline

Question: how to (using command-line/batch file only) make some file impossible to delete/rename for all users. I tried attrib +R on file itself and on directory where it exist but it doesn't help
Comment: You can't deny users with administrative rights from taking back access to the file. There are limitations to what you are trying to do. Also, without knowing exactly which user accounts have what permissions, it will be difficult to make this batch file.
Answer: CACLS will do the trick. When you say all users however, the system user will still have privileges in most cases.
https://superuser.com/questions/222256/change-windows-7-file-permissions-from-command-prompt
Comment: Not exactly. Calc is depreciated so Im using icalc. It's doing its job but it doesnt matter since user can add permissions to him again
Comment: Once the user has no view rights, they will not be able to see the file. That should make it difficult to change permissions. :)
Answer: Here is a solution you can try.
You pass the full path and file to the batch file within quotes for security.
TAKEOWN /A "%~1"
ICACLS "%~1" /grant:r SYSTEM:(F) Administrators:(F) users:(R)

The /grant:r will reset the permissions of the file to what is specified.
Again, if any user is a member of the administrator group then can reset the permissions to any file or folder.


callback method for soft keyboard changes?

Question: Is there any callback methods for soft keyboard up and down. I want to do some action when soft keyboard is up and down. I know to check whether the keyboard is up or down. But that i should call that method from somewhere. Here I don't want to call it. It should be triggered automatically when there is change in soft keyboard state.
Answer: Try this code it is worked in my project
R.id.activityRoot is  ParentLayout ID
final View activityRootView = findViewById(R.id.activityRoot);
            activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
                    new OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {

                            try {
                                int heightDiff = activityRootView.getRootView()
                                        .getHeight() - activityRootView.getHeight();
                                if (heightDiff > 100) { // if more than 100 pixels,
                                                        // its probably a
                                                        // keyboard...
                                //do your stuff here keyboard shown
                                }else {     //do your stuff here keyboard not visible }

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

                    });

Comment: this is for checking whether the keyboard is up or down rt?not a callback method na?
Comment: After adding this code when i tap on the textviews or buttons in the layout.keyboard disappears :( how to prevent it?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/67000/discussion-between-seethalakshmi-and-jenuine).


Como usar regex começando no meio da string?

Question: Eu tenho uma string bastante grande e gostaria de verificar se um trecho dela casa com uma regex. O problema é que esse trecho está no meio da string, em uma posição bem específica. Como terei de fazer isso várias vezes (strings diferentes, regexes diferentes e posições diferentes) gostaria que essa verificação fosse feita de forma eficiente, sem ter que:

Fazer uma substring, o que criaria novas strings desnecessariamente:
var sub = str.substring(pos); // Cria um novo objeto, potencialmente bem grande
regex.exec(sub);

ou:
Fazer a busca globalmente, o que não só percorre partes da string que não me interessam (i.e. aquelas antes da posição desejada) como também pode não me dar o resultado que eu quero em absoluto (ex.: se há interseção entre um casamento anterior e a parte da string que me interessa):
var resultado = regex.exec(str); // Assumindo que regex possui a flag g
while ( resultado && resultado.index < pos )
    resultado = regex.exec(str);
if ( resultado.index == pos )
    ...

É possível fazer isso? Os métodos usuais de casamento (String.match, RegExp.test e RegExp.exec) não possuem parâmetros para especificar a posição da string de onde iniciar a execução, e mesmo o String.search não possui essa opção. Há alguma outra maneira?
Comment: Relacionado (acho que não chega a ser dup): https://pt.stackoverflow.com/q/442142/112052
Answer: Isso pode ser feito através da flag sticky e da propriedade lastIndex (a mesma usada pela flag global). Basta criar a regex com essa flag e em seguida atribuir a posição que se deseja buscar:

var re = /\w+/y;
var str = "....abc....def...";

re.lastIndex = 4;
console.log(re.exec(str)); // ["abc"]

re.lastIndex = 11;
console.log(re.exec(str)); // ["def"]

re.lastIndex = 2;
console.log(re.exec(str)); // null

re.lastIndex = 5; // Funciona em qualquer índice
console.log(re.exec(str)); // ["bc"]

(Nota: essa flag somente foi padronizada recentemente pelo ES2015, de modo que só é suportada pelos browsers em suas versões mais recentes, e o suporte nas plataformas móveis ainda é limitado)
Essa flag é necessária porque: a) se a regex não for global, o valor da propriedade lastIndex é ignorado; b) se a regex for global, ele busca a partir do lastIndex, em vez de começar o casamento exatamente no lastIndex (e não adianta usar ^ no início da regex, pois como não se está no início da string, a execução falhará):

var str = "....abc....def....";

var re1 = /\w+/;
re1.lastIndex = 11; // Deveria pegar a segunda palavra
console.log(re1.exec(str)); // ["abc"]

var re2 = /\w+/g;
re2.lastIndex = 2; // Deveria falhar
console.log(re2.exec(str)); // ["abc"]

var re3 = /^\w+/g;
re3.lastIndex = 11; // Deveria pegar a segunda palavra
console.log(re3.exec(str)); // null
Comment: Vale ressaltar que a flag `/y` [não é suportado por todos os navegadores](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Compatibilidade_de_navegador)
Comment: @Mariano De fato. Essa flag já é usada no Firefox há anos, mas só foi padronizada pelo ES6. Atualmente [todos os browsers modernos para desktop dão suporte](https://kangax.github.io/compat-table/es6/#test-RegExp_y_and_u_flags) - incluindo o Edge, mas excluindo o IE em todas as suas versões. Nas plataformas móveis, só o iOS 10 por enquanto... Vou atualizar a resposta com essa informação.


rsync less verbose logs

Question: How do I get rsync to only log the files it backs up?
I don't want these lines filling up my log file which it does every time runs even if it has nothing to send.:
2016/11/13 14:30:01 [1554] building file list
2016/11/13 14:30:04 [1554] sent 3255320 bytes  received 6707 bytes  total size 697719781381

It's running from a cron, not in daemon mode. My command is:
rsync -rtbpgo --suffix="."$(date +"%Y%m%d%H%M") --exclude=".*" --exclude="~*" --exclude="[Tt][Hh][Uu][Mm][Bb][Ss].[Dd][Bb]" --exclude="[Dd][Ee][Ss][Kk][Tt][Oo][Pp].[Ii][Nn][Ii]" --log-file=/mnt/rsync.log --info=FLIST /mnt/datastore/ /mnt/dsbackup
Answer: Add hese two flags, they should do the trick  -q -i   (quiet and items)

rsync less verbose logs


Can the volleyball be set over the net on the first touch?

Question: When my opponent first serves a ball, can I set and pass the ball over the net?
My friend told me that this is a fault - but the ball was coming towards my face, so I don't see what else could I do.
Answer: It is not a fault to set the ball back over the net on the first contact. Two exceptions to this:

If you are playing beach volleyball as opposed to indoor volleyball, you cannot set the first contact at all - it doesn't matter if it goes over the net or not.
You may not play the serve directly back over the net if the ball is entirely higher than the top of the net and in the front zone (Rule 13.2.4). Basically this is "you can't block the serve", but it equally applies to setting the ball back if the ball is higher than the top of the net; perhaps it is this rule which is confusing your friend.

However, none of this means it's a good idea to play the ball directly back - you should always be trying to pass the ball to your own side one way or another.
Comment: In addition, in Germany, there's a rule for underage players (under fourteen years) called "Pflichtzuspiel". It forbids to play the ball over the net on the first touch.
Comment: Can you provide the beach volleyball rule number for the first claim? Thank you (:
Comment: you can set overhead **ANY** ball in the beach volleyball **if you can do it as perfectly** as a very good set on a second touch of the team, and there are two errors you need to avoid: 1) commit lift/grab errors 2) touch the ball twice (when it comes TO your hands, and when goes FROM your hands). In real life it is almost impossible to handle the serve as good as a good set — maybe, if you have titanium fingers with hydraulic drive. So, I'm pretty sure: you can't provide a link to the rules/recommendations for the first item, because there is no such rule/recommendation.
Comment: but. the thing is we compare ourselves to professionals (who have morning and evening sessions - because it is their lives). Most of us aren't professionals (read other questions, and you'll agree). Even on a good day, even under a lucky star I can easily commit a double on the team's second touch. So, for amateurs who didn't dedicate years to master an over-head setting - it is better to avoid these tricks on the first touch of the team
Answer: In beach volleyball like with indoor, setting the first ball of a rally (not serve) has traditionally been allowed including over the net.  It's possible the rules have changed, and it's fair to note the AVP (from the USA) and the FIVB may have (had) different rules.
One commenter notes the FIVB has a rule 18.104.22.168 from the 2017-2020 edition, stating "the first hit of the team... may NOT contact the fingers/hands". While this sounds conclusive, this is an ambiguous statement, because the first hit of the two teams are: 1. the serve, and 2. the first play of serve receive.  Setting a non driven first ball of a rally (not serve) has been legal for decades and if it's changed, it needs to be clarified clearly in the rules.  But FIVB rules reflect the game, they were not intended to change it.
Have a look at this clip where in a major FIVB tournament match, the first ball of a -rally- is a set at 10 seconds and it's not called, nor do either of these first class teams, the ref, or the announcer complain.  In fact, the player who set's this rally ball was complaining about a possible lift on the other team just before he sets the first ball of a rally.

This proves the rule probably still does not apply first touch in a rally, or if it does now it's a new rule, or at the highest levels they still don't call it.  It's seen as legal by the experts.  Look at the comments on youtube, many people say exactly what I'm saying here. Traditionally, and maybe still today, it was always about the quality of the set in the context of the ball coming over the net not being a hard driven ball.  There's also a reddit on "Beach Volleyball Rules: A Refresher" which states the same thing I'm saying here: "Setting first ball is allowed."
In the case of hard driven balls (which can be dug over net) rule 18.104.22.168 mentions one may contact the ball with "overhand fingers" (in a setting like motion) but this is not in fact a set.
The next part of the question is, if one sets a ball over the net, the ball must travel perpendicular to the shoulders of the person setting the ball.  That is rule 13.2.5.  This means, the set must go directly in front of or behind the setter.
If 220.127.116.11 does apply to rally play, it may be a relatively new rule and is not universally enforced even by refs at the highest level.  The play in the clip above where the first ball is set has been legal and performed thousands of times since the 1980s in the USA (AVP) and more recently in FIVB international play.
Comment: 1) The rule is not ambiguous, it very clearly states "At the first hit of the team". 2) The rule in 22.214.171.124 is about playing the ball "overhand with the fingers", the play there is with the palms, not the fingers; that has always been an acceptable defensive play.
Comment: Hi Philip, at 10 seconds Marci sets the first touch during the rally. I do hope you're kidding saying that touch was not a set, or that it was done with the palms. The first ball of a rally can be touched with separated palms only if the ball was hard driven, that was clearly a set. Rule 184.108.40.206 has grammatical errors in addition to not specifying if the regulation applies to rally play, but this has been legal for decades. I agree however it sounds like it could mean what you say.  There's a reddit on "Beach Volleyball Rules: A Refresher" which states the same thing I'm saying.


Standalone Spark application in IntelliJ

Question: I am trying to run a spark application (written in Scala) on a local server for debug. It seems that YARN is the default in the version of spark (2.2.1) that I have in the sbt build definitions, and according to an error I'm consistently getting, there is no spark/YARN server listening:
Client:920 - Failed to connect to server: 0.0.0.0/0.0.0.0:8032: retries get failed due to exceeded maximum allowed retries number

According to netstat indeed there is really no port 8032 on my local server, in listening state.
How would I typically accomplish running my spark application locally, in a way bypassing this problem? I only need the application to process a small amount of data for debug, and hence would like to be able to run locally, without reliance on specific SPARK/YARN installations and setups on the local server ― that would be an ideal debug setup.
Is that possible?
My sbt definitions already bring in all the necessary spark and spark.yarn jars. The problem also reproduces when running the same project in sbt, outside of IntelliJ.
Comment: What is it that you are trying to debug exactly, is it just the spark pipeline or distributed way of application run?
Comment: Just the pipeline. Not any spark internals or any issue related to a distributed run.
Comment: [A Related Q&A helpful for debug mode](https://stackoverflow.com/questions/57310833/lost-executor-driver-on-localhost-executor-heartbeat-timed-out)
Answer: You can add this property to VM options in your debug configurations instead of hardcoding inside the code
-Dspark.master=local[2]

Answer: You could submit spark application in local mode with .master("local[*]") if you have to test pipeline with miniscule data.
Full code:
val spark = SparkSession
  .builder
  .appName("myapp")
  .master("local[*]")
  .getOrCreate()

For spark-submit use --master local[*] as one of the arguments. Refer this: https://spark.apache.org/docs/latest/submitting-applications.html
Note: Do not hard code master in your codebase, always try to supply these variables from commandline. This makes application reusable for local/test/mesos/kubernetes/yarn/whatever.
Comment: How are you trying to submit the application? I have added programmatic way of adding it
Comment: I'm running the application as you show in the code (just found that API the moment you posted it), rather than submitting it from the outside. It simply works. Thanks and we can probably remove our comments because the answer seems to me _as full_ without them!
Comment: A related helpful resource: https://pawanmishra.github.io/spark-stand-alone-mode/


Why is this almost affine code not equivalent to a linear code?

Question: I am a bachelor student who just started studying coding theory and I came across the following example in "Generalized Hamming weights for almost affine codes" by Johnsen and Verdure, page 4 (https://arxiv.org/abs/1601.01504):

We will use a running example throughout this paper. It is the almost affine code C
′
in [14, Example 5]. It is a code of length 3 and dimension 2 on the alphabet F = {0, 1, 2, 3}. Its set
of codewords is

$$
\begin{matrix}
000 & 011 & 022 & 033 \\
101 & 112 & 123 & 130 \\
202 & 213 & 220 & 231 \\
303 & 310 & 321 & 332 \\
\end{matrix}
$$

[...] This is an example of an almost affine code which is not
equivalent to a linear code, and not even to a multilinear code.

I understand why the code is almost affine. However, to me, it seems like this is a linear code, since all the codewords can be expressed as linear combinations of 101 and 011. What mistake am I making? Also, how would I check that it is not equivalent to a multilinear code? Thank you in advance.
Comment: When people say a $C$ linear code, they mean that $C$ is linear subspace of a vector space over a finite field. It is true that $C'$ is a sub-__group__ of the group $(\mathbb Z/4\mathbb Z)^3$, generated by the two group elements $(1,0,1)$ and $(0,1,1)$, but since it is not a sub-**space** of a vector space, we cannot call $C'$ linear. Note that $\mathbb Z/\mathbb 4Z$ is not a field.
Comment: @MikeEarnest Thank you for your help. I think I understand it now.
Comment: @MikeEarnest: That looks like an answer to me – see https://math.meta.stackexchange.com/questions/35479.
Answer: When people say a $C$ linear code, they mean that $C$ is linear subspace of a vector space. It is true that $C'$ is a sub-group of the group $(\mathbb Z/4\mathbb Z)^3$, generated by the two group elements $(1,0,1)$ and $(0,1,1)$, but since it is not a sub-space of a vector space, we cannot call $C'$ linear. Note that $\mathbb Z/4\mathbb Z$ is not a field.
I do not know about how to prove it is not equivalent to a (multi)linear code, perhaps someone else can answer about that.
Comment: Does this imply that it is in general not possible to construct a linear code on the alphabet {0, 1, 2, 3}?
Comment: @AsocialButterfly It is possible, just not using usual addition/multiplication $\pmod 4$. You just need to define $+$ and $\times$ operations on $\{0,1,2,3\}$ which turns it into a field, and then use a vector space and subspace over that field. Just choose an arbitrary bijection of $\{0,1,2,3\}$ with $\mathbb F_4$. The latter can be defined as $(\mathbb Z/ 2\mathbb Z)[x]$, where $x$ satisfies $x^2=x+1$.
Comment: Linear codes over rings are most certainly a thing, and in that context often *linear (over $R$)* = *a submodule of the free module $R^n$*. I guess the authors here want to discuss some aspects, where it makes a difference whether we have a (commutative) ring as opposed to a field.


Como converter este código de derivação em PHP para JavaScript

Question: Estou com uma linda função de derivação escrita em PHP mas gostaria de passa-la para JavaScript e como ela tem muita "soma" eu não sei como transforma-la, alguém pode ajudar-me?
function derivate($key, $iv, $x) {
    $sha1_a = SHA1($iv + substr($key, $x, 32));
    $sha1_b = SHA1(substr($key, 32 + $x, 16) + $iv + substr($key, 48 + $x, 16));
    $sha1_c = SHA1(substr($key, 64 + $x, 32) + $iv);
    $sha1_d = SHA1($iv + substr($key, 96 + $x, 32));

    $A = substr($sha1_a, 0, 8) + substr($sha1_b, 8, 12) + substr($sha1_c, 4, 12);
    $B  = substr($sha1_a, 8, 12) + substr($sha1_b, 0, 8) + substr($sha1_c, 16, 4) + substr($sha1_d, 0, 8);

    return array(
        'A' => SHA1($A),
        'B' => SHA1($B)
    );
}

a função SHA1 eu tenho funcionando normal
Comment: Editei o titulo para não soar como apenas um pedido, mas sim como algo útil para a comunidade.
Comment: Tem certeza que a pergunta não é: "como converter esse código para JS"? Pq basicamente se vc escrever essa função antes do teu código: `var substr = function(str, pos, len) { return str.substr(pos, len); };` teu código vai funcionar dentro da condição de vc ter uma lib pra *SHA1*
Comment: @GabrielGartz sim, era este o titulo mas foi remanejado por MODS
Comment: @Elaine opinião pessoal, acho o seu título melhor do que o alterado, colocou o código que eu escrevi, funcionou?
Answer: Para converter este código de PHP para JavaScript não é preciso muito se você já tem a lib para SHA1, basta alterar a sintaxe e adicionar a seguinte função ao seu código:
function substr(str, pos, len) {
    return str.substr(pos, len);
};

No JavaScript o substr é um método do protótipo do objeto String, isso significa que ao invés de adicionar como primeiro parâmetro a string, você deve chamar diretamente da string. E este código é um "calço" para ficar parecido com o PHP.
E o Array você deverá utilizar um objeto literal no JavaScript, pois apesar de que Arrays permitem utilização de qualquer chave não numérica, não é a forma correta de utiliza-las.
return {
    'A': SHA1($A),
    'B': SHA1($B)
}

Você pode manter as variáveis com o caractere $ assim como no PHP, porém no JavaScript ela não é necessária, mas como é um caracter unicode, e qualquer unicode pode ser usado para definir variável, este vai permitir. Mas não esqueça de adicionar o var antes das mesmas.
As operações aritméticas utilizam os mesmos caracteres em ambas linguagens.
O código final ficará:
function substr(str, pos, len) {
    return str.substr(pos, len);
};
function derivate($key, $iv, $x) {
    var $sha1_a = SHA1($iv + substr($key, $x, 32));
    var $sha1_b = SHA1(substr($key, 32 + $x, 16) + $iv + substr($key, 48 + $x, 16));
    var $sha1_c = SHA1(substr($key, 64 + $x, 32) + $iv);
    var $sha1_d = SHA1($iv + substr($key, 96 + $x, 32));

    var $A = substr($sha1_a, 0, 8) + substr($sha1_b, 8, 12) + substr($sha1_c, 4, 12);
    var $B  = substr($sha1_a, 8, 12) + substr($sha1_b, 0, 8) + substr($sha1_c, 16, 4) + substr($sha1_d, 0, 8);

    return {
        'A': SHA1($A),
        'B': SHA1($B)
    };
}

Se você estiver mais confortável com a notação orientada objeto de JavaScript pode remover o "calço" e escrever o código desta maneira:
function derivate($key, $iv, $x) {
    var $sha1_a = SHA1($iv + $key.substr($x, 32));
    var $sha1_b = SHA1($key.substr(32 + $x, 16) + $iv + $key.substr(48 + $x, 16));
    var $sha1_c = SHA1($key.substr(64 + $x, 32) + $iv);
    var $sha1_d = SHA1($iv + $key.substr(96 + $x, 32));

    var $A = $sha1_a.substr(0, 8) + $sha1_b.substr(8, 12) + $sha1_c.substr(4, 12);
    var $B  = $sha1_a.substr(8, 12) + $sha1_b.substr(0, 8) + $sha1_c.substr(16, 4) + $sha1_d.substr(0, 8);

    return {
        'A': SHA1($A),
        'B': SHA1($B)
    };
}

Um próximo passo seria remover o caractere $ das variáveis, como mencionei anteriormente, funcionará com, mas não são necessários, pois efetivamente nada adicionam além de estética.


How can I checkout project from cvs using gradle?

Question: I have created gradle script to build my project but I want project to be downloaded from cvs repository. Is there any cvs plugin of gradle ?
Answer: See this one: https://stackoverflow.com/a/15392070/1441857
As stated you'd usually not do that in the build script but in the CI. The answer is that there's probably not one for gradle. However should you actually need it for various reasons, it should be possible to create something like a shell script and execute it from gradle.
Comment: yes.. what I need to do is if I provide cvs repository details it should checkout project and then build using gradle.
Comment: If I understand correctly, you are trying to do dependency management? When searching the net I can't find anything immediately, so I still suspect that the answer is no, gradle can't immediately. As @Edvin-Syse says you could publish via some other tool, or build a local repository. Otherwise you can still call other commands from gradle and checkout projects via that. Perhaps you could call some other dependency system such as IVY to handle that?
Comment: Thank you for your reply. Will use jenkins. In that will checkout using ant and build using gradle scripts.
Answer: VCS is completely separate from your build system, simply use a CVS client to checkout your project.
If you want to distribute the project binaries you can publish to JCenter, Maven Central etc.


Drupal 8 route not found

Question: I keep having a 404 error no matter what I change on my routing file.
I've created a module in modules\custom which have :

An info file in modules\custom\first_module\first_module.info.yml:

name: First module
core: 8.x
type: module
package: Training modules
description: First Module created to learn coding in D8

A Routing file in  modules\custom\first_module\first_module.routing.yml:

first_module_hello_world:
  path: '/hello-world'
  defaults:
    _controller: '\Drupal\first_module\src\Controller\TrainingModule:helloWorld'
  requirements:
    _permission: 'access content'

A controller in modules\custom\first_module\first_module.routing.yml:

<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloWorldController.
 */

namespace Drupal\first_module\src\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for hello_world module routes.
 */
class TrainingModuleController extends ControllerBase {

 /**
  * Return the 'Hello World' page.
  *
  * @return string
  *   A render array containing our 'Hello World' page content.
  */
 public function helloWorld() {
  $output = array();

  $output['hello_world'] = array(
    '#markup' => $this->t('Hello World!'),
  );
  return $output;
 }
}

Any help would be greatly appreciated !
Edit: The Module is activated and I cleared the cache several times.
Answer: In first_module.routing.yml, controller there is no src and you use 2:  ::
first_module_hello_world:
    path: '/hello-world'
    defaults:
        _controller: '\Drupal\first_module\Controller\TrainingModule::helloWorld'
        _title: 'hello world'
    requirements:
        _permission: 'access content'

Also without src in drupal 8 there si no need to use  return $output;
Alsi class is not good. Class is TrainingModule not TrainingModuleControlle and file need to cole the some TrainingModule
namespace Drupal\first_module\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for hello_world module routes.
 */
class TrainingModule extends ControllerBase {

 /**
  * Return the 'Hello World' page.
  *
  * @return string
  *   A render array containing our 'Hello World' page content.
  */
 public function helloWorld() {

  return array(
    '#type' => 'markup',
        '#markup' => $this->t('Hello World!'),
  );
 }
}

change first_module_hello_world: to first_module_hello_world.help:
make the file first_module_hello_world.module and write this code
function first_module_hello_world_help($route_name, $route_match) {
 switch ($route_name) {
  case 'first_module_hello_world.help':
    $output = '';
    return $output;
 }
}

Comment: I'm glad that I helped..
Comment: Still Page not found. I guess the first thing to check is the routing file. There must be a problem there but I can't figure out which one ! otherwhise there would have been another kind of error report.
Comment: A controller in  need to be in modules\custom\first_module\src\Controller\TrainingModule.php did you chance also this class TrainingModule extends ControllerBase
Comment: Yes I copied your code in each file.
Comment: Worked with the class after rebuilding the cache ! thanks @s-a-k-a !
Comment: Si helpful but with lots of mispellings :)

Drupal 8 route not found


Why am I still able to get a response on port 80 when I've shut down all ports except 22?

Question: My goal is to shut down absolutely all ports on my Ubuntu server, except port 22 (SSH).
I followed the instructions from this question here on Server Fault, plus instructions here and here.
However, after going through the instructions, it seems like my ports are still open. Here's port 80, for example:
$ nmap -p 80 ###.###.###.###

Starting Nmap 5.21 ( http://nmap.org ) at 2012-05-09 15:36 JST
Nmap scan report for ###-###-###-###.name.name.com (###.###.###.###)
Host is up (0.0065s latency).
PORT   STATE SERVICE
80/tcp open  http

Nmap done: 1 IP address (1 host up) scanned in 1.63 seconds

Here is the contents of my iptables:
# sudo iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
DROP       all  --  anywhere             anywhere

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Just looking at it, especialy where it says "Accept all anywhere", it seems like I have the opposite of what I want. It looks like instead of closing down ports, I've opened them up. However, these are the results of following the instructions to the letter, so maybe I just don't understand what the terms really mean.
In any case, bottom line, what do I do to shut down all ports except 22, and then make it stick even if the server gets rebooted. Surely it's just a few commands at the command line?
(Please note I'm a web designer who got this task, so I'm not at all a super confident server admin. Please make answers easy to understand. Thanks!)
Answer: As you expected the line:
ACCEPT     all  --  anywhere             anywhere

means all protocols/ports are allowed since it comes before this line:
DROP       all  --  anywhere             anywhere

You are not denying any port since there is only one DROP rule that comes after an ACCEPT rule which is allowing everything.
iptables rules are matched in order, so you need to have the following rules if you want to allow only port 22 to be allowed on INPUT chain:
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

The above two rules should be enough with default INPUT policy set to DROP as indicated in the line:
Chain INPUT (policy DROP)

To make your rule-set persistent, you can use iptables-save > rules_file to dump your rule-set to a text file. Then, it can be loaded during server startup by including it in any script using iptables-restore.


Java: criar inner join usando criteria

Question: Eu estou tendo dificuldades em encontrar bons exemplos de como criar uma criteria query usando inner join.
Eu criei a query abaixo que seria o que gostaria de fazer com a criteria.
SELECT DISTINCT *
FROM DT_DOCUMENT as document
INNER JOIN DT_TRANSLATION as translation
ON translation.language_id IN(1, 2, 3)
WHERE document.id = translation.document_id
AND document.title LIKE '%documento%';

Isso retornará todos os documentos com o título "Document" e que estão associados a traduções com id 1, 2 e 3.
Eu consegui dividir essa query em 2 selects diferentes utilizando o criteria e estão retornando os resultados, mas eu necessito do inner join para fazer o filtro necessário.

Translation criteria query

CriteriaQuery<Translation> translationQuery = builder.createQuery(Translation.class);
Root<Translation> translation = translationQuery.from(Translation.class);

List<Long> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
Predicate idPredicate = translation.in(ids);
translationQuery.where(idPredicate);
translationQuery.distinct(true);

TypedQuery<Translation> query =

this.entityManager.createQuery(translationQuery);
query.getResultList();

Retorna todas as traduções com id 1, 2 e 3;

Document criteria query

CriteriaQuery<Document> documentQuery = builder.createQuery(Document.class);
Root<Document> document = documentQuery.from(Document.class);

Predicate titlePredicate = builder.like(document.get("title"), "%documento%");
documentQuery.where(titlePredicate);
TypedQuery<Document> query = this.entityManager.createQuery(documentQuery);
query.getResultList();

Retorna todos os documentos com o título "Document".
Agradeço a qualquer contribuição, obrigada.
Answer: Seguindo a Documentação Oracle
Ficaria assim:
CriteriaQuery<Translation> translationQuery = builder.createQuery(Translation.class);
Metamodel m = em.getMetamodel();
EntityType<Translation> Translation_ = m.entity(Translation.class);

Root<Translation> translation = translationQuery.from(Translation.class);
Join<Translation, Document> documents = translation.join(Translation_.documents);

cq.where(pet.get(Pet_.color).isNull());

List<Long> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
Predicate idPredicate = translation.in(ids);
translationQuery.where(idPredicate);
translationQuery.distinct(true);

Comment: Seria a referencia do "document_id", mapeada na classe Translation.
Comment: O que seria o valor deste Translation_.?
Comment: Bem eu não consegui aplicar esse modelo da Oracle, entanto consegui tirar ideias pra complementar o meu, obrigada.
Answer: Após muito pesquisar consegui chegar nesta solução unificando as 2 queries e utilizando o inner join:
    //criação da query
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Document> documentQuery = builder.createQuery(Document.class);
    Root<Document> root = documentQuery.from(Document.class);

    //lista de parâmetros para where
    List<Predicate> predicateList = new ArrayList<Predicate>();

    //fazendo o join: passo a referência de translations (list<Translations) que existe no model do documento.
    Join<Document, Translation> documentTranslationJoin = root.join("translations");
   //pego as ids das linguagens associadas as traduções encontradas no join
    Path<Long> translationLanguageId = documentTranslationJoin.get("language");
    //passo os ids das linguagens que quero encontrar traduções
    List<Long> ids = new ArrayList<>();
    ids.add(1);
    ids.add(2);
    ids.add(3);

    //considera linguagens das traduções
    Predicate predicateTranslationId = builder.isTrue(translationLanguageId.in(ids));
    //passei os ids das linguagens que será o where buscando as traduções que tem os ids das linguagens que desejo ver
    predicateList.add(predicateTranslationId);

    //considera titulo do documento
    Predicate titlePredicate = builder.like(root.get("title"),"%documento%");
    predicateList.add(titlePredicate);

    //where
    Predicate[] predicates = new Predicate[predicateList.size()];
    predicateList.toArray(predicates);
    documentQuery.where(predicates);

    //execução da query com seus parâmetros
    TypedQuery<Document> query = this.entityManager.createQuery(documentQuery);

    query.setFirstResult(0);
    query.setMaxResults(8);

    //resultados da query
    List<Document> documents = query.getResultList();

Java: criar inner join usando criteria