How to navigate to previous activity when back icon is clicked instead of the complete toolbar in Android?

Question: I am developing an android application and want to navigate up to the previous activity from the current activity.
Here, I want to navigate back to MainActivity from SecondActivity. I have added a toolbar and a back icon, which should navigate back to the previous activity when clicked. But here, the complete toolbar navigates back to the previous activity when clicked.
SecondActivity.java
package com.example.acer.videoapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class SecondActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();
    private ProgressDialog pDialog;
    private ListView listView1;
    Toolbar toolbar1;
    String subjectName;

    ArrayList<HashMap<String, String>> lessonList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        //setting title to toolbar
        toolbar1 = (Toolbar) findViewById(R.id.toolbar1);

        Bundle bundle = getIntent().getExtras();
        if(bundle!=null) {
            toolbar1.setTitle(bundle.getString("Subject"));
            subjectName=toolbar1.getTitle().toString();
        }

        lessonList = new ArrayList<>();
        listView1 = (ListView) findViewById(R.id.list);
        new GetLessons().execute();

        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
                HashMap<String, String> lesson = lessonList.get(i);
                intent.putExtra("number", lesson.get("number"));
                intent.putExtra("name", lesson.get("name"));
                //intent.putExtra("subject", listView1.getItemAtPosition(i).toString());
                startActivity(intent);
            }
        });

        //back navigation
        toolbar1.setNavigationIcon(R.drawable.back);
        toolbar1.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(),MainActivity.class));
            }
        });

    }

    /* Async task class to get json by making HTTP call */
    private class GetLessons extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(SecondActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String url = getResources().getString(R.string.lessons_url, subjectName);
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    // Getting JSON Array
                    JSONArray lessons = new JSONArray(jsonStr);

                    // looping through All lessons
                    for (int i = 0; i < lessons.length(); i++) {
                        JSONObject c = lessons.getJSONObject(i);

                        String number = c.getString("lessonNo");
                        String name = c.getString("lessonName");

                        // tmp hash map for single lesson
                        HashMap<String, String> lesson = new HashMap<>();

                        // adding each child node to HashMap key => value
                        lesson.put("number", number);
                        lesson.put("name", name);

                        // adding lesson to lesson list
                        lessonList.add(lesson);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Couldn't get json from server. Check LogCat for possible errors!",Toast.LENGTH_LONG).show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    SecondActivity.this, lessonList,R.layout.list_item, new String[]{"number", "name",}, new int[]{R.id.lnumber,R.id.lname});
            listView1.setAdapter(adapter);

        }

    }

}

activity_second.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.acer.videoapp.SecondActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="@color/blue"
        android.theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        />

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/toolbar1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        />

</RelativeLayout>

Comment: Are you finish your MainActivity when you open the SecondActivity?
Answer: its very simple, call onBackPressed() on click of your navigation icon
    toolbar1.setNavigationIcon(R.drawable.back);
    toolbar1.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });


What are 5 and 6 note chords called?

Question: I only know how to play 2 different types of chords which is a Triad (3 notes) and a 7th (4 notes). But, I often see chords with 5 or 6 notes being used. What are these types of chords called?
An example is in the images on this page (towards the bottom) http://www.attackmagazine.com/technique/passing-notes/passing-notes-deep-house-chords/
Comment: Can you post the chords you're referring to? The ones at the bottom I see are major 7th chords
Comment: @Shevliaskovic these ones ... http://www.attackmagazine.com/wp-content/uploads/2012/06/maw-muted-copy-631x223.png
Comment: Dunno - but I know 12-key chords are called "armbars" :-)
Comment: it does not matter, it's still a chord. You need at least a triad to make a chord, any additional notes stacked up doesn't change how they are called. You have different names not for how many more notes a triad can have, but for the TYPE of chord, e.g. a seventh chord, a dominant chord, a diminished seventh chord, etc
Comment: On a guitar, they are called barré chords.
Answer: They are called "5 note chords" and "6 note chords" because they are not so fundamental a component of music that they need a shorter name.
A "triad" applies to many different three-note chords - always based around the root, a third, and a fifth -- but the third may be major (4 semitones from the root) or minor (3 semitones from the root), and the fifth may be perfect (7 semitones from the root) augmented (8) diminished (6).
You've encountered a four-note dominant 7th chord, which is a major or minor triad plus a flattened 7th. But there are lots more 4-note chords - any combination of four notes, some more pleasant sounding than others.
The article you've linked has helpfully colour-coded the notes in the chords. Let's look at one of the chords - the second chord in this piano roll:

The author has already told you the colour coding: root (purple), 3rd (blue), 5th (yellow) and 7th (green).
This 6 note chord contains:

Ab (root)
C (3rd)
Eb (5th)
G (major 7th)
C (3rd)
Eb (5th)

Note that there are two 3rds and two 5ths. This is a 4-note chord, an Ab major 7th, with two of the notes doubled up by playing their octaves.
The author also tells you:

Notes highlighted in red aren't in the basic chords, but are added on top to form a simple melody

The following "8 note" chord is really a four-note chord -- C minor 7th -- with two notes doubled up, to make it 6 notes, and two melody notes, which are not part of the chord as such.
Comment: Perhaps a mention of *extended* chords would help here?
Comment: what an excellent response. Many thanks for taking the time to explain that, I understand it much better now.
Comment: @slim - this is NOT a criticism of your superb answer, but the chord is Ab maj7, with the maj.7 note being G.            These sort of voicings are commonplace for guitarists. And don't forget 'sus' triads !
Comment: @Tim Well caught. Of course it is.
Comment: @Tim ... but I'm going to gloss over sus chords for now. I think we've blown James' mind enough already.
Comment: @slim - good call. I guess the guy's a guitarist, with 5 or 6 note chords, so if it's acoustic stuff, those sus chords could come in handy.Maybe later...
Answer: Regarding 5 and 6 note chords, as well as chords beyond the "triad/seventh chord" nomenclature:
Chords with 5, 6 or 7 notes, if arranged in 3rds, are chord "extensions"
Root - 3rd - 5th - 7th - 9th - 11th - 13th.
You could call a chord with 5 notes a "quintal chord" and a 6-note chord a "sextal" chord. But let us examine chord structures in order to distinguish between chord types:

One needs to gather the vertically presented pitches (the different notes played together as a chord). We must only consider distinctly different pitches and eliminate any duplicated notes (octaves higher or lower) and enharmonic notes (pitches with the same sound but with different letter-names (such as E# and F)
Once the chord is reduced to its essential pitches, proceed.
Look for patterns amongst the pitches: do they fit into a tertian (thirds) pattern? (i.e. the "order of 3rds" contains all tertian chords - from 3-note triads to 7-note 13th chords: ...A C E G B D F|A C E G B D F...  This may require 'respelling' enharmonic notes disguising a 3rd pattern. If not, proceed.
If most of the notes in your chord fit into a tertian pattern, see whether the "wrong" note(s) result from a "false" bass or an appoggiatura chord. The false bass could be part of a "pedal point" or just a note used to "colour" the harmony. The appoggiatura chord will "resolve" into a conventional harmony on the next (or nearby) beat. If not, proceed.
Study the intervals between the chord tones, they will likely fit into one of the following categories:
Secondal: harmonies arising from notes a 2nd apart. Often called "clusters";
Tertiary (already discussed 3rd chords)
Quartal: harmonies arising from notes a 4th or 5th apart
6th intervals: invert and reduce to 3rds;
7th intervals: invert and reduce to 2nds
If none of these chord types applies, then proceed.
If your chord is not tertial, secondal or quartal, then it is likely the result of a chromatic serial compositional process. The system developed to analyze these vertical sonorities is known as the "pitch class" system. In this system, each note of the chromatic scale is numbered 1-12 (often starting on C).
The distinct notes are then collected, placed in the order of the chromatic scale (within the same octave) and identified by their resultant number.
For example: consider the chord: C, Db, E, F, Ab, this is a 5-note (or 'quintal') chord of pitch class 12569. Use this method if all other "tonal" analytical interpretations produce unsatisfactory results (or if you know that a serial compositional process was used.)
Comment: `quartal` & `quintal` already have established meanings in terms of chordal structures other than `tertian` as you mention in your answer. I'm not sure repurposing them to number of notes in the chord add much clarity.

What are 5 and 6 note chords called?


How to make user profile image reflect a transparent background?

Question: I made a site with Drupal 7.26. Added on the Advanced Forums module with some other things.
Everything works fine except the user profile image is displayed with a white box/background instead of being transparent in the forums and user profile when clicking on the user name. I'm using a png image that has a transparent background.
Here's a cropped screenshot of how the picture is being displayed in the forums.

As you can see there is a white box/background instead of it being transparent. The strange thing is that when I hover over the image with my mouse the white box/background disappears and the image displays as it should.
Here's a cropped screenshot of what it looks like when the cursor is hovered over the image.

That is how I would like the profile pictures to be displayed in the forums should a picture have a transparent background.
Does anyone know of a setting or something on how to get this done?
I'd really really appreciate any help with this as I'm pretty clueless.
Thanks in advance for any replies
Barrels
Answer: If the image background is transparent when you hover over it, then the picture has transparency, and must be a .png or .gif file.
Therefore the white background must be down to CSS
In Chrome or Firefox, right click on the image and select "Inspect Element". Find the CSS controlling the div or img, and change the CSS from
<code>.picture {
   background:#FFFFFF;
}
</code>
to
<code>.picture {
   background:none;
}
</code>
Comment: Thank you so so much. That was perfect. This is my first post so I don't have the required reputation to vote your comment up. Thanks again! :)
Comment: No problem. Glad to help :)


.htaccess retirar nome das vars do url mas deixar as vars

Question: Neste momento tenho os URLs:
www.meudominio.com/?route=service&serv_name=cascais_proxima&id=1
e
www.meudominio.com/?route=ticket&serv_id=1&ticket=A
mas gostaria que ficasse:
www.meudominio.com/service/cascais_proxima
e
www.meudominio.com/ticket/1/A
Há maneira de o fazer?
Answer: Olá, tem sim ficaria da seguinte forma no .htaccess :
RewriteEngine On
RewriteRule ^pagina/(.*)/(.*)/(.*)$ /pagina.php?route=$1&serv_name=$2&id=$3
Que no final ficaria algo como: pagina/rota/servidor/1
Sendo o (.*) o que você quer substituir e o $[numero] a posição da URL que vc obteve e quer sobrescrever.
Espero ter ajudado.
Comment: Desculpe mas pode ser mais explicito? O que escreveria no url para ver se resulta, no meu esemplo... Já tenho o meu .htaccess definido com esse conteudo
Comment: Não está a resultar
Comment: Para o 1º tentei: `.../service/cascais_proxima/1`, não deu
Comment: Olá Miguel, seguinte. Crie o arquivo na raiz do seu site com o conteúdo acima ajustando apenas a sua URL com o exemplo que fiz acima.


How to prove ~~A,A→B⊢B without double negation elimination

Question: This is an exercise from Mathematical Logic: A First Course by Joel W. Robbin.
The formal language PI, is obtained from the formal language P by deleting ⊥ from the set of primitive symbols and deleting rule (W2) (which says that ⊥ is a wff) in the definition of wff. The axiom schemas for PI are A$\rightarrow$[B$\rightarrow$A], [A$\rightarrow$[B$\rightarrow$C]]$\rightarrow$[[A$\rightarrow$B]$\rightarrow$[A$\rightarrow$C]], and [[A$\rightarrow$B]$\rightarrow$A]$\rightarrow$A (Peirce's law), and the rule of inference of PI is $modus\;
ponens$. The definitions of deduction in PI, deduction from hypotheses in PI,
and theorem of P, are $mutatis\;mutandis$ the same as for P. The notation $\vdash_\mbox I$ A
means A is a theorem of PI, and QA is an abbreviation for [A$\rightarrow$Q], In unabbreviating an expression which uses this abbreviation more than once use
association to the right; that is, QQA stands for QA$\rightarrow$Q rather than A$\rightarrow$QQ. Notice that the wff QA behaves very much like the wff ~A:=A$\rightarrow\bot$.
Show that the deduction theorem holds for P, and prove the following
theorem schemas.
(1) $\vdash_\mbox I[\mbox A\rightarrow \mbox B]\rightarrow[[\mbox B\rightarrow \mbox C]\rightarrow[\mbox A\rightarrow\mbox C]]$
(2) $\vdash_\mbox I[\mbox A\rightarrow\mbox B]\rightarrow[\mbox{QB}\rightarrow\mbox{QA}]$
(3) $\vdash_\mbox I\mbox A\rightarrow\mbox{QQA}$
(4) $\vdash_\mbox I\mbox{QQQA}\rightarrow\mbox{QA}$
(5) $\vdash_\mbox I\mbox{QQB}\rightarrow\mbox{QQ[A}\rightarrow\mbox B]$
(6) $\vdash_\mbox I\mbox{QQA}\rightarrow[\mbox{QB}\rightarrow\mbox{Q[A}\rightarrow\mbox B]]$...
I am now stuck at (6). Using the deduction theorm, I can convert (6) into $\mbox{QQA}\vdash_\mbox I\mbox{QB}\rightarrow\mbox{Q[A}\rightarrow\mbox B]$ and further into $\mbox{QQA}\vdash_\mbox I[\mbox A\rightarrow\mbox B]\rightarrow\mbox B$ by (2) and modus ponens. But I don't know how to proceed without double negation elimination to deal with that QQA.
Any help will be appreciated.
Comment: The Double Negation Elimination is typically a straightforward consequence of the Duns Scotus Law $\neg \phi \rightarrow (\phi \rightarrow \psi)$ and the Law of Clavius $(\neg \phi \rightarrow \phi) \rightarrow \phi$. Can you prove those? Because then fill in $\neg \neg A$ for $\phi$ and $A$ for $\psi$ in the Duns Scotus Law, fill in $A$ for $\phi$ in the Law of Clavius, and use your principle 1 to do the Hypothetical Syllogism on these.
Comment: I don't think QQA→A can be proved in this setting. Q is a metavariable which can be replaced by any proposition. It is only a crippled surrogate for ⊥.
Comment: (6) is provable without pierces law, it isn't a short proof though.  I'll work on writing it up...
Comment: The short answer to your question is :
$$\lambda xyz~.~x(\lambda v.y(zv))$$
$$\begin{array} {c|l} \text{variable} & \text{type} \\ \hline
x & ((A \to Q) \to Q \\
y & B \to Q \\
z & A \to B \\
v & A
\end{array}$$

is a well typed simply typed lambda expression, the entire type of which is $((A \to Q) \to Q) \to (B \to Q) \to (A \to B) \to Q$.  So (6) is provable using only the first 2 axioms listed.
Answer: I can show you how to solve (6) using type theory.

(6) $$((A \to Q) \to Q) \to (B \to Q) \to (A \to B) \to Q$$

Proving this is equivalent to finding a lambda expression available with the above type. (You can assume the existance of an expression of the type $(((g \to h) \to g) \to g$, but that is fortunately not necessary in this case).  By trial and error, an expression can be found:
$$\lambda xyz~.~x(\lambda v.y(zv)) \tag{P1a}$$
$$\begin{array} {c|l} \text{variable} & \text{type} \\ \hline
x & ((A \to Q) \to Q \\
y & B \to Q \\
z & A \to B \\
v & A
\end{array} \tag{P1b}$$
This allows you to construct a proof if you have deduction theorem available:
$$\begin{array} {r|ll}
%
(1) & ((A \to Q) \to Q) & \text{Premise} \\
%
(2) & B \to Q & \text{Premise} \\
%
(3) & A \to B & \text{Premise} \\
%
(4) & A & \text{Premise} \\
%
(5) & B & \text{Modus Ponens 3 , 4} \\
%
(6) & Q & \text{Modus Ponens 2 , 5} \\
%
(7) & A \to Q & \text{Deduction theorem on 6 removing premise 4} \\
%
(8) & Q & \text{Modus Ponens 1 , 7} \\
%
(9) & (A \to B) \to Q & \text{Deduction theorem on 8 removing premise 3} \\
%
(10) & (B \to Q) \to (A \to B) \to Q & \text{Deduction theorem on 9 removing premise 2} \\
%
(11) & ((A \to Q) \to Q) \to (B \to Q) \to (A \to B) \to Q & \text{Deduction theorem on 10 removing premise 1} \\
%
\end{array}$$
And if you don't have the deduction theorem immediately available, then the proof is very very long.
Comment: Thanks for the reply. There is one thing I don't understand. You seem to claim that type A is inhabited, which isn't assumed by the exercise and this is exactly where I'm stuck in. If QQA->A were available, I could prove A with QQA, but there is no double negation elimination.
Comment: The conclusion doesn't depend on A being provable.  That's the entire point of the deduction theorem.  The premise of A is removed in step 7.
Comment: With respect to the "very very long" comment, I fired up Prover9 and in less than 10 seconds, it found a proof that has only 14 condensed detachments.  Though, it indicated a proof of the more general CCCxyzCCuyCCxuz.
Answer: QQA stands for [QA -> Q].  QA is an abbreviation for [A -> Q].  Thus,
QQA stands for [[A -> Q] -> Q], correct?
So, if you expand out (6), without the meta-logical $\vdash$$_I$, you end up with (and add some points for emphasis) the following
[.[[A -> Q] -> Q]. -> [:[B -> Q]: -> [;[A -> B]; -> Q]]], correct?
Thus, assume

[[A -> Q] -> Q].  Then assume
[B -> Q].  Then assume
[A -> B]

Now, can you deduce Q?
Comment: If QQA→A were available, I could use modus ponens to produce Q. But the only QQA related thing I have now is (5)QQA→QQ[B→A]. I can't see how this makes way to Q.


Searching in .txt file that contains class

Question: I am very new to C# (only experience with programming was with Haskell and a bit of C) and I was tasked with learning this language by myself and doing a project using it.
So, what I pretend to do is to use user input (an AccessKey) as a way to locate which Tech is login in by comparing between AccessKeys in a .txt (that only contains this class, Tech) and then return the TechID and TechName associated with the inserted AccessKey.
class Tech
{
    public String TechName
    { get; set; }
    public String TechID
    { get; set; }
    public String AccessKey
    { get; set; }
    public Tech(String TechNames, String TechIDs, String AccessKeys)
    {
        TechName = TechNames;
        TechID = TechIDs;
        AccessKey = AccessKeys;
    }
}

class Registo
{
    public List<Tech> ListaTech
    { get; set; }
    public Registo()
    {
        ListaTech = new List<Tech>();
    }
    public void addTech(Tech tech)
    {
        ListaTech.Add(tech);
    }
}

This are the classes that I am using, and following is the code responsible for updating the .txt file
    private void saveRegistry(string v, Tech tech)
    {
        IFormatter formatter = new BinaryFormatter();
        Registo registo;

       using (Stream stream = new FileStream(@"C:\\Registry.txt", FileMode.Open, FileAccess.Read))
        {
            registo = (Registo)formatter.Deserialize(stream);
            registo.addTech(tech);

        }
        using (Stream stream = new FileStream(@"C:\\Registry.txt", FileMode.Create, FileAccess.Write))
        {
            formatter.Serialize(stream, registo);
            stream.Close();
        }
    }

at the button click is what is below:
        string pastaMae = "C:\\";
        string directoryName = pastaMae;
        string fileName = "Registry.txt";

        string techNames = textBoxRegisto1.Text;
        string techIDs = textBoxRegisto2.Text;
        string AccessKeys = textBoxRegisto3.Text;
        Tech tech = new Tech(techNames, techIDs, AccessKeys);

        try
        {
            // This line creates the directory using the path that was just created
            Directory.CreateDirectory(directoryName);

            saveRegistry(pastaMae + fileName, tech);

        }
        catch (Exception e2)
        {
            Console.WriteLine(e2.StackTrace);
        }

    }

What I can't do (and need help with) is to create a function to compare the user input with the AccessKeys on the file and then to return the TechID and TechName that is associated with it.
Something that maybe would start like this?
    public Tech getTech(String AcessKey)
    {

    }

I think this code explains what happens much better than me, but if you need any more code or for me to explain in a different way I will try my best. Sorry for my lack of use of better and proper terms, as I said I am pretty new to C#.
Comment: A couple of questions: why are the parameter names for your `Tech` constructor plural nouns (`TechNames`, etc.)? Why are you using a binary formatter to save/read text information? Have you considered a format like JSON? It would make your debugging easier. If it were me, I'd keep everything in a `Dictionary` and use a JSON serializer
Comment: For no particular reason, I thought I could name them anything I just add 's' in front of all 3.

I can't really answer that well, my knowledge equals 0. I just tried out this way until it worked.
I am not aware of JSON formatting, what sections of code that I should would I have to change? Just the classes?
Thank you for your input!
Comment: I just want to add that I have almost no theoric basis and this project is the first code I am writing in C#, my knowledge and experience in C and Haskel isn't really broad at all.
Comment: If this is anything other than a project to learn C#, please don't store credentials in plaintext on disk. Use a real, secure authentication mechanism.
Comment: no, this is university work, but thanks
Answer: Seems to me like your Registo class should know how to load itself from a text file and save itself to a text file. For simplicity I'll show how to make a tab separated file:
class Registo
{
    public List<Tech> ListaTechs { get; set; }
    public Registo()
    {
        ListaTechs = new List<Tech>();
    }
    public void AddTech(Tech tech)
    {
        ListaTechs.Add(tech);
    }

    public void Load(string filePath){
      foreach(string line in File.ReadAllLines(filePath)){
        var bits = line.Split('\t');
        if(bits.Length != 3) continue;

        var tech = new Tech(bits[0], bits[1], bits[2]); //assume you save like nameTABidTABkey

        AddTech(tech);
      }
    }

    public void Save(string filePath){
      var sb = new StringBuilder();

      foreach(var tech in ListaTechs)
        sb.AppendFormat("{0}\t{1}\t{2}\r\n", tech.TechName, tech.TechId, tech.AccessKey);

      File.WriteAllText(sb.ToString(), filePath);
    }
}

It adds a couple of methods that let a Registo load/save itself from/to some given path. Registo defines the format it will save so that it can load itself again via the same format
Now we can load techs from disk, search them for an AccessKey:
var reg = new Registo();
reg.Load(@"C:\registo.txt");

var accessKey = "the key you are searching for";
var tech = reg.ListaTechs.FirstOrDefault(t => t.AccessKey == accessKey);

You'd probably encapsulate this final line as a new method in Registo, perhaps called FindByAccessKey(string accessKey)
For FirstOrDefault to work you'll need to using System.Linq and you should use the fact that null will be returned if there is no tech with the given access key.. Oh, and that comparison is case sensitive

A few notes on styling your code:

In C# methods and properties are NamedLikeThis i.e. PascalCase, parameters to methods are namedLikeThis i.e. camelCase, and we use plurals for collections (ListaTechs).

Generally the get/set for a property go on the same line as the prop name if they are empty; put them on new lines if they have a body
Comment: Thank you for your input! How does your Save differ from my saveRegistry? Besides being inside the class
Comment: Please do not put code in comments; the formatting is awful
Comment: Well, it a) only saves a file (your save seems to load?), and it saves it as a text file - binary formatter won't :).. Personally I would make a workflow like "load" then "add to" then "save", rather than making a "save" actually do an "append" ..
Comment: Thank you so much for the explanation and extra pointers!
Comment: Sorry for the dumb question but the 4 lines of code in the smaller block belong within the method FindByAccessKey(string accessKey) that's in the Registo right?
Comment: It depends on how you want to do things, but I'd say "no" - it was not my intent that those 4 lines would be the "FindByAccessKey" - only the final line would be "find by accesskey" as it is the only line that implements a find operation. The first two lines load the registo, and the third line simply declares an example parameter, which would be the `string accessKey` in  method signature like `FindByAccessKey(string accessKey)`. I would imagine that your program would load a registo as a one time operation when it starts, but it would repeatedly FindByAccessKey when running, hence why I ...
Comment: ..wouldn't expect the file to be loaded from disk every time the find occurs. Don't forget that the Load operation as written doesn't clear the existing data, so if you did have a Find op that loaded the same file again and again, by the time you've searched your 10 entries a hundred times your registo has a thousand things in its list
Comment: Ok, I will try to make it work like that :) thank you once again


Indefenite Integral requiring substitution

Question: Can someone please help me find a useful substitution for the following integral:
$$\int \frac{1}{\sqrt{x}(1+\sqrt{x})^2}dx$$
I tried letting $ u = \sqrt{x} $ But I couldn't proceed. Please help.
Answer: Setting $1+\sqrt x=u$ gives you
$$\frac{dx}{\sqrt x}=2du.$$
So,
$$\int\frac{1}{(1+\sqrt x)^2}\cdot\color{red}{\frac{dx}{\sqrt x}}=\int\frac{1}{u^2}\cdot \color{red}{2du}.$$
Answer: That's certainly a workable solution, as you can absorb the factor of $\sqrt{x}$ in the denominator when you write $du$, but you may as well take care of the constant in the parenthetical quantity and substitute
$$u = 1 + \sqrt{x},$$
so that $du = \frac{1}{2 \sqrt{x}}dx$, and your integral becomes
$$2 \int \frac{du}{u^2}.$$


What do you call a javelin thrower?

Question: Is there a name for a javelin thrower?  in baseball we've got pitcher, batter etc.
Comment: As the answers indicate, there's no accepted specific term, but you may find some sportswriters fond of florid prose who invent colorful phrases like "spear men" and so on.
Answer: Like Philip Kendall said, in athletics, a person who throws a javelin is called a "javelin thrower".  Collins Dictionary has an entry for "javelin thrower":

(athletics) a person who throws a javelin

There is the word "javelinier" (or "javelineer"), but apparently that is only used for non-athletic purposes.  Wikitionary defines "javelinier" as:

A soldier who throws a javelin

There used to be the word "jaculator", which is defined in The Century dictionary and cyclopedia (published in 1906) as "one who throws (a javelin)":

There is even an entry in dictionary.com which has the same definition for "jaculator", but I'm fairly certain that word isn't used nowadays.
Answer: I don't believe there is a more specific term than "javelin thrower". Certainly that's what Wikipedia uses to describe eg Jan Železný:

Jan Železný [...] is a Czech javelin thrower

What do you call a javelin thrower?


Is it appropriate to put "error bars" on data when you have the full population?

Question: I have data on the large number of people who were applying to receive an award.  Everyone who applied must fill out a survey and specify their gender (although they can choose "prefer not to say").  My question: is it appropriate to put "error bars" on this data given that the survey was not a sample of the population, but rather the whole population?  (Any citations would be helpful.)
Comment: Do you have some super-population in mind here? For example, there could be applicants next year or people who did not know about the grant that are not in your sample. If your goal is to say something about that larger population, SEs make sense. See more [here](https://stats.stackexchange.com/a/533894/7071). Another way this could creep up is if the judges reading the applications are the source of the randomness here. For example, if the approval process has some subjective evaluation and is not just a formula where two judges always disagree.
Comment: Re: the superpopulation, I wasn't familiar with this so hadn't thought about it. There will be applicants every year, and there definitely are people who did not know about the award that did not apply, but could have applied.
Comment: What type of graph are you creating? It would not be appropriate to create a confidence interval because that is interpreted as you are ___% confident that you captured the population mean, except you are 100% confident since you know the population mean.
Comment: TY. This would be reporting e.g. 37% of applicants were men, 60% were women, and 3% were unknown.
Comment: I believe that you might find this article interesting: https://onlinelibrary.wiley.com/doi/abs/10.3982/ECTA12675
Answer: Error bars show intervals; these intervals must represent something
Error bars in a plot show an interval for a particular quantity, and like any element of a plot, these intervals must actually represent something.
Intervals in a plot are generally useful in two situations: when you want to show an interval estimate for an unknown quantity, or when you want to show an interval that represents some descriptive aspect of the sample data.
The most common use of error bars is when you have an unknown quantity that you are estimating with data.  Typically this will occur when we have an estimate of some unknown quantity (which is a single point) and then the error bars are used to give an interval estimate for the quantity which encompasses the point estimate.  In your case, you have a full population of values, so there is no unknown quantity of interest to you.  Sometimes people may wish to use full population data to make an inference about some unknown aspects of a hypothetical "superpopulation" (and infinite extension of the population), in which case there may be some unknown quantity of interest.
The other case where error bars are sometimes used is when you want to show an interval range pertaining to a descriptive quantity that is known, rather than as an interval estimate for an unknown quantity.  For example, a graphical element that is somewhat akin to an "error bar" is used in a box-and-whiskers plot.  More generally, if you have a set of sample data with continuous measurements divided into categories, it is not unusual to give a barplot of means with bars showing some descriptive range for the subsample of continuous values in each category (e.g., interquartile range, or a certain number of sample standard deviations from the sample mean, etc.).  In this case the bars are used to indicate some kind of descriptive range pertaining to a sample.  Strictly speaking, these bars don't represent "errors" but they are nevertheless graphically identical to bars indicating interval estimates accounting for "errors".
Often there is a crossover between these two cases, when a descriptive interval pertaining to the data also functions as an interval estimate for some unknown quantity for an object outside the data.  In any case, whenever you produce a plot with error bars, you must ensure that the meaning of your bars is clear.  For certain plots like the box-and-whiskers, the meaning of the bars is fixed by convention (so no explanation is required), but in other cases you should tell your reader what the error bars on your plot represent.
If you think you might need to use error bars, or other bars that are graphically identical to error bars, you need to step back and ask yourself: What is the purpose of the interval I am proposing to show with these bars?  It it an interval estimate of an unknown quantity?  (If so, what is the unknown quantity?  What type of interval estimator are you using?)  Is it an interval representing some aspect of the data?  (If so, what aspect of the data does it represent?)  If you do not have satisfactory answers to these questions, then you do not have a need to use error bars in your plot of the data.
Comment: TY!!  This is the typical data I would report (note: data made up)
"About 60% of applicants for the award in 2020 were female, 37% were male, and 3% were unknown. 61% of award SELECTIONS in 2020 were female, 36% were male, etc.  The success rates (selections/submissions) were 26% for females, etc. it sounds like the consensus is NOT report error bars (e.g. confidence intervals) on these percentages, since the numbers are exact.
Comment: To learn about the notion of a superpopulation, I recommend taking a course on sampling theory.  In any case, let's put it this way.  If five seconds ago you hadn't heard of a superpopulation, then it stands to reason that your goal here had nothing to do with inference of unknown quantities from a superpopulation.  So again, if you ask yourself, the question "What is the unknown quantity I am estimating", it is likely that the answer here is that there isn't one (in which case you don't need error bars).
Comment: (+1) Something that irks me about people putting "error bars" based on sampling error despite having (often large) population data at their disposal, is the false sense of certainty: often things like measurement error are far bigger problem, so even if you think of this as a draw from a superpopulation, the sampling error for such high $n$ is practically irrelevant. Self-reported gender for an award certificate likely gets useful responses. but low-stakes multiple choice questionnaires can suffer from "lizardman's constant" & self-reported height/weight figures can be all over the place.
Comment: I'm unclear though whether the error bars SHOULD be reported if there is a "superpopulation." Firstly, can ALL finite populations can be considered a sample from a superpopulation? What if someone said that the population of award applications is hypothetical, and could have turned out differently if different people decided to apply, or some people were notified about the award when they hadn't been– would it make sense THEN to report error bars on the data above?  Or would that still not make sense? I'm not sure how I would interpret such error bars.
Answer: @Ben is of course right that there is no "error" if you have the full population. But at least colloquially, "error-bars" are not always referring to uncertainties comming from a incomplete sample. And just a single number is seldomly useful, even if it is "exact". Two examples:

If you say "$34.7$ percent of applicants were male", then that number is exact and should not have an error-bar. BUT: If your goal is to say something about gender-bias for example, the exact number itself is not sufficient. You need to add a line like "given the total number of applicants that we have, a deviation from a 'perfect' 50% by $\pm X$ is statistically expected without any bias existing". This number $X$ is not an error-bar of your data. But it can serve the same purpose: It informs the reader to what degree the first number you quote is meaningful.

If you say "on average, the applicants are $34.7$ years old", it might again be less helpful to the reader as it could be. Saying "the mean age of applicants is $34.7$ years with a standard deviation of $4.6$" is much more useful. This second number is of course not an error-bar, but it serves the same purpose because it tells the reader a range of expected results, which is generally more helpful than one central result alone.

(After thinking about it, case (1) is essentially equivalent to the thing @Ben was referring to as "superpopulation")
Comment: Is that not really then asking a question about the data generating process in general? E.g. it seems you ask a question like "Is this data consistent with the theory that - given approx. 50% equally qualified male and female potential recipients - the people handing out the reward were equally likely to choose a male or female awardee?", right? In a way, you are then not putting an error bar on the percentage, but on parameters of an assumed underlying data generating model. But, yes, I'd agree that doing so might make sense even if the award will never be given out again...
Comment: Thank you. How would you calculate "standard deviation of 4.6" in this case though?
Comment: @Björn you are correct. That example tells you something about consistency with some null-hypothesis about the data-generation process. My overall point was just this: "Just quoting a single number is seldomly useful". You pretty much always need a second number that gives some sort of "range" or "scale" to the first. It can be outright misleading to quote just a single number (especially if it is "exact"), because that number suggests more meaning than it actually has.
Comment: This is a good answer (+1), although I agree with Björn's rejoinder in comments.  In any case, I've now edited my own answer to note the use of bars to represent ranges of descriptive quantities.
Comment: Thank you Simon for your helpful responses.


Sum of production of k out of n variables

Question: Given a vector of positive values $$v_{1:n} = <v_1,v_2,,,,v_n>$$, define $$SumProd(v_{1:n},k) = \sum_{s \in S_k^n} \prod_{i \in s} v_i$$. It seems that this requires $O(n^k)$ computation. Is there a faster way to compute SumProd?
Comment: Use the recurrence $$\text{SumProd}(v_{1:n},k)=\text{SumProd}(v_{1:(n-1)},k)+v_{n}\cdot \text{SumProd}(v_{1:(n-1)},k-1)$$to compute this with dynamic programming in $O(nk)$ time.
Answer: It is commonly denoted by $e_k(v_1,\ldots,v_n)$ and called the $k$-th elementary symmetric polynomial.
Using Newton's identities (let's assume $e_0(v_1,\ldots,v_n):=1$ below) $$ke_k(v_1,\ldots,v_n)=\sum_{j=1}^{k}(-1)^{j-1}e_{k-j}(v_1,\ldots,v_n)p_j(v_1,\ldots,v_n),$$ where $p_j(v_1,\ldots,v_n):=\sum\limits_{i=1}^{n}v_i^j$, it is computed iteratively in $\mathcal{O}(nk)$ operations.


Inserção de elementos HTML dentro de outro HTML Gerado com Jquery em uma mesma função

Question: No meu seguinte código abaixo eu gostaria de inserir os dados vindo da requisição ajax, juntamente com os HTML do append() apenas nos elementos cujo id do input hidden fossem iguais ao item.id (do objItens). Porém todas as formas que eu imaginei não funcionam. Alguma dica de como posso implementar isso da melhor forma?
 function listaItensPorIdExecCadeia(objIdExecCadeia){

    var idExecucaoDaCadeia = [];

    objIdExecCadeia.map(cadeia => {

        $('#bloco-procedimento-lista-itens').append(`

${cadeia.nome} #${cadeia.id}

        <input id="inputIdExecucaoDaCadeia" type="hidden" value="${cadeia.id}" />

        `);
        idExecucaoDaCadeia.push(cadeia.id);
    });

    for(var i = 0; i <= idExecucaoDaCadeia.length; i++){

        $.get(BASE_URL+'item/listar',{
            idItem: idExecucaoDaCadeia[i],
        },
        function(objResponse){

            var objItens = objResponse.strMessage;

            objItens.map(item => {
                    $('#procedimento-lista-itens').append(`

${item.nome}

                `);
            })
        },'JSON'
        );
    }
}

Comment: Qual é exatamente o erro?
Answer: Acontece você está criando elementos com id duplicado no seu DOM o que não é nada recomendado, adicione um identificador único para os seus elementos dinâmicos.
function listaItensPorIdExecCadeia(objIdExecCadeia){

    var idExecucaoDaCadeia = [];

    objIdExecCadeia.map(cadeia => {

        $('#bloco-procedimento-lista-itens').append(`

${cadeia.nome} #${cadeia.id}

        <input id="inputIdExecucaoDaCadeia" type="hidden" value="${cadeia.id}" />

        `);
        idExecucaoDaCadeia.push(cadeia.id);
    });

    for(var i = 0; i <= idExecucaoDaCadeia.length; i++){

        $.get(BASE_URL+'item/listar',{
            idItem: idExecucaoDaCadeia[i],
        },
        function(objResponse){

            var objItens = objResponse.strMessage;

            objItens.map(item => {
                    $('#procedimento-lista-itens_'+idExecucaoDaCadeia[i]).append(`

${item.nome}

                `);
            })
        },'JSON'
        );
    }
}

Abaixo deixei um exemplo removendo a sua consulta dos itens de detalhes e simulando o resultado.

var cadeias = [{id: 1, nome: "teste"}, { id: 2, nome: "teste 2"}];
var itens = [{ cadeiaId: 1, nome: "sub teste 1 - 1"}, { cadeiaId: 1, nome: "sub teste 1 - 2"}, { cadeiaId: 2, nome: "sub teste 2 - 1"}, {cadeiaId: 2, nome: "sub teste 2 - 2"}];

function listaItensPorIdExecCadeia(objIdExecCadeia) {

  var idExecucaoDaCadeia = [];

  objIdExecCadeia.map(cadeia => {

    $('#bloco-procedimento-lista-itens').append(`

${cadeia.nome} #${cadeia.id}

        <input id="inputIdExecucaoDaCadeia" type="hidden" value="${cadeia.id}" />

        `);
    idExecucaoDaCadeia.push(cadeia.id);
  });

  for (var i = 0; i <= idExecucaoDaCadeia.length; i++) {

    var objItens = jQuery.grep(itens, function(n,j){
      return n.cadeiaId === idExecucaoDaCadeia[i];
    });

    objItens.map(item => {
      $('#procedimento-lista-itens_'+idExecucaoDaCadeia[i]).append(`

${item.nome}

                `);
    });

  }

}

listaItensPorIdExecCadeia(cadeias);

Comment: Obrigado Leandro, sua dica de gerar os IDs dinamicamente foi crucial para resolver meu problema.


Speaking words in an array

Question: I have an array of words that I would like to say aloud using the Web Speech API.
The words are one, two, three, four, five.
When speaking the words on Chrome, the script below says the first word and then repeats the last word until the iteration is complete, the speech output is:

one, five, five, five, five.

On Firefox, the script says the first word and then stops, the speech output is:

one.

I've logged things to the console in an attempt to figure out what's going on, this is the result from both browsers.
word: one
message: one
word: two
message: two
word: three
message: three
word: four
message: four
word: five
message: five

The output to the console is desired speech output so I am unsure what exactly is happening.

var msg = new SpeechSynthesisUtterance();
var words = ['one', 'two', 'three', 'four', 'five'];

for (var i = 0; i < words.length; i++) {
    msg.text = words[i];

    console.log('word: ' + words[i]);
    console.log('message: ' + msg.text);

    window.speechSynthesis.speak(msg);
}

What could be causing this and how can I go about correcting it?
Comment: any errors in console?
Comment: @ochi No errors in the console.
Answer: You need to use a new SpeechSynthesisUtterance instance each time.
var words = ['one', 'two', 'three', 'four', 'five'];

for (var i = 0; i < words.length; i++) {
    var msg = new SpeechSynthesisUtterance();
    msg.text = words[i];

    console.log('word: ' + words[i]);
    console.log('message: ' + msg.text);

    window.speechSynthesis.speak(msg);
}

Speech isn't played in zero time, and it appears that subsequent SpeechSynthesisUtterance instances are placed in a queue until previous speech has finished playing. You're reusing the same instance repeatedly,  modifying the values after they've been queued by speak(...) but before they've been popped off the queue and read. The first utterance ("one") is played correctly because there's nothing else in the queue to block it (it's read immediately), but the rest need to wait, and end up modified before being read.

Speaking words in an array


Maximize $x(C-x)A^2+y(D-y)B^2+(x(D-y)+y(C-x))AB$ where $A,B,C,D$ are Constant

Question: I am trying to figure out where the maximum occurs for the following expression of 2 variables ($x$ and $y$):
$x(C-x)A^2+y(D-y)B^2+(x(D-y)+y(C-x))AB$
where $-1\leq A,B\leq 1$, $C\geq 2$ and $D\geq 2$ are all constants. Moreover the range of values allowed for $x$ and $y$ is $0\leq x\leq C$ and $0\leq y\leq D$.
I tried taking partial derivatives but the second order partial derivative test (https://en.wikipedia.org/wiki/Second_partial_derivative_test) is inconclusive so I was wondering if there may be another way to approach this.
Comment: The level curves of this function are pair of (possibly coincident) lines with slope $-B/A$.
Answer: Hint:   write it as $\;(xA+yB)\big((C-x)A+(D-y)B\big)\,$ and use that $\,ab \le \left(\frac{a+b}{2}\right)^2\,$.


Can't run nutch from a Tomcat webapp on Windows

Question: I have a web app that spawns off a script that runs a Nutch crawl. It's all working really well, except now my client wants it running on a Windows PC.  The Windows PC she gave me is running Windows 7 Home Premium.
I've got nearly everything running, except when the crawl script - when it fires off nutch, nutch (which runs Hadoop, which for some bizarre reason does a whoami) fails because whoami returns "nt authority\system" instead of a single string.  The error:

javax.security.auth.login.LoginException:
  Login failed: Expect one token as the
  result of whoami: nt authority\system

Is there some way to change the name that whoami returns in that case?
Update: Just to clarify, the exact same script runs fine when I run it from the command line.  The problem is that Tomcat runs as a service, so the script it spawns is running as this "nt authority\system" user, which is what is confusing hadoop because it evidently expects whoami to return a single word, not two words separated by a space.
Answer:
The problem is that Tomcat runs as a service, so the script it spawns is running as this "nt authority\system" user, which is what is confusing hadoop because it evidently expects whoami to return a single word, not two words separated by a space.

Then change the account. Start > Run > services.msc, doubleclick the Tomcat service, open Log On tab and set the account there.
Comment: I did not know you could change that.  Thanks.
Answer: I run Nutch on my Windows PC using Vista... almost daily, with cygwin installed have you tried ?
Comment: Yes, I have cygwin installed.  You're not answering the question - I'm trying to run it from within Tomcat, which is run as a service, so it doesn't run with the same userid as if you start it yourself.


How to update or sync a tree from a sorted array in C

Question: I have one sorted int array and one avl tree. Array data is original data set and the tree is formed from the array elements. Need to get the list of elements in a tree which are either missing or extra from the original array and make the tree similar to the array by deleting or adding the element in the tree.
Example 1:
    int orig[5] = {10, 20, 25, 30, 40};
    ref_tree = 10, 20, 25, 30, 35, 40, 50

    Delete from tree: 35, 50

Example 2:
    int orig[6] = {10, 20, 25, 30, 35, 40};
    ref_tree = 10, 20, 25, 35

    Add to tree : 30, 40

NOTE: If the length of arrays and tree node count are the same, then assume both are having same element list.
I tried something like this:
'''
if (array_len < node_count) {
    /*Extra element in ref array */
    while(tree_node) {
        //iterate through all nodes of tree
        bool found = false;
        for (int i=0; i<array_len; i++) {
            if (tree_node->data == orig[i]) {
                found = true;
                break;
            }
        }
        if (found == false) {
            //Data is extra in tree, so delete node to make it similar.
        }
    }

} else {
    /*Missing element from tree */
    for (i=0; i<orig_len; i++) {
        /* Calling tree find api if element is available or not*/
        if (find(orig[i], ref_tree) == false) {
            //Element is Missing
            //add that node from tree to make it similar
        }
    }
}
'''

I want to optimize the code here.

Instead of doing a find operation every time while finding missing elements, is there anything that can be done to make the code more efficient?
Looping for multiple times in case of finding extra elements in the tree, is it possible to merge into a single loop and optimize the code from any other way?
Instead of having 'if-else', is it possible to have a common logic that can handle to get the element to be added/deleted from the tree?
Comment: does your code work correctly?  does your code compile cleanly?  If both of those questions have an answer of `yes` then strongly suggest moving this question to `code review` as that is what that web page(s) is for
Comment: Why not just convert the array to a tree. That way you don't need to compare array and tree. And you don't need an AVL tree implementation. Building a tree from an array yields a balanced tree without the need for rotations.
Comment: @user3386109 that depends on how you build the tree given an already sorted input . The naive approach results in essentially a linked list.
Comment: @user3386109,  Here array is an input which I can't modify and tree I formed is for my use inside module. This array may contain 10 millions of elements sometimes. So, I created AVL tree to make find operation quickly.  So linked-list will not be efficient in this case.
Comment: @PDe It was Shawn that was talking about a linked list, not me. Given an array, you can build a perfectly balanced BST faster than you can compare the array to the existing tree. So there's no point in trying to compare the array to the existing tree. Just build a new tree.
Comment: @user3386109 - if I already have 50k elements in array and tree as well and now if 2 or 3 new elements are added into the array.. so it will be costly operation deleting 50k nodes and then add again 50k + 2 nodes.
Comment: @Shawn Array may contain 10 millions of elements sometimes. So, I created AVL tree to make find operation quickly in my module .. So linked-list will not be efficient in this case
Comment: @PDe If you know the 2 or 3 elements that are new without comparing the array to the tree, then you are absolutely right. Just add the elements to the tree. But it's  unclear whether you have that information. The question seems like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. You've described your proposed solution, but haven't actually described the underlying problem that led you to that solution.
Answer: You seem to be making the problem harder than it needs to be, at least conceptually.  You have a sorted array, and you have a binary search tree.  An in-order traversal of the tree will visit the nodes in order of the values they hold.  By matching the the node values traversed to the elements of your list, you can detect which values are missing from the tree and which are extra -- even in the presence of multiple elements and / or multiple nodes having the same value, and even if there are the same number of nodes as values.  At each node:

if we've exhausted the array, then the node is extra, else
if the current node has the expected value, then it's a match.  We'll expect the next node to have the next value.
if the current node has a value less than expected then it's extra.  We'll expect the next node to have the current expected value.
else the current node has a value greater than expected, so a node with the expected value must have been deleted.  We'll then try again with the same node, expecting it to have the next value.

After the traversal is complete, any list elements after the last one matched or considered correspond to deleted nodes.
That's enough to identify the differences, but that approach does not afford updating the tree as you go, because mutating the tree affects traversal order.  You therefore have (at least) these alternatives:

when you detect a tree mutation, correct it immediately and then restart from the beginning, or
make a list of the mutations as you go, and fix them all after completing the traversal, or, of course,
after the traversal, just build a new tree from your array.


Delete/create nodes programmatically

Question: I created a custom module that uses the Taleo Web API to get data from the external Taleo database and make nodes from this data. This works great.
But now I want to run this update script every night... The script works great whem I logged in into Drupal.
What would be the safest way to allow deleting and adding nodes programmatically when logged out?
<code>function taleo_menu() {
  $items['taleo-update'] = array(
    'title' => 'Taleo Update page',
    'description' => 'Taleo Update page',
    'page callback' => '_taleo_update',
    'access arguments' => array('view content'),
        'type' => MENU_NORMAL_ITEM,
  );
    return $items;
}

function _taleo_insert($jobs) {
    foreach ($jobs as $job_object) {

        $node = new stdClass();
        $node->type = 'job';
        $node->title    = $job_object->title;
        $node->language = LANGUAGE_NONE;

        node_object_prepare($node);
        $node = node_submit($node); // Prepare node for a submit
        node_save($node); // After this call we'll get a nid
    }

    drupal_set_message(t('Added %count jobs.', array('%count' => count($jobs))));
    return array();
}
</code>
Comment: Please provide code of hook_menu() function of your module
Comment: The hook_menu won't be the problem, my module adds new nodes programmatically, that's the problem I guess.
Answer: If you are looking for the safest way, I would say your current approach is not how most of us get things done in Drupal.
Basically, you can make use of a hook that wakes up your module, check last run's status and if suitable, start its next run.
Check out hook_cron. You can check last run status easily from a variable_get (you need to set the value first using variable_set). Cron runs anonymously regardless of a specific page call. Even if the cron runs frequently, you can use some condition to check last run timestamp and compare it to current system time. If it has exceeded the interval (1 day), you can now run the "create nodes" function.
If nodes are saved correctly, you will see a $node->nid set. use that as a condition and if all given jobs are done, you can set the last run variable to the current time.
Comment: Ayesh K is right , you can write your function in hook_cron, and set your cron to run 'every night'. You can set cron job at admin/config/system/cron
Comment: Thanks, I will take a look at this! Ayesh, what do you mean with 'your current approach is not how we do things in Drupal'? Any suggestions for improvement for doing this?
Comment: Ayesh, you mean it's unusual to use hook_menu for this kind of task instead of hook_cron? I just did it to test the module. Seems that hook_cron is doing what I want it to do, I'm testing right now!

Delete/create nodes programmatically


Exclude certain paths for bootsnap loading

Question: https://github.com/Shopify/bootsnap would load all ruby files at launch. However I have certain need to not load a specific directory. Is there a configuration for doing that? Or is there a simple monkey patch to achieve the same thing?
Comment: I, too, would love this as we're seeing some intermittent issues related to `bootsnap` loading translation files from the `faker` gem when running tests in parallel on a 24-thread Mac Pro. I've created an issue for this on `bootsnap`, that will hopefully lead to an exclusion option for the gem: https://github.com/Shopify/bootsnap/issues/350
Answer: Looking at the source of the gem, I've not been able to see any configuration to exclude certain paths from being cached.
However, I think you can define your paths which needs to be excluded in the following file (monkey patching):
https://github.com/Shopify/bootsnap/blob/master/lib/bootsnap/load_path_cache/path_scanner.rb#L39
<code>Dir.glob(path + ALL_FILES).each do |absolute_path|
  next if contains_bundle_path && absolute_path.start_with?(BUNDLE_PATH)
  relative_path = absolute_path.slice(relative_slice)

  // Here match your path with the relative path and skip the loop iteration

  if File.directory?(absolute_path)
    dirs << relative_path
  elsif REQUIRABLE_EXTENSIONS.include?(File.extname(relative_path))
    requirables << relative_path
  end
end
</code>


Sketching an arbitrary ellipse from its parametric equation

Question: I was solving a question, in which I was asked to solve the following system of differential equations:
$$
\dot x = 3x + 2y, \quad \dot y = -5x - 3y.
$$
I got the general solution in $\mathbb R^2$ to be
$$
\begin{pmatrix} x \\ y \end{pmatrix} = \begin{pmatrix} C & D \\ -\frac32 C + \frac12 D & -\frac12 C - \frac 32 D \end{pmatrix}\begin{pmatrix} \cos t \\ \sin t \end{pmatrix}, \quad C,D\in \mathbb R.
$$
Now, I want to sketch the phase portrait of this solution (apparently, as we change $C$ and $D$, only the scale of the ellipse changes, not its orientation or ratio between major and minor axes). My question is, how do I determine the orientation of axis lengths of this ellipse (in terms of $C$ and $D$)? Given an arbitrary ellipse of the form
$$
\begin{pmatrix} C & D \\ E & F \end{pmatrix}\begin{pmatrix} \cos t \\ \sin t \end{pmatrix},
$$
how would one sketch it?
Answer: $$\dot x = 3x + 2y, \quad \dot y = -5x - 3y.$$
$$2\dot x+\dot y = x + y, \quad \dot y+\dot x = -2x - y.$$
Substitute $u=x+y$ and $v=2x+y$:
$$\dot v= u ,\quad \dot u=-v$$
$$\implies \dfrac {dv}{du}=-\dfrac u v$$
$$v^2+u^2=C$$
$$(x+y)^2+(2x+y)^2=C$$
Answer: late to the party. Given
$$
\left(
\begin{array}{c}
\dot x \\
\dot y
\end{array}
\right) =
\left(
\begin{array}{cc}
p & q \\
r&s
\end{array}
\right)
\left(
\begin{array}{c}
 x \\
 y
\end{array}
\right),
$$
we can have a constant quadratic form (other than at the origin)  only when the trace or the determinant of the coefficient matrix is zero.  Zero determinant  means a line.   More interesting is trace zero.
When
$$
\left(
\begin{array}{c}
\dot x \\
\dot y
\end{array}
\right) =
\left(
\begin{array}{cc}
p & q \\
r&-p
\end{array}
\right)
\left(
\begin{array}{c}
 x \\
 y
\end{array}
\right)
$$
we can readily calculate that
$$ \frac{d}{dt} \; \left( rx^2 - 2pxy - q y^2 \right)   = 0 $$
The type of conic section we see is determined by the discriminant
$$  \Delta = 4p^2 + 4qr  ,$$  as well as the sign of the constant $C$ in $ rx^2 - 2pxy - q y^2   = C $
Answer: If you set $\vec\alpha=(C,E)$ and $\vec\beta=(D,F)$, then the parametric equation can be written as $\vec p(t)=\vec\alpha\cos t+\vec\beta\sin t$ and vectors $\vec\alpha$, $\vec\beta$ are two conjugate semi-diameters.
But conjugate semidiameters are related to semi-axes $a$, $b$ of the ellipse by Apollonius' formulas:
$$
a^2+b^2=|\vec\alpha|^2+|\vec\beta|^2,
\quad
ab=|\vec\alpha\times\vec\beta|
$$
and can thus be computed. To find the directions of the axes one could follow a nice geometric construction, or find the values of $t$ for which the derivative of $|\vec p(t)|^2$ vanishes, obtaining:
$$
\tan 2t={2\vec\alpha\cdot\vec\beta
\over|\vec\alpha|^2-|\vec\beta|^2}.
$$
Answer: First write $\cos t$ and $\sin t$ in terms of $x$ and $y$:
$$
\begin{pmatrix} x \\ y\end{pmatrix}=\begin{pmatrix} C & D \\ E & F \end{pmatrix}\begin{pmatrix} \cos t \\ \sin t \end{pmatrix}\\
\begin{pmatrix} \cos t \\ \sin t \end{pmatrix}=\begin{pmatrix} C & D \\ E & F \end{pmatrix}^{-1}\begin{pmatrix} x \\ y\end{pmatrix}
$$
The inverse is a $2\times2$ matrix, say $\begin{pmatrix} \alpha & \beta \\ \gamma & \delta \end{pmatrix}$.
You also know $\cos^2 t+\sin^2t=1$. So $$(\alpha x+\beta y)^2+(\gamma x+\delta y)^2=1$$
You can group the terms together, then use this answer to get the orientation, and something like this answer to find the length of the semiaxes.


Power set of any set.

Question: Question:

Let $A$ be any set. Let $\mathbb{P}(A)$ be the power set of $A$. Then which one is true?

$\mathbb{P}(A)=\emptyset$ for some $A$.

$\mathbb{P}(A)$ is finite for some $A$.

$\mathbb{P}(A)$ is countable for some $A$.

$\mathbb{P}(A)$ is uncountable for some $A$.

Now 1. is not true, since if $A=\emptyset$, $\mathbb{P}(A)=\{\emptyset\}\neq \emptyset$. 3. is not true since let $A=\mathbb{N}$, then $\mathbb{P}(A)=2^\mathbb{N}$ is uncountable. So answer will be 2 and 4.
But when I saw the answer book, it says answer is (2,4) or (2,3,4). That or is for answer is not decided yet.
My question is why is their doubt!!! The answer should be $(2,4)$.... this is obvious, isn't? I am very bad at set theoritic arguments. Can someone clarify it?
Comment: Your argument about 3. is not valid since it says "for some $A$".
Comment: By $\Phi$, I assumed you meant the null set. I applied a typesetting edit: the null set has $\LaTeX$ command \emptyset
Comment: @KajHansen thanks. That was the notation in the question. Thanks for the edit!!!
Comment: Here's another similar question - https://math.stackexchange.com/questions/77656/is-the-power-set-of-the-natural-numbers-countable?rq=1
Comment: @BAI thanks I understood that.
Answer: A countable set is a set which cardinality is at most $\aleph_0$, the cardinal of $\mathbb{N}$. In particular, any finite set is countable. So, since $2$ is true, so is $3$: taking a finite set $A$, $\mathcal{P}(A)$ is finite (hence $2$ is true) and thus countable (hence $3$ is true).
Your argument for 1 is a bit off. The power set of $\emptyset$ is $\{\emptyset\}$, not $\{\{\emptyset\}\}$.
Edit:
As R. Suwalski pointed out, countable may mean of cardinality $\aleph_0$. So if that's the case, then no there is no $A$ such that $\text{card}{\mathcal{P}(A)}=\aleph_0$. Indeed, by contradiction, we have according to Cantor's theorem, $\text{card}A<\text{card}\mathcal{P}(A)=\aleph_0$. Thus $A$ is finite and hence so is $\mathcal{P}(A)$, contradiction.
Comment: Some people define a set to be countable if it has the same cardinality as natural numbers and shorten "countable or finite" to "at most countable". No power set is countable - from Cantor's theorem we conclude that $|P(A)| > |A|$, so if $A$ is infinite countable, then $P(A)$ is strictly larger; if $A$ is finite, then $P(A)$ is finite too.
Comment: "I guess that's what you're working at, right? What book are you using?"... not really @Scientifica this was just a competitive exam question, **ZFC** is included in the syllabus, as far I know.
Comment: I am saying I wrote $\{\{\emptyset\}\}$ mistakenly.
Comment: Ah ok I understand.
Comment: thanks, that is a good argument(got out of my mind, ha ha). But I am really confused what @Deusovi said in the second paragraph.
Comment: I knowledge about models is very limited so I can't explain what he meant because I fear I may say something wrong. But what I'm sure of is that in the context of **ZFC** theory (I guess that's what you're working at, right? What book are you using?) you can't have a model that involve sets with countably infinite power sets as I showed in a comment to Deusovi's answer. A model for **ZFC** theory is a structure that satisfies the axioms of **ZFC**.
Comment: @R.Suwalski Ah I see. Ok I'll edit it.
Answer: Assuming countable means "countably infinite" (so finite sets are not considered countable), 3 is false. If $A$ is finite, then $\mathbb{P}(A)$ is finite.
If $A$ is infinite it contains a countably infinite subset $B$ (mild form of choice used here). And then $2^{\mathbb{N}} = |\mathbb{P}(B)| \ge |\mathbb{P}(A)|$ so that $\mathbb{P}(A)$ is uncountable. So a power set cannot be countable.
Answer: There are two conventions on the meaning of the word "countable" that lead to different answers in the third case.
Some use "countable" as an adjective that refers specifically to sets with the same cardinality as the natural numbers. With this usage, statement 3 would be false, since no set has a power set with the same cardinality as the natural number.
Some use "countable" as an adjective that refers to sets whose cardinality is less than or equal to the natural numbers. With this usage, statement 3 would be true, since every finite set is countable, and any finite set has finite power set.

I think originally, the word "countable" was used for the second convention; the intuition behind the name is that they are sets you can count with natural numbers. If one wanted to specifically refer to the sets where you had to exhaust the natural numbers, one would use the phrase "countably infinite".
And in some contexts, you really do want an adjective that covers both the case of finite sets and sets with the same cardinality as the naturals.
But some contexts speak only about infinite sets, so by both conventions "countable" uniquely refers to sets with the same cardinality as the naturals.
In other contexts, the gulf between finite and infinite cardinals is that having a word that lumps together the cardinality of the natural numbers with finite cardinalities is not useful. So the term "countable" is only ever used in the phrase "countably infinite", and the latter term eventually got shortened to simply "countable".
Answer: Your answer to 1 is a bit off. It shows that the empty set cannot be such an A, but it does not prove there is no A. For that, suppose there is an A such that 2^A is empty. The empty set is a subset of all sets, so it is a subset of A, so it is a member of 2^A, so 2^A is not empty, a contradiction. Or more briefly: the empty set is a member of all powersets, so no powerset can be the empty set.
Your argument against 3 is a bit off, in a similar way. The proposition is that the statement is true for SOME A. You then say: look it is not true for this particular A. But, so what, there might be some other A for which it IS true! If the proposition had been for ALL A, then yes, one counterexample is enough. But here it only claims for SOME (and just one will do).
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: OPs proof is enough if you add the observation that $\emptyset \subset A$ for any set $A$ and there fore $|P(A)| \geq |P(\emptyset)| > |\emptyset|$.

Power set of any set.


This equation returns NaN only when certain values are passed

Question: So for my C# programming class I have to calculate the number of months it would take to pay off a credit card balance given the balance, monthly payment and APR.
Here is the formula we were given to interpret:

Here is the C# version I made:
months = (double)decimal.Divide(-1, 30) * (
  Math.Log(1 + (double)(balance / payment) * (1 - Math.Pow((1 + (apr / 365)), 30)))
    / Math.Log(1 + (apr / 365))
);

It works for every example I've tried, except one, which is specified in a question I need to have the answer for:

How many months will it take Alice to pay off a $7,500.00 balance if the
  APR value is 0.22 and she pays $125.00 per month?

The output of which looks like:
Enter the credit card balance (example: 10000.00)
7500
Enter the monthly payment amount (example: 250.00)
125
Enter the annual percentage rate (example: 0.15)
0.22
It will take NaN months to pay off the balance.
Goodbye! Press any key to exit.

In my investigations, I plugged the formula into WolframAlpha and it returns two different values (http://bit.ly/1LQSsEx) perhaps this has something to do with it, but I am new to C# and have reached the end of my knowledge.
What is happening here, and how do I fix it?
Comment: That line of c# isn't very readable. I'd break it up. It will help you debug. [Code should be written for humans to read first and computers to read second](http://stackoverflow.com/a/522907/542251)
Comment: I'm, guessing that if wolfram gives you a complex number as a result, that it means, that there is no real solution for your equation probably log is out of its domain, or something like that... so that would be the reason for `NaN`
Comment: Consider changing your equiatation into an expression, e.g.: ``Expression> months = (b, p, i) => (-1 / 30d) * (
                Math.Log(1 + (b / p) * (1 - Math.Pow(1 + i, 30)))
                / Math.Log(1 + i)
        );``
Answer: the result of the following code yields a negative number.
1 + (double)(7500 / 125) * (1 - Math.Pow((1 + (0.22 / 365)), 30))

Math.Log for obvious reasons only works with numbers > 0
that's what giving you a NaN.
Comment: Ah! Thank you. I wrapped it in Math.Abs and now I am getting the output like I should. Hopefully, this isn't considered a terrible solution! Should I wrap the other Math.Log function with Abs as well? Edit: Actually nevermind, don't see why I'd need to, as the input shouldn't be less than zero in any case.


Fedora 17 transparent Ethernet Bridge not forwarding IP traffic

Question: I am running on Fedora 17 with the latest ebtables and have been trying to setup a transparent bridge - using the following script, I send a ping through the bridged host and only see the requests on the bridge (among other traffic from eth0), BUT, arps and arp replies are making it through.
My host is setup - Client 192.168.1.10 <-- eth0  --> eth2 192.168.1.20
Ethernet script:
<code>#!/bin/sh
brctl addbr br0;
brctl stp br0 off;
brctl addif br0 eth0;
brctl addif br0 eth2;
(ifdown eth0 1>/dev/null 2>&1;);
(ifdown eth2 1>/dev/null 2>&1;);
ifconfig eth0 0.0.0.0 up;
ifconfig eth2 0.0.0.0 up;
echo "1" > /proc/sys/net/ipv4/ip_forward;
ebtables -P INPUT ACCEPT
ebtables -P FORWARD ACCEPT
ebtables -P OUTPUT ACCEPT
ebtables -A FORWARD -p ipv4 -j ACCEPT
ebtables -A FORWARD -p arp -j ACCEPT
</code>
Any assistance would be great! Edit  - also tried ACCEPT for ebtable policy which seems to be working better
Comment: Does it work when ebtables is configured to accept all traffic? Are there any iptables rules? (iptables shouldn't be in the path, but I've seen it affect traffic before.)
Comment: ebtables does not work when set to accept all traffic.  I think there might be some sort of routing logic issue if I have a management interface installed (which has an IP on the same subnet)
Answer: I would be looking at those ebtables entries first. I haven't heard of ebtables before but to me it looks like you're dropping everything. Are you really trying to build a bridging firewall? If not, you don't need the firewall rules.
Comment: Yes I am.  One of the things I noticed was that if I had a management interface installed, the kernel was trying to be "smart" and routing everything incorrectly... disabled the management NIC so packets go through the correct interface.  Secondly, Network Manager  disabled that nightmare.


How can I edit puppet .pp files with Eclipse & DLTK

Question: The puppet editor tips page seems to suggest that using eclipse & dltk (presumably the ruby tools) will assist with editing .pp files.
http://projects.puppetlabs.com/projects/1/wiki/Editor_Tips
I can't see any difference or get syntax highlighting with DLTK 1.0 and the ruby plugins installed. Is there something I'm missing or eclipse configuration I need to set for it to start doing syntax highlighting and validation of my puppet model?
Answer: Before the above will work, I had to create a new eclipse ruby project and add a ruby interpreter pointing at /usr/bin/ruby (the default install location of ruby on Mac OS X).
After that was done, it was possible to open and highlight .pp files in the Ruby editor and get syntax highlighting working.
It also helps to link the .pp file type with the ruby editor in the General > Editors > File Associations section of the Eclipse preferences.
Answer: Also checkout the project https://github.com/cloudsmith/geppetto which contains a Puppet .pp parser/editor with syntax coloring, error markers, etc. and with features that makes it easy to work with puppet modules.
Geppetto is available as a ready to use download, or as features installable into Eclipse.
Comment: geppetto is definitely the way to go.


Ancora de site no iframe mexe a página principal

Question: Ola, tenho um site onde tenho uma linha do tempo que montei, quando clico em cada ano da linha do tempo, o iframe abaixo dele mexe direcionando para um texto específico na página, o problema é que exclusivamente no google chrome, quando clico em um ano, a ancora puxa o iframe para a posição certa, porem a ancora tambem faz a página principal descer até a posição do iframe, teria como concertar isso?
Toda a animação está em javascript, e tudo relacionado a ancora esta em html e css apenas (assim como a ancora tambem está em html)
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Time Line</title>

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link
        href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;0,800;1,300;1,400;1,600;1,700;1,800&display=swap"
        rel="stylesheet">

    <map name="map">
        <area shape="circle" coords="20,20,20" href="timeHistory.html#1935" onclick="yearSelect(0)" target="yearHistory" />
        <area shape="circle" coords="140,20,20" href="timeHistory.html#1940" onclick="yearSelect(1)" target="yearHistory" />
        <area shape="circle" coords="263,20,20" href="timeHistory.html#1950" onclick="yearSelect(2)" target="yearHistory" />
        <area shape="circle" coords="385,20,20" href="timeHistory.html#1960" onclick="yearSelect(3)" target="yearHistory" />
        <area shape="circle" coords="506,20,20" href="timeHistory.html#1970" onclick="yearSelect(4)" target="yearHistory" />
        <area shape="circle" coords="627,20,20" href="timeHistory.html#1980" onclick="yearSelect(5)" target="yearHistory" />
        <area shape="circle" coords="749,20,20" href="timeHistory.html#1990" onclick="yearSelect(6)" target="yearHistory" />
        <area shape="circle" coords="870,20,20" href="timeHistory.html#2000" onclick="yearSelect(7)" target="yearHistory" />
        <area shape="circle" coords="992,20,20" href="timeHistory.html#2010" onclick="yearSelect(8)" target="yearHistory" />
        <area shape="circle" coords="1113,20,20" href="timeHistory.html#2020" onclick="yearSelect(9)" target="yearHistory" />
    </map>

1935

1940

1950

1960

1970

1980

1990

2000

2010

2020

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Iframe</title>

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link
        href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;0,800;1,300;1,400;1,600;1,700;1,800&display=swap"
        rel="stylesheet">

1935

1940

1950

1960

1970

1980

1990

2000

2010

2020

Answer: Para todos que tiverem o mesmo problema, eu apenas acrescentei na tag do iframe o sandbox="allow-top-navigation"


Trouble reading data from USB device using Python

Question: I am using PyUSB library to read data from my USB mouse in windows. I was able to run the code in a UBUNTU virtual machine, but I can't replicate the same in windows. Can someone tell me what am I doing wrong? Following is the code and the error it throws :
import usb.core
import usb.util

# decimal vendor and product values
dev = usb.core.find(idVendor=1133, idProduct=49278)
if dev is None :
    raise ValueError('Device is not found')

print(dev)

# first endpoint
interface = 0
endpoint = dev[0][(0,0)][0]
# if the OS kernel already claimed the device, which is most likely true

if dev.is_kernel_driver_active(interface) is True:
  # tell the kernel to detach
  dev.detach_kernel_driver(interface)
  # claim the device
  usb.util.claim_interface(dev, interface)
collected = 0
attempts = 50
while collected < attempts :
    try:
        data = dev.read(endpoint.bEndpointAddress,endpoint.wMaxPacketSize)
        collected += 1
        print(data)
    except usb.core.USBError as e:
        data = None
        if e.args == ('Operation timed out',):
            continue
# release the device
usb.util.release_interface(dev, interface)
# reattach the device to the OS kernel
dev.attach_kernel_driver(interface)

Traceback (most recent call last):
  File "c:\BCD\i360\python\usb_reader.py", line 27, in <module>
    if dev.is_kernel_driver_active(interface) is True:
  File "C:\Python\Python38\lib\site-packages\usb\core.py", line 1107, in is_kernel_driver_active
    self._ctx.managed_open()
  File "C:\Python\Python38\lib\site-packages\usb\core.py", line 113, in wrapper
    return f(self, *args, **kwargs)
  File "C:\Python\Python38\lib\site-packages\usb\core.py", line 131, in managed_open
    self.handle = self.backend.open_device(self.dev)
  File "C:\Python\Python38\lib\site-packages\usb\backend\libusb1.py", line 804, in open_device
    return _DeviceHandle(dev)
  File "C:\Python\Python38\lib\site-packages\usb\backend\libusb1.py", line 652, in __init__
    _check(_lib.libusb_open(self.devid, byref(self.handle)))
  File "C:\Python\Python38\lib\site-packages\usb\backend\libusb1.py", line 600, in _check
    raise NotImplementedError(_strerror(ret))
NotImplementedError: Operation not supported or unimplemented on this platform

Comment: Handle the exception!
Answer: The error says exactly what's wrong: You're using a function that makes no sense on your operating system (Windows).
So, don't do that? Either, if you know this is something only running on Windows, remove the check, or better, try:-handle the exception.
Answer: dev.is_kernel_driver_active(interface) is not supported in Windows
Comment: Can you suggest something that is supported in Windows. This is my first time working with PyUSB. WOuld really appreciate if you could help me with it


Custom PHP code as a Panels selection rule

Question: Panels allows selection rules to be created with custom PHP code (disclaimer: I know this approach is insecure and should be avoided).
When adding PHP code as a selection rule, the helpful description states:

Access will be granted if the following PHP code returns TRUE. Do not
  include . Note that executing incorrect PHP-code can break
  your Drupal site. All contexts will be available in the $contexts
  variable.

I made a function in a custom module to use for the selection rule:
function mymodule_selection_rule_is_location_set() {
  global $user;
  $user_fields = user_load($user->uid);
  if (isset($user_fields->field_acc_location['und']['0']['lat'])) {
    $location = $user_fields->field_acc_location['und']['0']['lat'];
  }
  if (empty($location)) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

However, when I set the selection rule as shown below, the selection rule is not triggered even when there is a value for $location and the function returns TRUE (confirmed with devel module).
Evaluates false as a selection rule even when the function returns TRUE
mymodule_selection_rule_is_location_set()

To get it to work, I had to write the selection rule like this:
Evaluates correctly
if (mymodule_selection_rule_is_location_set()) {
  return TRUE;
}

My question is why do I have to write it like the latter rather than the former?
Comment: The first one is missing a `;`, could that be the problem?
Comment: Nope, it evaluates incorrectly whether there is a `;` or not.
Answer: I think the calling function which executes your PHP code would expect the RETURN true/false statement. Thus, you would need return to the calling function as returned by the called function.
return mymodule_selection_rule_is_location_set();

If you don't have return, the calling function would expect NULL and it would execute as FALSE always regardless of what is returned by the called function.


Can't create alias name for has_many :through

Question: This is my Migration code:
1.User
<code>    create_table :users do |t|
      t.string :name
      t.string :password
      t.string  :department

      t.timestamps
    end
</code>
2.Ploy
<code>    create_table :ploys do |t|
      t.string :name
      t.string :state
      t.string :description
      t.string :location
      t.float  :spend

      t.references :creator, index: true, class_name: "User"

      t.timestamps
    end
</code>
3.participants
<code>   def change
    create_table :participants do |t|
      t.belongs_to :ploy
      t.belongs_to :user

      t.timestamps
    end
</code>
This is my Model code:
<code>class User < ActiveRecord::Base
  has_one :create_ploys, class_name: "Ploy"

  has_many :participants
  has_many :ploys, through: :participants, source: :join_ploys
end

class Ploy < ActiveRecord::Base
  belongs_to :creator, class_name: "User"

  has_many :participants
  has_many :users, through: :participants, source: "joiners"
end

class Participant < ActiveRecord::Base
  belongs_to :user
  belongs_to :ploy
end
</code>
When i call user.join_ploys, but give me a error: NoMethodError: undefined method `join_ploys'
So i think maybe something is wrong about :source, But i don't know how to do.
Answer: so where are you defining a model or association for joiners and join_ploys? You can't just create a :source without defining what it is. Check out this SO: Need help to understand :source option of has_one/has_many through of Rails


What are some interesting examples of stochastic preferences for random variables?

Question: Let $X$ and $Y$ be stochastic variables. We say that $X$ is preferred over $Y$ when $X \succeq Y$. There are many types of preference relations. For instance, we may have:

$X \succeq Y$ iff $E(X) \geq E(Y)$. Here, $E(X)$ is the expectation of $X$.
Let $u^{X}_{\alpha} := \sup \{ t \in \mathbb{R} \,  | \,  P(X \leq t) \leq \alpha \} $. Furthermore, let $U(X) := u^{X}_{\alpha}$ Then we could define $X \succeq Y$ iff $U(X) \geq U(Y)$.
Define $(XY)_{\alpha} := \{ \alpha \, | \, F_{X}^{-1} (\alpha) \geq F_{Y}^{-1} (\alpha) \} $. Then $X \succeq Y$ iff $\lambda((XY)_{\alpha}) \geq \frac{1}{2}$. Here, $\lambda$ denotes the Lebesgue measure.

I think all of these preference relations each in their own way meaningfully compare the stochastic variables $X$ and $Y$ with one another. I'm wondering whether there are other important or interesting ways to compare stochastic variables. Can you give me a good example?
Answer: Well, this is a big area.  One thing to consider is what properties you want in your preference relation, must it be complete, should it be transitive, and so forth. That aside, here are some examples, drawn from my area of familiarity, which is economics and finance.

Variance: $X \succeq Y \ \rm{if} \ E(X -E(X))^2 \leq E(Y-E(Y))^2$
more generally, choose a utility function $u()$, and $X \succeq Y \ \rm{if}\ E(u(X))\geq E(u(Y)),$ where $u()$ is increasing, continuous, and concave. For example, for positive random variables you might choose $\ln(x)$ as your utility function.
First Order Stochastic Dominance: $X \succeq Y \ \rm{if} \ F(z)\leq G(z)$ for all $z$, where $F$ is the Cumulative Distribution Function of $X$ and $G$ is the CDF of $Y$.  $Y$ has more weight in the tails, and thus is riskier.
Second Order Stochastic Dominance, $X \succeq Y \ \rm{if} \ \int_0^z[F(z)-G(z)]dz\geq 0.$

There is also third order stochastic dominance.
Some of these definitions are equivalent, for example second order stochastic dominance holds if and only if $E(u(x))\geq E(u(y))$ for every increasing concave utility function. Ingersoll, Theory of Financial Decision Making, is good on this.
          All this is very heavily centered on expected utility, but of course there are alternatives, and papers by Mark Machina have explored the issue.


Vscode API: read clipboard text content

Question: I'm currently trying to write an extension for Visual Studio Code, and I can't manage to understand how to read the clipboard content.
The VSCode API specifies this method:
readText ():Thenable<String>
Following what I read about Thenable, I should be able to get the clipboard's text like that:
var clipboard_content = vscode.env.clipboard.readText().then((text)=>text);

But all I manage to get is a Promise { pending } object.
What I would like to get is the clipboard content as a string
Answer: Basics mistake.
Because you use promises (async)  and want async/await (linear) functionality.
It should be (promises, async code):
vscode.env.clipboard.readText().then((text)=>{
    clipboard_content = text;
    /* code */
});

or (sequential code)
let clipboard_content = await vscode.env.clipboard.readText();
/* code */

PS.: In JS, you should use camelCase instead of snake_case when naming variables and functions. This is one of the recommendations of JavaScript Standard Style
Comment: Using `await`, I think, doesn't make your code `synchronous` but `sequential`. I would also suggest to replace 'linear' with 'sequential' as a better term to describe sequential events. :-)

Vscode API: read clipboard text content


JS Como autopreencher um input com JavaScript?

Question: Olá
Preciso fazer um botão que ao clicar ele preenche de forma automática os campos de input.
HTML
<button type="button" id="botao">Auto</button>
<input type="text" id="nome">
<input type="text" id="sobrenome">

JS
$(document).ready(function() {
   var nome = "Joãozinho";
   var sobrenome = "Fulano";

   $("#botao").click(function(){
      $("#nome").val(nome);
      $("#sobrenome").val(sobrenome);
   });
});

Mas ao clicar no button nada ocorre, o está errado no código?
Comment: O código funciona. Confirme se tem o jquery corretamente adicionado ao à página.
Comment: Realmente faltou jquery, muito obrigado pela ajuda :)
Answer: Codigo está correto, veja funcionando aqui

$(document).ready(function() {
   var nome = "Joãozinho";
   var sobrenome = "Fulano";

   $("#botao").click(function(){
      $("#nome").val(nome);
      $("#sobrenome").val(sobrenome);
   });
});

<button type="button" id="botao">Auto</button>
<input type="text" id="nome">
<input type="text" id="sobrenome">


Generate 3 random numbers such that the sum is below a number, or within a range

Question: I'm writing a program for fun which generates random colours for text.
(If you're curious: https://github.com/Arunscape/acat)
So, I have 3 variables $r, g$, and $b$ , each of which can be any integer $\in [0, 256)$
I figure that if I want dark text on a light background, or light text on a dark background, I should generate $r,g,b$ such that their sum is within a range, either
$r + g + b \leq 255 \quad r,g,b \in [0, 255]$ for dark text
or
$r + g + b \geq 255 \quad r,g,b \in [0, 255]$ for light text
Here is my thought process so far for approaches I could take:

generate $r$, let's say we get $r=100$
g = random_num_in_range($0, 256-r)$, let's say we get $g=100$
b = random_num_in_range(0, 256-r-g), let's say we get $b=50$

In this example, I would get a dark-ish yellow colour for use with a light background
However, because r is always the first number to be generated, would this algorithm have some sort of bias, or would the generated colours be random?
If this algorithm does work, can I make it more efficient? I will be generating lots of colours, so the less CPU cycles I can waste, the better.
Another approach I'm thinking I could take is, instead of generating 3 random numbers for each colour, is it possible to say, generate a number between 0 and $256^3 - 1$ and then map the number to r,g,b values. (or rather I would generate numbers in the range, $[0,0x7FFFFF]$ for dark values and $[0x800000, 0xFFFFFF]$ for lighter values.
Now that I think of it, that's kind of close to hex colour codes, except that for hex colour codes, the 2 leftmost digits are r, the 2 middle are g, and the 2 left ones are for b
Or, is there some other approach that I completely missed that's much better than what I came up with?
Comment: Just randomize also the order of variables when choosing the random numbers to get rid of the bias.
Answer: Your approach will definitely bias $r$ high-it will average $127.5$ and $b$ low.  A simple approach is to generate four numbers, $r,g,b$ in a fixed range and a sum to normalize to.  Multiply each one by $\frac {desired sum}{actual sum}$ and you are there.  Certainly you can generate one random number and split it into four bytes, however the low order bits of a random number are often much less random than the high order bits.
I would be surprised if a simple sum of $r+g+b$ got you a good split of light vs. dark colors.  Note that $255$ is $\frac 13$ of the way up, not $\frac 12$.
Comment: just making sure I understand-- so you're saying generate 4 numbers, say r,g,b, x then multiply each by x/(r+g+b) ?
Comment: Yes, that is correct.


Why won't php_oauth.dll module work on Windows 7?

Question: I am struggeling for days to install OAuth module of PHP to apache, but it simply doesn't want to work. I have tried many combinations, but I just can't get it to work:

XAMPP

XAMPP doesn't include oauth by default. Therefore, I have downloaded the module from PEAR websote, placed it in the ext folder, placed it into php.ini. However, when I try to start apache it says that oauth and PHP are compiled with different APIs!?. I tried with older versions too, but with the same result

Manual Installation of Apache & PHP

I also tried to install both Apache and PHP separately. They install successfully, however apache gives an error when I am trying to start it saying that the php5apach2_2.dll cannot be loaded into server. Some way I managed to fix that and start pache. However, without any error and with php.ini and httpd.conf configured the OAuth module doesn't load and it doesn't appear in phpinfo().

Microsoft IIS

Ultimately I installed IIS and got it to work up until the last problem in the previous trial: won't show up in phpinfo() nor work in PHP scripts.

I got it to work in minutes on Ubuntu Linux on a VM, but it is really a pain to work on a VM as a web developer.
My OS is Windows 7 x64.
The files I used to install:

php_oauth-1.2.3-5.5-ts-vc9-x 86.zip
php_oauth-1.2.2-5.4-ts-vc9-x86.zip
php_oauth-1.2.2-5.3-ts-vc9-x86.zip
php_oauth-1.1.1-dev-5.3-vc9-x86.zip
php-5.3.21.tar.gz
php-5.4.11-nts-Win32-VC9-x86.zip
php-5.3.21-src.zip
php-5.5.0alpha1.tar.bz2
Apache2.2.zip
and many others...

Does anyone have a clue why is this happening ?
Thanks!
Answer: I think the problem that you're running into is that your OAuth DLL's are 32bit (x86) whereas your OS is x64.  I'm dealing with a similar problem, looking for the OAuth DLL that is both x64 and for PHP 5.4.
I did however find a x64 DLL that works for PHP 5.3.  It's available here: http://www.mediafire.com/php-win64-extensions.  Just make sure to get the file named php_oauth-1.2.2-5.3-VC9-x64.zip as the other OAuth DLL is not thread safe (nts).
If you are fine using PHP 5.3 then that DLL should work for you.
Comment: Make sure that you are editing correct php.ini file. Use this to know correct php.ini file:
echo 'php.ini: ', get_cfg_var('cfg_file_path');
Comment: Sorry for the late response. Unfortunately that didn't work either. I have re-installed my OS, installed Apache and PHP manually and sepparately, I added php_oauth.dll from your link in ext and php_ini and it still doesn't show up in phpinfo() nor work in scripts.


How to set up AWS EC2 with apache

Question: I am new to AWS and I have some basic set up questions that I can't find answers to.
1) I have created an EC2 instance using the default Amazon Linux AMI.  How can I install apache?  Then how can I confirm what is installed?
2) I have downloaded the Eclipse toolkit and SDK for the aws products.  I have written some code that can take data and push it into my dynamoDB table.  I can connect and run this successfully from my local PC.  How will this work on the cloud?  What do I need to do to get my application working on my EC2 instance?
Thank you in advance
Answer: 1) The package manager for Linux AMI is yum, the same one you use on RHEL/CentOS. So if you run something like that:
sudo yum install -y httpd php php-pear mysql mysql-server perl php-common php-dba php-pdo php-mysql php-xml php-xmlrpc

This will install all the LAMP stack. Check the console if was installed properly.
To start the service run:
service httpd start

Before doing that make sure to check the config file.
2) Eh the best think to try how it will work it to actually try ? :)
Comment: :-)  Thanks I have been trying.  I'm not sure if I need to put source code on the EC2 instance, or run a jar, and if I need to install anything special to run a java app?  Right now I'm stuck at the first stage - I can connect with WinSCP but I can't place any files on the server because it says access denied.  Thoughts?
Answer: First, log in to your instance
ssh -i key.pem ec2-user@your-instance-address

Then you can install apache
sudo yum install httpd
sudo /etc/init.d/httpd start

You can check what is installed with RPM
rpm -qa

I am not that familiar with dynamodb but it should work the same from the EC2 instance as it does from your desktop.
Comment: Thank you.  It looks like apache is working and I was able to bring up a basic web page.  If I create an S3 bucket/RDS/DynamoDB, will they all sit within my EC2 instance?  I'm confused as to how it all goes together.  Should my databases and applications run *on* my EC2 instance or just in conjunction with
Comment: Brian, S3 and RDS are separate services from EC2, for file storage and data storage respectively. They can definitely work in conjunction with an EC2 server, but they do not reside on it. They are in essence, separate instances of their own.
Comment: Your applications will run on the ec2 machine but can call out to the other AWS services if you need to.  They dont live "on" the ec2.  They are just other things that aws provides.

How to set up AWS EC2 with apache


ERRO: This is application failed to start because it could not find or load the Qt platform plugin "windows"

Question: Estou com erro ao executar um programa que foi criado com o Qt , ele gera o erro da foto! Esse erro é gerado quando executo o exe, todas as dlls indicadas no dependency walker estão na pasta do exe.
Alguém saberia me ajudar?
Obrigado, desde já.
Comment: Oi Jefferson. Você menciona uma foto, mas não a colocou na pergunta.
Answer: À partir da Qt5 você deve ter a seguinte estrutura:
<code>+-+ pasta do aplicativo)
  |-- Aplicativo.exe
  |-- Qt5Core.dll
  |-- Qt5Widgets.dll
  |-- outras dlls dos módulos usados
  +-+ platforms
    |-- qwindows.dll
</code>
A pasta platforms deve estar no mesmo nível do seu .exe, e conter a .dll (no caso do Windows, .so em *nix, etc) referente ao sistema operacional em questão.
No seu caso basta criar a pasta "platforms" junto do aplicativo e colocar a "qwindows.dll" dentro.

PS: Detalhe bem observado, mencionado pelo @LuizVieira:

Sei que a pergunta é sobre Windows. Mas acho que vale lembrar que em *nix não há garantia de funcionar só colocando as bibliotecas compartilhadas na mesma pasta da aplicação. É necessário definir LD_LIBRARY_PATH (tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html) ou usar a diretiva QMAKE_LFLAGS_RPATH no .pro (qt-project.org/doc/qt-4.8/…).