How can I have two voices in one staff in completely different colors, including accidentals, ledger lines and beams?

Question: I cannot get the accidental and beam in voice two to be blue (bars 7-8), and if I include the ledger line override in voice two, it overrides the command in voice one (the ledger lines are black rather than red).
 \repeat volta 2 { << { \voiceOne
\override Staff.LedgerLineSpanner #'color = #darkred
\override NoteHead.color = #darkred
\override Dots.color = #darkred
\override Stem.color = #darkred
\override Beam.color = #(x11-color "DarkRed")
\override Accidental.color = #(x11-color 'DarkRed)

b'4 c4. b8 | a4 b2 | d8 f, e4. e8 | c'8 g fis4 d | a'8 c, b4. g'8 |
 b8 d, cis4. a8 | g'8 cis d[ fis,] e d | \once \override NoteColumn.force-hshift = 1 a cis d2 | }

  \new Voice
  { \voiceTwo
\override Staff.LedgerLineSpanner #'color = #darkblue
\override NoteHead.color = #darkblue
\override Dots.color = #blue
\override Accidental.color = #(x11-color 'darkblue)
\override Stem.color = #darkblue
\override Beam.color = #(x11-color 'darkblue)

 g,4 g2 | fis4 g2 | b4 c2 | a8 g8 fis2 | fis4 g2 | g4 a2 |  cis4 fis,4 a4 | a4 d d, }>>
   \oneVoice  }
}

Here's the whole file. https://drive.google.com/file/d/1wBQTijOKhWw0LN6ZvhTk9AeNR0YKYuC_/view?usp=sharing
Answer: Your code does not correspond to your output: different meter, different key, different clef.  So there is no way I can "adjust" the code to get the desired result.  Also because it has unmatched braces.  Please make it a habit to actually test your examples.
The solution generally here would be to move the Ledger_line_engraver to Voice level and then override the Ledger_line color at Voice level (like you do with the other overrides) rather than at Staff level.
That would work by adding something akin to
\layout {
  \context {
     \Staff
     \remove "Ledger_line_engraver"
  }
  \context {
     \Voice
     \consists "Ledger_line_engraver"
  }
}

in front of your code.  If you are lucky (I could not test it), it will work for your use case.  Note that it may cause ledger lines to be drawn multiple times in which case the resulting color may be inconsistent.
Comment: Thank you for your help.  I've included the entire fiile in the original message which does work.
Comment: @Stephanie do you have this working now or not? As I will post another answer with your code working. But user72086 is totally correct and I've used their code and your code together to get it to work.
Answer: Thanks to @user72086 above this works. Their answer is the more concise as future reference.
\version "2.19.83"
\header {
  title = "J.S. Bach's G Major Sarabande"
  subtitle = ""
  composer = ""
}
colorNotes =
#(define-music-function
     (parser location myColor)
     (color?)
   #{
     \override LedgerLineSpanner.color = #myColor
     \override NoteHead.color = #myColor
     \override Dots.color = #myColor
     \override Stem.color = #myColor
     \override Beam.color = #myColor
     \override Accidental.color = #myColor
   #})

scoreAGlobal = {
  \key g \major
  \numericTimeSignature
  \time 3/4
}

scoreACelloI = \relative c {
  \scoreAGlobal
  \repeat volta 2 {
    << \new Voice \voiceOne {
        \colorNotes #red
        b'4 c4. b8 | a4 b2 | d8 f, e4. e8 |
        c'8 g fis4 d | a'8 c, b4. g'8 |
        b8 d, cis4. a8 | g'8 cis d[ fis,] e d |
        \once \override NoteColumn.force-hshift = 1 a cis d2 |
       } \break
       \\
      \new Voice \voiceTwo {
        \colorNotes #blue
         g,4 g2 | fis4 g2 | b4 c2 |
         a8 g8 fis2 | fis4 g2 | g4 a2 |
         cis4 fis,4 a4 | a4 d d, |
      }
    >>
  }
}

scoreACelloIPart = \new Staff \with {
  instrumentName = "Simplified"
  midiInstrument = "cello"
}
{ \clef bass \scoreACelloI }

\score {
  << \scoreACelloIPart >>
  \layout {
   \context {
     \Staff
     \remove "Ledger_line_engraver"
  }
  \context {
     \Voice
     \consists "Ledger_line_engraver"
  }
}
  \midi {
    \tempo 4=100
  }
}

Comment: Yes, and thank you for laying it all out for me.  I was not able to make it work until you did so.


TypeError listOfNames.split is not a function

Question: I am very new to coding and javascript and working on a project at school. I am not into the answers as it does me know good to be given them.  however, I am stuck at a part of my program and I am unable to go any further in my testing.  wondered if someone could share a little insight as to why I would be getting typeError is not a function on the listOfNames.split(" "); area of my code as provided to me by the console.  It is very frustrating that I cant seem to figure our why.  Thank you in advance.  Here is what I have so far.
     var realNinjas = [
       'Chuck Norris',
       'Jackie Chan',
       'Lucy Liu',
       'Billy Blanks',
       'Michelle Yeoh',
    ]
    var createListOfObjects = function(listOfNames){
    var nameList = listOfNames.split(" ");
    var namesArr = [];
    // var firstName = [];
    // var lastname = [];
       for (var i = 0; i < nameList.length; i++){
           namesArr.push("firstName:" + nameList[0], " " + "lastName:" +            nameList[1]);

   }
         return;
   //OUTPUT: List of strings
}
var ninjaListOfObjects = createListOfObjects(realNinjas);

Answer: split is a method of type String, not of Array
Use split over each string in array within loop

 var realNinjas = [
   'Chuck Norris',
   'Jackie Chan',
   'Lucy Liu',
   'Billy Blanks',
   'Michelle Yeoh',
 ]
 var createListOfObjects = function(listOfNames) {
   var namesArr = [];
   for (var i = 0; i < listOfNames.length; i++) {
     var split = listOfNames[i].split(' ');
     namesArr.push("firstName:" + split[0], " " + "lastName:" + split[1]);
   }
   return namesArr;
 }
 var ninjaListOfObjects = createListOfObjects(realNinjas);
 console.log(ninjaListOfObjects);


Handling MySQL Full Text Special Characters

Question: When using MySQL full text search in boolean mode there are certain characters like + and - that are used as operators. If I do a search for something like "C++" it interprets the + as an operator. What is the best practice for dealing with these special characters?
The current method I am using is to convert all + characters in the data to _plus. It also converts &,@,/ and # characters to a textual representation.
Answer: There's no way to do this in nicely using MySQL's full text search. What you're doing (substituting special characters with a pre-defined string) is the only way to do it.
You may wish to consider using Sphinx Search instead. It apparently supports escaping special characters, and by all reports is significantly faster than the default full text search.
Answer: MySQL is fairly brutal in what tokens it ignores when building its full text indexes.  I'd say that where it encountered the term "C++" it would probably strip out the plus characters, leaving only C, and then ignore that because it's too short.  You could probably configure MySQL to include single-letter words, but it's not optimised for that, and I doubt you could get it to treat the plus characters how you want.
If you have a need for a good internal search engine where you can configure things like this, check out Lucene which has been ported to various languages including PHP (in the Zend framework).
Or if you need this more for 'tagging' than text search then something else may be more appropriate.


Run Time Error '13: Type Mismatch when comparing Dates - EXCEL VBA

Question: I keep getting a "Run Time Error '13': Type Mismatch" error when comparing 2 dates. The code grabs a date from a second Workbook, which in this case I've tried to paste it into a cell to make sure it's a date... Which it is. Then it tries to compare it to a date already on the current Workbook. The pasted date and the other dates are identical formats. I have no idea why it can't compare the 2 dates! I've also tried putting CDate() around each of the components to no avail. Please help.
Sub NewMacro()
Dim CurrentWB As Workbook
Dim ForecastWB As Workbook
Dim strDate As Date

Set CurrentWB = ActiveWorkbook

Application.DisplayAlerts = False
Set ForecastWB = Workbooks.Open("My Other Workbook File Name")
Application.DisplayAlerts = True
strDate = ActiveWorkbook.Worksheets("My Sheet Name").Cells(20, "N").Value

ThisWorkbook.Activate

If Cells(5, 5) = Range("A:A") Then 'TYPE MISMATCH HERE
    Set x = Range("A:A").Find(what:=Cells(5, 5), lookat:=xlWhole)
    Cells(x, 5) = strDate
End If

End Sub

Comment: Wouldn't `Cells(5, 5) = Range("A:A")` be comparing a single cell to a whole column?  `Cells(5, 5) = Range("A1")` works.
Comment: please check for both dates that `IsDate()` is true... there may be the chance that at least one date is treated like a string... please see [THIS](http://stackoverflow.com/questions/10502802/cdate-type-mismatch-error)
Comment: @DarrenBartrup-Cook thats the one :) write it up
Comment: @DarrenBartrup-Cook Yes! I'm trying to find the Date in a Range of cells! Is this not the way to do it?
Answer: From what I can read in your code:
Cells(5, 5) = Range("A:A") - you can't compare a single value to a whole column of values.
Cells(x, 5) = strDate - x is a range object, not a row number.  Use x.Row instead.
If the value in Cells(5,5) isn't found then x will equal nothing causing an error on this line: Cells(x, 5) = strDate
Try adapting this code:
Sub Test()

    Dim x As Range

    With ThisWorkbook.Worksheets("Sheet1")
        Set x = .Range("A:A").Find(What:=.Cells(5, 5), LookIn:=xlValues, LookAt:=xlWhole)
        If Not x Is Nothing Then
            .Cells(x.Row, 5) = CDate("5 Aug 2016")
        End If
    End With

End Sub

It will search column A in Sheet1 for the value in cell Sheet1!E5.  It will then put 05/08/2016 in column five of the row it finds.
With...End With:
https://msdn.microsoft.com/en-us/library/wc500chb.aspx
Comment: Thanks so much Darren! This works perfect. I very much appreciate it!


Javascript Array combine elements to get a unique array

Question: Suppose I have a JS array like this:
[
  {
    "lat": 49.26125,
    "lon": -123.24807,
    "weight": 120
  },
  {
    "lat": 49.26125,
    "lon": -123.24807,
    "weight": 80
  },
  {
    "lat": 49.26125,
    "lon": -123.24807,
    "weight": 160
  },
  {
    "lat": 49.26229,
    "lon": 23.24342,
    "weight": 236
  },
  {
    "lat": 49.26229,
    "lon": 23.24342,
    "weight": 167
  }
]

Suppose I want to add up the weights the elements that have the same lat & lon to get something like this:
[
  {
    "lat": 49.26125,
    "lon": -123.24807,
    "weight": 360
  },
  {
    "lat": 49.26229,
    "lon": 23.24342,
    "weight": 403
  }
]

what's an efficient way to do that in JS?
Comment: Look at Array.prototype.reduce, or if you post what you've tried so far, we can assist you further.
Answer: You could use a hash table as closure and a key with lat and lon as combined value.
Then check if the hash exists and if not generate a new object with the data and push it to the result set.
Later add weight to the property at the hashed object.

var data = [{ lat: 49.26125, lon: -123.24807, weight: 120 }, { lat: 49.26125, lon: -123.24807, weight: 80 }, { lat: 49.26125, lon: -123.24807, weight: 160 }, { lat: 49.26229, lon: 23.24342, weight: 236 }, { lat: 49.26229, lon: 23.24342, weight: 167 }],
    result = data.reduce(function (hash) {
        return function (r, a) {
            var key = ['lat', 'lon'].map(function (k) { return a[k]; }).join('|');
            if (!hash[key]) {
                hash[key] = { lat: a.lat, lon: a.lon, weight: 0 };
                r.push(hash[key]);
            }
            hash[key].weight += a.weight;
            return r;
        };
    }(Object.create(null)), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer: You can do this by reduce-ing your array to form a map from unique [lat, lon] pairs to a merged object that accumulates your total weight. Your result is then the list of values held by that map (which can be obtained using Object.keys and Array#map).

var array = [{lat:49.26125,lon:-123.24807,weight:120},{lat:49.26125,lon:-123.24807,weight:80},{lat:49.26125,lon:-123.24807,weight:160},{lat:49.26229,lon:23.24342,weight:236},{lat:49.26229,lon:23.24342,weight:167}]

var map = array.reduce(function (map, o) {
  var k = [o.lat, o.lon].join()

  if (k in map)
    map[k].weight += o.weight
  else
    map[k] = o

  return map
}, {})

var result = Object.keys(map).map(function (k) { return map[k] })

console.log(result)
.as-console-wrapper { min-height: 100%; }
Answer: You can do something like this. It may not be that efficient but it works.

var arr = [{ lat: 49.26125, lon: -123.24807, weight: 120 }, { lat: 49.26125, lon: -123.24807, weight: 80 }, { lat: 49.26125, lon: -123.24807, weight: 160 }, { lat: 49.26229, lon: 23.24342, weight: 236 }, { lat: 49.26229, lon: 23.24342, weight: 167 }];

arr = arr.reduce(function(accumulation, currentElement){
    var samePosition = accumulation.find(function(obj){
        return obj.lat === currentElement.lat && obj.lng === currentElement.lng;
    });
    if(samePosition){
        samePosition.weight += currentElement.weight;
    }else{
        accumulation.push(currentElement);
    }
    return accumulation;
}, []);

console.log(arr);


Add custom action buttons to a view

Question: Suppose that I have a view that outputs a list of some content. Now I'd like to add some action buttons next to each content item, so that clicking these buttons triggers some custom action or redirect the user to another path (specific for that item).
I found a solution here that comes close to what I'd like to do, but that solution is based on D7 Add custom action buttons to view.
Without repeating the content of this link, could someone let me know whether that approach is still valid/good practice for Drupal 8?
In case it is the solution, how would you implement the functionality of passing the $nid of a list item to a different form via POST when clicking one of the action buttons ? Would this be part of the function function query() {...} in step 5 of the link ? If so, how would you approach this ?
Are there solutions that might be better suited to D8?
Answer: Drupal 8 lets you add 'DropButtons' to your View, which looks really good in UI.

add a 'Custom text' field for each action you want to provide - use 'exclude from display' and 'output as custom link'
add a 'dropbutton' field and select your custom links to be shown in it
profit
Comment: Thanks, that seems to be a good way to solve this. If you could help me with one more thing. Let's say I have a dropbutton now in each row. Is it possible when clicking the button to redirect to a form and pass a variable (e.g $nid) via POST ?
Comment: Better late than never: Views let you add Replacement patterns. These are based on columns prior the one holding the Custom text.

So in this case, you should add a (hidden) 'nid' column to your view, which will make the {{ nid }} replacement pattern available in the Custom text field (see Replacement patterns). In the Rewrite results section's Link path, you can use this, e.g. node/{{ nid }}/edit.

Add custom action buttons to a view


Next and Previous Button for Pages

Question: I have created a 'Content Type' names it Stories. And have created 30 new pages for each stories using the same Content Type. Now how can i add Previous and Next Button under each stories?
Any Article or Video tutorial will be appreciated
Thank You,
Mazhar
P.S I am using D8
Answer: I would say that one relatively easy way without relying on any additional modules is to use the book module that comes with drupal core.
If you put the nodes in a book then you can use the book navigation's previous and next button.
You can override book-navigation.html.twig to remove elements of the book navigation that you don't need.
Comment: Thanks Rooby,

I am a newbie in Drupal, thank you. Liked your suggestion very much. I looked for the video and found this https://www.youtube.com/watch?v=UuItYbS9Rlo&t=4s

I am gonna try it later and if I get stuck I will seek your help again.

Thanks
Mazhar
Answer: I know this is old thread, but for benefit of users looking for an answer in 2020 for Drupal 8 (8.8+) and 9, try out https://www.drupal.org/project/related_nodes_block.
It does not require any taxonomy terms, and it supports Prev/Next, First/Last, Most/Least Viewed and Random, of same content-type or others, you choose.
Disclaimer: I am the author of the module.

Next and Previous Button for Pages


Music Note Flashcards

Question: Beginner looking to improve music note recognition, particularly for bass clef and tenor clef (I'm proficient in treble). Any suggestions besides just slugging my way through music?
Unlike the other question, Learning standard notation without succumbing to simply remembering songs?, I am already proficient at treble clef, i.e. reading standard notation; I don't "simply remember songs," or rely on my ear. It's also 5 years 9 months old and maybe newermore info available? I thought the mnemonics idea and links below were helpful and neither mentioned in the other post. Not a big deal though. Thanks.
Comment: I'm unsure what you are asking for here. Are you wanting to recognise written score? If so, there really is no alternative to practicing, "slogging" your way through music.
Comment: Nothing beats doing it.  You simply need to get your head down and read as much music as you can.
Answer: I've used these as mini assignments before (they have them for every clef) decent way to work on it reading away from your instrument. But the best way really is just reading though a bunch of music.

Free Bass Clef Flashcards (music-theory-practice.com/music-notes/bass-clef-flashcards.html)
Tenor Clef Flashcards (music-theory-practice.com/music-notes/tenor-clef-flashcards.html)
Answer: You could use maybe "mnemonic"-s to improve your skill.
One example is my favourite: FACE. The name of the notes in the spaces of the treble cleff.
For bass (and if you want to some for treble):
"Great Big Dogs Fight Animals." for the lines of bass.
"All Caretaker Eats Grocery." for the space of bass.
https://www.mnemonic-device.com/music/
For tenor:

(Image Source: http://whatbrassplayerswant.com/alto-and-tenor-clef-no-worries-with-these-simple-tricks/)
"Every Garage Band Dominates." for the spaces of tenor.
"Dearest Friends Always Care." for the lines of tenor.
Now look at the alto cleff just to be sure:

(Image Source: https://en.wikipedia.org/wiki/Clef)
"F A C E" for the lines of alto.
"Global Boredom Doesn't Fail." for the spaces.
The last one doesn't make as much sense as the ones before but maybe help.

Music Note Flashcards


What are the difference between an ARMA(2,1) model and an ARMA(13,9) model?

Question: I was wondering if there are any other things that I can say about the differences between these 2 models, besides the comments about the ACF and PACF. Specifically, I was wondering which model would be easier to forecast with, if that makes any sense, and why.
Answer: As you can see here ( http://en.wikipedia.org/wiki/Autoregressive%E2%80%93moving-average_model#ARMA_model ) the ARMA(2,1) will only depend on the last two values, and on the last noise variable, when the ARMA(13,9) will consider 13 values to the past and 9 past noise variables.
To forecast it all depends on your what you're trying to forecast. If your variables do not depend strongly on lots of values in the past, you can use the ARMA(2,1). It all depends on the nature of what you're trying to predict.


Adding additional option values to the selectbox after they are typed in the input box

Question: I need your help.
I have the following code below, which works well if only one single value is added into the select box after it has been typed out in the input box (hence, making it an editable selectbox), then if another value is typed out in the input box, the content of the select box is changed to the newly entered value.
I would like to modify the code below so as to allow additional typed in values to be added into the selectbox.

<input id="text1" type="text" onkeyup="AddListItem(this)"><select id="list" onchange="getval()">
</select>

Comment: Do you have a JSFiddle?
Answer: In order to do this, I had to change onkeyup to onchange. So the option will only get added after the input element loses focus.

<input id="text1" type="text" onchange="AddListItem(this)"><select id="list" onchange="getval()">
</select>


the set $\{xm + ny : x,y \in Z^+\}$ contains all but a finite number of the positive integers.

Question: If $m$ and $n$ are relatively prime then the set $\{xm + ny : x,y \in Z^+\}$ contains all but a finite number of the positive integers.
What I tried : We know that there exist integers $x,y$ such that $mx+ny=1$. But both can't be negative/positive. So, we need to separate the positive and negative part of each coefficient. Let $a_1 =x^+$ and $b_1=x^-$ and $a_2 =y^+$ and $b_2=y^-$. Then $ma_1 + na_2 = 1 + mb_1 + nb_2$. So, I have got two consecutive integers. Stuck after that.
Comment: This is the [coin problem](http://en.wikipedia.org/wiki/Coin_problem) for two coins.
Comment: @Arthur: I said $x,y$ are positive integers, but the theorem says that it is non-negative.
Comment: That _will_ have an effect on the actual bound, but not on the fact that there are only a finite number of unreachables. To see this, take one of each coin, and set them aside. Now use the theorem to show that the highest unobtainable result (not counting the two you set aside) is $mn - (m + n)$. Add back the two coins you set aside, and see that the highest unreachable number is $mn$, with at least one of each coin present.
Answer: Take a large enough number $t$ (Say, $t>mn$). Then take the set $\{t-in,0\le i< m\}$. This set contains $m$ numbers.
If two elements in this set are the same $\pmod m$, we have:
$$
t-i_1n\equiv t-i_2n \pmod m\\
i_1n\equiv i_2n \pmod m\\
m|(i_1-i_2)n$$
Since $gcd(m,n)=1$, it impies $m|i_1-i_2$ Which is impossible since $m>i_1-i_2$.
So any two elements in this set are different from each other $\pmod m$. This implies one of them equal to 0 $\pmod m$, or $m|t-i_rn$ for some $r$:
$$
m|t-i_rn\\
t-i_rn=km\\
t=km+i_rn
$$
As needed.
There are only finitely many numbers that $<mn$.


Connect OpenVPN clients to clients only (without server access)

Question: I have setup an OpenVPN server (on Windows), that allows clients to talk to each other and the server, using client-to-client in the servers conf file.
Now I want to restrict the clients access to each other only, so they cannot access any server resources (shares etc.).
Is there a configuration option, that blocks traffic to the server itself and just allows the clients to reach each other?
Of course I could configure the server's firewall, but maybe there is something easier already lingering in OpenVPN's configuration options.
Answer: In the end I did not find any option in OpenVPN itself to block reaching the server itself, so I blocked access to the server using the firewall after all.


Nuisance parameters and $o_p(n^{-1/4})$ convergence: citation

Question: I'm looking for an original reference to a proof idea.
Suppose we have $n$ iid observations $(X_i,Y_i)$ and an estimating function
$$\bar U(\beta;\alpha)=\frac{1}{n}U(\beta;\alpha; X_i,Y_i)$$
where we are interested in estimating $\beta\in \mathbb{R}^p$ and $\alpha\in\mathbb{R}^q$ is a nuisance parameter.
Further suppose that
$$E[\bar U(\beta_0,\alpha)]=0$$
for every fixed $\alpha$ (or every fixed $\alpha$ in some suitable open set or whatever).  This happens in GEE when $\alpha$ are working correlation parameters and in survey statistics when $\alpha$ are raking parameters and a variety of other settings.
Under classical smoothness assumptions, and using the fact that $$\frac{\partial }{\partial\alpha}E[\bar U(\beta_0,\alpha)]=0,$$
it can be shown that if $\|\hat\alpha-\alpha^*\|=o_p(n^{-1/4})$, there is a consistent and asymptotically Normal sequence of plug-in estimators of $\beta_0$ solving $$\bar U(\beta; \hat\alpha)=0$$ with the limiting variance depending on $\hat\alpha$ only through $\alpha^*$.
Question: This argument was certainly known in the mid-1990s, and I was told it was first developed by Whitney Newey, but I don't know where. Does anyone know the Newey reference? Also, does anyone know an early reference by someone else?
Comment: Hi, did you get to the bottom of this?
Comment: No, I'm still no further forward.
Answer: The paper I'm looking for appears to be
Newey, W. K. (1994). The Asymptotic Variance of Semiparametric Estimators. Econometrica, 62(6), 1349–1382. https://doi.org/10.2307/2951752
The fourth-root convergence assumption appears in the discussion following Assumption 5.1


Ant design  create static array of forms

Question: I am using antd with react to develop an application.
<Form.List name="secondaryContacts">
  {(fields, { add, remove }) => {
    return (

        {fields.map((field, index) => (
          <Form.Item
            {...formItemLayoutWithOutLabel}
            label={index === 0 ? "" : ""}
            required={false}
            key={field.key}
          >
            <Form.Item
              {...field}
              validateTrigger={["onChange", "onBlur"]}
              rules={[
                {
                  required: true,
                  validator: phoneNumberValidator
                }
              ]}
            >
              <Input
                placeholder="Secondary Contact"
                addonAfter={
                  fields.length >= 1 ? (
                    <MinusCircleOutlined
                      onClick={() => {
                        remove(field.name);
                      }}
                    />
                  ) : null
                }
              />
            </Form.Item>
          </Form.Item>
        ))}
        <Form.Item {...formItemLayoutWithOutLabel}>
          <Button
            type="dashed"
            onClick={() => {
              add();
            }}
            style={{ width: "100%" }}
          >
            <PlusOutlined /> Add Secondary Contact
          </Button>
        </Form.Item>

    );
  }}
</Form.List>;

Above is the code I am using to add dynamic form fields with validation using Form.List.
Now I have a specific scenario where I need to show 7 Sliders(https://ant.design/components/slider/) for the selected time slot and store them in an array, so I thought of using Form.List and keep all sliders inside just like above(except that it's static).
But I am not clear how I can achieve it with Form.List and there are very few examples on the internet.
I have a scenario where I need to have an array of forms and club them as an array using Form.List.
Comment: what difficulty u facing?
Comment: Not able to add a form.list entry for static set of items.
Comment: Have you solved the issue?
Answer: You can use the initialValue property to set the static data
Example:
const staticValue = [{ formItem1: 'value1', formItem2: 'value2'}];

<Form.List name="formListName" initialValue={staticValue}>
    {(fields, { add, remove }, { errors }) => (
        fields.map((field) => (
            <>
                <Form.Item {...field} name={[field.name, 'formItem1']}>
                    <Input placeholder="Field 1" />
                </Form.Item>
                ...

Answer: You still need <Form> component
Try
<Form>
  <Form.List>
  </Form.List>
</Form>

Ant design  create static array of forms


The usefulness of very broad tags - macroeconomics and microeconomics

Question: we've already got macroeconomics and microeconomics . The risk is that these are so broad, that they are no longer useful ways of locating questions.
Should we keep these very very broad tags, even if it means that most questions end up with one or the other of them?
Answer: I think they are worth keeping.

Even though they are broad, Macro and Micro are very much part of the usual branching of economics. I think not having them as tags would be confusing.
They can be combined with other, more specific tags, so you can express what the question represents. For example, macroeconomics labor-economics.
Macro and Micro represent two different approaches to an issue, so it might be worth differentiating a question with a top-down approach (macro), or a bottom-up approach (micro), depending on what kind of answer you expect.
Comment: In addition I can just ignore anything that includes the tag Macroeconomics ;-)
Comment: Combining tags has consistently failed where it's been tried.  That's not to say that you shouldn't use multiple tags on a question, but merely that you shouldn't rely on tag synergies.
Comment: @TheAlmightyBob 's answer is actually on point. For example, on Stackoverflow, you will tag questions to packages of Python not only with the package name, but also with the superset tag *Python*, in order to exactly allow for that.
Answer: Even though they may not be useful for browsing through, they will help the sidebar bring up related questions. For this to work both the macro/micro and topical tags will be needed.
Answer: I think that they should stay but should be used relatively sparingly.  We should come up with a good excerpt that limits what they do.  For example, there are a lot of rather basic results that come up during introductory courses.  Questions related to those kinds of things should get the tags.  Things that can be approached from either direction should not get the tags, e.g. international trade should have its own tag.
The problem is that we could end up with every question being tagged at least one.  That makes for a pretty useless tag.  If we keep them, then we need to find definitions that limit their scope.


Passing Function Pointers to Native functions as parameters

Question: I am working with the android NDK trying to use an existing library to build an Application.
The following function is declared in the library...
BYTE __stdcall InitRelay(fp_setbaud _setbaud, fp_get _get, fp_put _put, fp_flush _flush, fp_delay _delay){

These are the declarations for the parameters passed to InitRelay...
typedef void (__stdcall *fp_setbaud)(WORD);
typedef short (__stdcall *fp_get)(WORD);
typedef void (__stdcall *fp_put)(BYTE);
typedef void (__stdcall *fp_flush)(void);
typedef void (__stdcall *fp_delay)(WORD);
 typedef short (__stdcall *fp_ProgressUpdate)(WORD);

I've been to this thread, but still am not sure what to do. The difference between what I am doing and what they are doing, is that I want to call a native function in C that requires a function pointer as a parameter.
I was considering writing a wrapper function in the Native code, does that sound right? My main problem is that I cannot change the native code i've been given, but I can add new functions. I know people will ask me to post my java code, so I will, but it is literally useless. It is just a method call with parameters that currently don't make sense to java.
 // InitRelay
    InitRelay( fp_setbaud _setbaud, fp_get _get, fp_put, fp_flush _flush, fp_delay _delay );

Answer: Yes, write native wrappers.  You will need to do this anyway as jni has very particular naming requirements for the interface functions.  Non-trivial data types will also require copy conversion from/to jni references.
Process-level static state in the library can also give you a lot of headaches, since android does not link the lifetime of a process to a user perceptible session lifetime.  Android will also quite happily put multiple distinct sessions into the same process.
Comment: Thank you, I actually have no experience in C, and have only been working android for about five weeks, is there anywhere you know of I can learn more about this situation?
Comment: Well, start by building the hello-jni example from the ndk samples, and look at the function naming and what it has to do to create a string that java can use.
Comment: Yeah, I've done it. I'm comfortable calling functions from the native code in my Android code. What I'm not comfortable is writing wrappers in C, but I guess that's a very broad topic.
Comment: Basically you need to create things that are called in a jni-compatible way, and call the native library in the way it expects.  That is fairly straightforward on a detail level; the real challenge will be figuring out if an overlall plan of mapping one onto the other is workable, or if you may need to consider a different overall mapping.
Comment: Not asking you to write my code for me, but if you find the time to edit the post and add some sort of example code for the wrapper, I'd really appreciate it.


Yammer: Android WebView Authentication

Question: I am trying to authenticate an user from my Android App for Yammer OAuth. Using Webview for loading the authentication URL and expecting a code / token to come back. But the results are not predictable.
webView.loadUrl(OAUTH_URL + "?redirect_uri=" + REDIRECT_URI + "&client_id=" + CLIENT_ID);

Also using WebViewClient.
webView.setWebViewClient(new WebViewClient() {...}

In Android 4.4, no URL redirection is happening and it stays blank. Or no code / token comes.
In older android versions, it works sporadically.
Anyone tried this? I am doing this because of the lack of Android SDK. Appreciate any working sample.
Adding Android tag to reach bigger group. Any working snippet is welcome!
Answer: Goodness gracious, after hours and hours of struggle, finally fixed it.
Problem is I was having the WebView load into a dialog, instead of a full activity. Thats it! The WebView inside a Dialog was loading redirects so unpredictably.
As soon as moved the WebView into its own Activity which has layout height and width of fill_parent, everything worked the way it is supposed to work.

Yammer: Android WebView Authentication


Is there any group $G$ with $ord(G)=20$ so that $\varphi:G\rightarrow \mathbb{Z}_{10}$ is epimorphism?

Question: Is there any group $G$ with $ord(G)=20$ so that $\varphi:G\rightarrow \mathbb{Z}_{10}$ is epimorphism?
I thout about $\mathbb{2\cdot Z}_{40}$, is it right?
Answer: Sure! For example the group $\Bbb{Z}_2 \times \Bbb{Z}_{10}$, where $\varphi$ is the projection on the second component.

If by $2 \cdot \Bbb{Z}_{40}$ you mean the image of the multiplication by $2$ homomorphism in $\Bbb{Z}_{40}$ then that works, too. Indeed, we know that
$$
\Bbb{Z}_{40} \simeq \Bbb{Z}_8 \times \Bbb{Z}_5
$$
and since $\Bbb{Z}_5$ has no elements of order $2$ it follows that
$$
G := 2 \cdot \Bbb{Z}_{40} \simeq \Bbb{Z}_4 \times \Bbb{Z}_5 \simeq \Bbb{Z}_{20}
$$
which clearly has cardinality $20$. Similarly, we see that multiplication by $2$ in $G$ gives a surjective homomorphism
$$
\Bbb{Z}_4 \times \Bbb{Z}_5 \to \Bbb{Z}_2 \times \Bbb{Z}_5 \simeq \Bbb{Z}_{10}
$$


Como fazer Hover para link e ícone ao mesmo tempo

Question: Bom dia, pessoal. Estou com o seguinte código HTML:

         ENTRAR

E o seguinte código CSS:
.gly-user {
    border: 2px solid rgb(35, 220, 97);
    padding: 0.6em;
    border-radius: 25px;
    margin-right: 8px;
    color: #23DC61;
}

Como eu faço, para que ao passar o mouse em cima do "link" entrar, tanto a cor do ícone como sua borda fique verde e ao mesmo tempo a palavra entrar também fique verde. Além disso, como fazer para ao retirar o mouse, os dois voltem para o "estado normal" (inicial), o ícone com a cor e a borda branca e o texto com a cor branca?
Obrigado!
Answer: Você pode usar funções como li:hover .gly-user {} e li:hover a {}, dessa forma, quando o li sofrer o hover irá modificar a classe escolhida.
Veja este exemplo:

/* SOMENTE PARA DEMOSTRAÇÃO */

html, body, li {
  background: #222;
  margin:0px;
  padding:0px;
}

.menu {
  width:200px;
  float:left;
}

.menu li {
  width:200px;
  height:auto;
  padding:10px;
  border: 2px dashed rgb(0, 0, 0);
}

/* QUANDO ACIONADO */
/* Apenas acrescente as "variaveis" que são modificadas, não há necessidade de declarar novamente o que já contem no PADRAO */

.menu li:hover a {
  color: #23DC61;
}

.menu li:hover .gly-user {
  border: 2px solid rgb(35, 220, 97);
}

/* PADRAO */

.menu li a {
  color: #fff;
  text-decoration: none;
}

.menu li .gly-user {
  border: 2px solid rgb(255, 255, 255);
  padding: 0.6em;
  border-radius: 25px;
  margin-right: 8px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

       ENTRAR

A classe .menu foi criada apenas para que o li:hover não alteresse em todos os locais, sendo assim, apenas os elementos dentro dele serão afetados.


Permission to create new users but not to manage them

Question: I need to create a permission that allows any user to create other users without allowing them to manage all users (ie without granting them 'administer users' permission).
My approach was altering menu 'admin/people/create' but it - for unknown reason - doesn't work. Even though the permission for the menu is granted the menu item with link for is invisible and when I go to the specific url it - if I don't have 'administer users' permission - just redirects me to current user profile page.
    /**
 * Implements hook_menu_alter().
 */
function fm_users_more_menu_alter(&$items) {
  $add_new_user = &$items['admin/people/create'];

  unset($add_new_user['access callback']);
  unset($add_new_user['access arguments']);

  $add_new_user['access callback'] = 'fmu_add_user_access_callback';
  $add_new_user['access arguments'] = array(1);
}

/**
 * Callback that manages access to create user page.
 */
function fmu_add_user_access_callback($arguement) {
  dsm('test23');
  return true;
}

It does the same - redirects you to current user profile page - with User register form.
  $register_new_user = &$items['user/register'];

  unset($register_new_user['access callback']);
  $register_new_user['access callback'] = 'fmu_register_user_access_callback';

/**
 * Callback that manages access to create user page.
 */
function fmu_register_user_access_callback() {
  dsm('test23');
  if (user_register_access() || user_access('create users under self')) {
    return true;
  }
  else {
    return false;
  }
}

Answer: Don't forget to also give those same users the permission to access administration pages -- otherwise they'll be denied anytime they try to access any URI beginning with admin.
Also, I don't think it's necessary (or even desirable) to unset the menu items like that... You should just be able to do this:
function fm_users_more_menu_alter(&$items) {
  $items['admin/people/create']['access callback'] = 'fmu_add_user_access_callback';
  $items['admin/people/create']['access arguments'] = array(1);
}

Finally, remember to rebuild the menus after making such a change.
Comment: It doesn't help, it still redirects me to current user profile page without any apparent reason.
Comment: Yikes. Without giving them that permission? I don't think so... Well, not without compromising a whole lot of security. And actually I just looked, and if you look at lines 3752-3768 of `modules/user/user.module` you'll see that in order for anyone to access the user registration form, they have to either be anonymous or have the permission `administer users`. You should also see why it's redirecting you to the user page on line 3767. :/
Comment: Yep, I see it know (actually had found it before read your comment. Now I need to figure out how to surpass it.

//I might have found an answer to that here: https://api.drupal.org/api/drupal/modules!user!user.module/function/user_register_form/7
Answer: I've found out where the problem was, inside user register form there's this piece of code that - if a user is logged in but is not a administrator - redirects you to your profile page.
  // If we aren't admin but already logged on, go to the user page instead.
  if (!$admin && $user->uid) {
    drupal_goto('user/' . $user->uid);
  }

More information can be found here: https://api.drupal.org/api/drupal/modules!user!user.module/function/user_register_form/7


Given data matrix and error matrix, find value of $x,y,z$

Question: In an exercise about multiple regression, I'm given the following data matrix $X$ and error vector $\epsilon$:
$$
X = \begin{bmatrix}
    1 & 4 & x \\
    1 & -2 & 1\\
    1 & 1 & 4 \\
    1 & -2 & 8 \\
    1 & y & 2 \\
\end{bmatrix}~, \quad \epsilon = \begin{bmatrix}
    z \\
    4 \\
    5 \\
    -7 \\
    -1 \\
\end{bmatrix}
$$
I'm asked to find $x,y$ and $z$ but I don't know what to do. I thought the formula of $Y = \beta X + \epsilon$ might help but it doesn't do much since we don't know $\beta$ nor $Y$. Any help is appreciated.
Answer: I managed to find the answer:
Through properties of the residuals we know that $X^{T}\epsilon = 0$ so all we need to do is solve the following system:
\begin{align}
z + 4 + 5 -7 - 1 = 0\\
4z - 8 + 5 + 14 - y = 0\\
xz + 4 + 20 - 56 -2 = 0
\end{align}
So that
\begin{align}
z = -1 \\
y = 7 \\
x = -34
\end{align}


How to take care of the percentage/rate of an absolute number as independent variable?

Question: I am working on a mixed model, where suppose I have several stores of different sizes. The number of products manufactured in each store is different, say one store can manufacture 100 and other can do 10000 products as well. I have one independent variable as "total number of defects in a store". I am assuming that larger the products manufactured at a store, more will be the defects at that store.
Now if I take only the "absolute total number of defects" at a store, I am losing on the info about the total size of the stores. Can I use "percentage = (total defects at the store/total size of the store)" as my independent variable instead of "total defects at the store". Will that solve my issue? Or do I need to include interaction? Will the model become complicated in this scenerio?
Comment: Can you use size of the stores as an independent variable? This should help you avoid using percentages.
Comment: Also, you mentioned that number of defects is the independent variable. I would assume this would be your dependent variable instead?
Comment: Sorry for my extreme late reply! To your first answer, do you mean to use both the number of defects and size of store as independent variables?
Comment: Assuming that I want to use both of them at the independent variable side, what is the best possible way to do that? Is it to use percentages/rate (using one as numberator and other as denominator) or using both as two separate independent variable?
Comment: It is very unclear what your final objective is. Are you trying to predict number of errors? Calculating a percentage can be done even after predicting number of errors
Answer: It is best to avoid using percentages as the dependent variable if at all possible, especially if you intend to use the denominator of the percentage as an independent variable. This will introduce sever bias due to mathematical coupling. Another pitfall is to use variables that are rates which are divided by the same denominator for a similar reason. A better approach in your case is to use the number of defects as the dependent variable and the size of the store as an independent variable.


Proving Subtraction without using it??

Question: Definition: $(a, b) \sim (c, d)$ iff $a + d = b + c$. Explain how this relation represents subtraction. (Do not prove that it's an equivalence relation.)
I'm not sure how to answer this/what the final step looks like so any help would be appreciated. I believe you set each side equal to a single variable first? Could be completely wrong
Comment: I'm not sure how you're supposed to show that this is the same as subtraction without even referencing what subtraction is in the first place... I'll note that this is usually how you define $\mathbb{Z}$ from $\mathbb{N}$, by letting $\mathbb{Z}\colon= \mathbb{N}\times\mathbb{N}/\sim$. Are you sure this isn't supposed to be explaining *negative numbers*, not subtraction? A relation isn't an operation...
Comment: my bad. its my first post; ill fix it next time
Comment: I think the question statement is under-specified; "represents subtraction" seems a bit arbitrary, so I understand your confusion.

Note that $a+d=b+c$ means the same as $a-b=c-d$. I would maybe start there.
Comment: @Charlie exactly where I go wrong. I'm supposed to explain how this shows subtraction or the idea of subtraction without using it; therefore I can't show how those are the same thing. I think I'm meant to start by setting a+d=e or something and proving that this relation somehow outlines subtraction? I don't know if that gives you any better idea on how to proceed?
Comment: @Charlie. This is all the instructions I have; it might just be another way to define Z actually...if you want to expand on that? Otherwise: "But, since
we can't subtract in N we will arrive at subtraction through addition. We begin by defining a relation ~ on N x N.
Definition: (a, b) ~ (c, d) iff a + d = b + c.
Explain how this relation represents subtraction.
I believe I can reference subtraction, but can't perform it on the numbers. Also I'm confused on how the two directions of the iff work. Not sure if this clarifies?
Comment: I'll just second what @Charlie said: this is the usual definition of negative numbers.
Answer: I'm interpreting this question as charitably as possible. Unfortunately, it seems from the comments that your instructor has provided you with vague instructions.
The relation $\sim$ on $\mathbb{N}\times\mathbb{N}$ allows you to represent subtraction as follows: for a given natural number $n\in\mathbb{N}$, write $n$ as $[(n,0)]$ (the equivalence class of $(n, 0)$). Then for any two natural numbers $n, m$, we can simply define $n-m = [(n, 0)]- [(m, 0)] = [(n, m)]$. One can easily check that this is well-defined. This interpretation of subtraction hinges on the idea of $(a, b)$ being considered "large" if $a$ is much bigger than $b$. It also allows the representation of negative numbers by using pairs where $b>a$.
That's about the best I can give from the context provided; since a relation isn't an operation, all I can really do is show you how the operation is actually defined. But my real advice is to ask for clarification from your instructor directly.
Comment: Ok! I'll mention this idea to him and ask for more clarification. Thanks!

Proving Subtraction without using it??


1-d harmonic oscillator recursive function, possible Infinit-loop, c++ syntax

Question: Working on a 1-d Harmonic oscillator using recursive functions, code works in fortran and trying to convert to C++ in order to learn the new syntax.
I have fixed all the notified errors so far searching through google, but still not getting a result.  The program just runs seemingly forever without posting results.
I think the likely answer is maybe its not being calculated at all or there some some infinit loop because of a syntax problem in my for loop or called functions? but I am not seeing it and it is not identifying an error with them.
Any advice on why this program is not working properly?

//
//  main.cpp
//  1-d HO
//
//  Created by Grant Metheny on 3/2/16.
//  Copyright (c) 2016 Grant Metheny C++ Codes. All rights reserved.
//

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
#include <math.h>

using namespace std;

int i = 0;
int n = 0;
double x = 1.;
double xmax = 5;
double imax = 1000;
double wavefunc = 0;
double fact = 1;
double hpol = 1;
double wf0 = 1;
double wf1 = 1;
double wf2 = 1;
double wf3 = 1;
double wf4 = 1;
double wf5 = 1;
double wf6 = 1;

double wavefunction(int n, double x)
{
    return wavefunc = pow(2.0,-(n*.5)) * pow(M_PI,.25) * exp(-(.5*pow(x,2.0)));
}

double factorial(int n)
{
    for (i = 0; i <= n; i++)

        if (i == 0)
             fact = 1.;
        else
             fact = fact * i;

    return fact;
}

double hermite(int n, double x)
{
    for (i = 0; i <= n; i++)
        if (i==1)
            hpol = 1.0;
        else if (n==1)
            hpol = 2*x;
        else
            hpol = 2*x*hermite(n-1,x) - 2*(n-1)*hermite(n-2,x);

    return hpol;
}

double dx = 2*xmax/imax;

int main(int argc, const char * argv[]) {

    for (i=0; i <= imax; i++) {

    x =  5. - dx*i;

    n = 0;
    wf0 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));

    n = 1;
    wf1 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));

    n = 2;
    wf2 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));

    n = 3;
    wf3 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));

    n = 4;
    wf4 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));

    n = 5;
    wf5 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));

    n = 6;
    wf6 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));

    cout <<"I="<< i <<"X="<< x <<"WF0="<< wf0<<"WF1=" << wf1;  // wf2, wf3, wf4, wf5, wf6

}
    return 0;
}
Comment: If you want to learn C++ I recommend you find a good beginners book instead, for example from [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list).
Answer: Your for loops are not terminating. Instead of this:
for (i = 0; n; i++)

(which is clearly Fortran-inspired), you need to do this:
for (i = 0; i < n; i++)

The idea is that the second part of the for loop is not a limit; it is a predicate that should evaluate to true (to keep the loop going one more iteration) or false (to exit the loop). Because C/C++ treats non-zero integer values as true whenever a true/false value is expected, the loops just keep on going.
You need to make that correction in several places in your code.
Comment: made the changes but still getting a long run time with no results. so far have allowed like 5 min run time.
Comment: @g-metheny - You sure you changed them all? The loop in `main` involving `i` and `imax` also needs to be changed.
Comment: just updated the code in the question, changed 3 for loops including the one in main, factorial, and hermite.
Comment: @g-metheny - Okay. That's probably not a good idea because the original question is now lost. It would be better to at least leave a comment in the code about what it used to be. But at least I see that you did catch all the `for` loops. Some of your calculations are inefficient, but with the small values of `n`, I don't see anything that should be taking 5 minutes. Can you tell by using a debugger where it's spending its time? Or perhaps add in some logging statements.
Comment: @g-metheny - Hm. The recursion in the `hermite()` function looks suspicious. Won't that recurse forever if `n != 1`? The `if` tests look suspicious to me.
Comment: fixed it!!!  the hermit function didn't need to be in a "for" loop at all.  the recursive nature of the function worked by the nature of calling itself within the "if" statement
Comment: @g-metheny - Cool. I thought that looked wrong. By the way, some of those loop conditions look like they should perhaps be `<` instead of `<=`.
Comment: how would i use the debugger to check where it is spending its time? this could be useful in the future
Comment: @g-metheny - You could step through and watch the pattern of code execution. Presumably it would take an unexpected branch fairly early on. Or you could set conditional break points for unexpected conditions (like negative argument values).
Comment: I will keep that in mind.  Thank you very much for the help.  Darn code is freezing up my comp now, so its still got some bugs, but it pumped out results which is a start.  I will try to use those debug techniques to find the inefficiencies.
Comment: Just for completeness sake: because the for loop in main and the for loop in factorial both use the same variable i, the program ends up using i=7 infinitely many times in main.  Essentially it changes the value of i after it calculates factorial to 6, and does this every iteration thus it never moves on in the code.  changing one of them to ii or j or whatever corrected the problem.  once this error was corrected to code runs in about a second.
Comment: @g-metheny - The solution there is to eliminate most of the global variables and declare local variables in each method. So get rid of the global declaration of `i` (for instance) and change each loop involving `i` to `for (int i = 0 ...`.


Close rdpcap function - Scapy

Question: I have a script that loops through a lot of pcap files. For each pcap file I need to read it and then write some information to a txt file. I'm using the rdcap function from Scapy. Is there anyway to close the pcap file once I'm done reading it? My script has a memory leak and I'm worried this may be the culprit (via leaving many pcap files essentially open)
Answer: Inspecting Scapy's source code reveals that the rdpcap function neglects to close the pcap file:
@conf.commands.register
def rdpcap(filename, count=-1):
    """Read a pcap file and return a packet list
count: read only <count> packets"""
    return PcapReader(filename).read_all(count=count)

I suggest you implement your own version of this function as follows:
def rdpcap_and_close(filename, count=-1):
    """Read a pcap file, return a packet list and close the file
count: read only <count> packets"""
    pcap_reader = PcapReader(filename)
    packets = pcap_reader.read_all(count=count)
    pcap_reader.close()
    return packets

I've created an issue for this problem here.
EDIT: The issue has been resolved in this changeset.

Close rdpcap function - Scapy


how to make keyframe animations in chrome

Question: How to make keyframe animations in Chrome
fiddle
http://jsfiddle.net/tPw8J/
html
<button class="loading">btn</button>

css
@keyframes animation_loading {
    from { background-position:0 0; }
    to { background-position:25px 0; }
}

@-webkit-keyframes animation_loading {
    from { background-position:0 0; }
    to { background-position:25px 0; }
}

button.loading {
    background-image:url(//www.dynaccount.com/button.bg-loading.png);
    animation:animation_loading 0.5s linear infinite;
}

Answer:
"How to make keyframe animations in Chrome"

You'll need to include the -webkit prefix on the animation property:
button.loading {
    background-image:url(//www.dynaccount.com/button.bg-loading.png);
    -moz-animation: animation_loading 0.5s linear infinite; /* FF 15 & below */
    -webkit-animation: animation_loading 0.5s linear infinite;
     animation: animation_loading 0.5s linear infinite;
}

http://jsfiddle.net/tPw8J/3/


Which data structure preserves order in python?

Question: I am looking for a data structure which allows fast search and also preserves the order of the data it received?
Comment: You can use an OrderedDict - https://docs.python.org/3/library/collections.html#collections.OrderedDict
Comment: For anyone finding this question in the modern era: sets and dictionaries in Python are now guaranteed to be order-preserving, starting in Python 3.7.  See https://docs.python.org/3/library/stdtypes.html#mapping-types-dict .  If this question weren't closed, I would add an answer recommending to use those as the canonical solution.
Answer: Lists and tuples preserve order, dictionaries and set don't. An available ordered version of a dictionary is collections.OrderedDict, which provides a faster search than a list.
Comment: Also: [Synchronized queues classes](https://docs.python.org/3/library/queue.html)
Comment: And [collections.deque](https://docs.python.org/3.4/library/collections.html#collections.deque)
Comment: For numeric values, there is [array](https://docs.python.org/3/library/array.html).
Answer: Take a look at this
You have dictionaries and set:(unordered)

Dictionary is an unordered set of key: value pairs
set is an unordered collection with no duplicate elements

You can either use for preserving the order:

list
tuple
collections.OrderedDict

Choosing the data structure totally depends on your requirement.

List and tuple hold a basic difference. List is mutable and tuples is immutable
ordered dictionary is nothing but a key value pair.

So you can choose accordingly!


Question about a funky array declaration

Question: I just came across this array declaration:
const int nNums= 4;
int* nums[nNums] = {0, 0, 0}, d[nNums];

I understand that a pointer to nums is being created, but what is the business on the right? d[] gets initialized, but I am not quite sure what the {0,0,0} does.
Answer: int* nums[nNums] = {0, 0, 0} defined a array of 4 integer pointers each initialized to NULL. However, note that d is an array of integers and not integer pointers and these values are not initialized.
Comment: @zerocrates: I am not sure, but as far as I know if you partially initialize an array in c++ using `{}` syntax, then rest of the elements are default initialized, so in this case `nums[3]` will also be `NULL`.
Comment: In C++98 they were default-initialized; in C++03 and C++0x they're value-initialized.
Answer: That code is equivalent to:
const int nNums= 4;
int* nums[nNums] = {0, 0, 0};
int d[nNums];

So, nums is an array of int*s of length 4, with all four elements initialized to null; d is an array of ints of length 4, with all four elements uninitialized (to reemphasize, d does not get initialized in any way).
The syntax = {0, 0, 0} in this context is known as "aggregate initialization", and is described in §8.5.1 of the C++03 standard; the relevant portion for this code (§8.5.1/2) states:

When an aggregate is initialized the initializer can contain an initializer-clause consisting of a brace-enclosed, comma-separated list of initializer-clauses for the members of the aggregate, written in increasing subscript or member order. If the aggregate contains subaggregates, this rule applies recursively to the members of the subaggregate.

So, the first three elements of nums are explicitly initialized to 0, and the fourth element is implicitly "value-initialized", as stated in §8.5.1/7:

If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized.

Value-initialization is described in §8.5/5:

To value-initialize an object of type T means:

if T is a class type with a user-declared constructor, then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;
if T is an array type, then each element is value-initialized;
otherwise, the object is zero-initialized

To zero-initialize an object of type T means:

if T is a scalar type, the object is set to the value of 0 (zero) converted to T;
if T is a non-union class type, each nonstatic data member and each base-class subobject is zero-initialized;
if T is a union type, the object's first named data member) is zero-initialized;
if T is an array type, each element is zero-initialized;
if T is a reference type, no initialization is performed.

This results in the fourth element of nums also being initialized to null.
Answer: int* nums[nNums] = {0, 0, 0}, d[nNums];

As @Asha already said that nums is an array of 4 integer pointers each initialized to NULL.
The interesting question which can be further asked here is : what is the type of the variable d?

Is it an array of 4 integer pointers?

Or

Is it an array of 4 integers?

So the answer is : its an array of 4 integers. The * is associated with only first declared symbol nums.
The equivalent declaration would be this:
int* nums[nNums] = {0, 0, 0};
int d[nNums]; //not int* d[nNums];

To avoid such confusion, I prefer to write such declaration on multiple lines. If you want to declare in one line, the second declaration would be a bit better:
int*  nums[nNums] = {0, 0, 0}, d[nNums];  //old one!
int  *nums[nNums] = {0, 0, 0}, d[nNums];  //new one. note the position of *

Answer:
> I understand that a pointer to nums is
  being created,

You understand incorrectly. There's no "pointer to nums" being created in that declaration. Declaration
int* nums[4] = {0, 0, 0};

declares an array of 4 pointers. nums itself is an array, not a pointer to anything.

> but what is the business on the right?

The = {0, 0, 0} parts is called "aggregate initializer". It initializes the first tree elements of the nums array. It is not clear why only three are explicitly initialized (while the fourth one is left to be initialized to zero implicitly). Also, in C++ the same effect can be achieved by a
int* nums[4] = {};

declaration, where all four elements are initialized to zero implicitly.

> d[] gets initialized

Huh? No. The declaration of d is equivalent to
int d[4];

meaning that d does not get initialized at all.


Nginx HTTP/SPDY over SCTP

Question: I've ready a thread in russian Nginx maillist about implementing HTTP/SPDY over SCTP in future.
I realize that SCTP is completely unusable for public service at the moment, but what changes should happen for SCTP to replace TCP for public web?
Comment: Time travel is one really hard problem to solve when implementing protocols in the future :P
Comment: ipv6 questions was pure theory just couple of years ago. That's why it's such a big problem now.
Answer: Why SCTP, I wonder?  SPDY specifically implements the multiplexing itself within TCP because SCTP isn't practical in the short term.
In my understanding, the biggest barrier to SCTP deployment today is support for the protocol in the operating systems of endpoints, and support for the protocol in transit in NAT and firewall network devices (anything that needs to actually be able to inspect the protocol).
Most decent firewalls will let you allow an IP protocol number, but support for more granular port rules and connection tracking for NAT is a must for widespread deployment.  NAT support in consumer routers is going to be a real barrier - those devices don't tend to be very close to the "cutting edge" of decade-old internet standards (say, for instance, IPv6).
Comment: IPv6 supposed to make NAT useless. I think that IPv6 support in SOHO/consumer routers is more close than SCTP NAT fixup
Comment: Yeah, but when NAT's gone in IPv6, then those consumer routers still need to be able to inspect the protocol and act as a firewall.  It doesn't seem terribly likely that the consumer routers with IPv6 support deployed over the next 5 years will tend to have SCTP support.

Nginx HTTP/SPDY over SCTP


Flutter remove specific route from route stack

Question: I want to remove a specific route and stay on the same page without navigating to different page.
I have three pages PageA, PageB, PageC. I have the below code in PageC and removing PageB from Route stack. After removing it's navigating back to PageA (default route page). I want to stay on the RouteC without navigating.
final newRouteName = "/PageB";

navigatorKey.currentState!.popUntil((route) {
  if (widget.routeSettings!.name == newRouteName) {
    navigatorKey.currentState!.removeRoute(route);
  }
  return true;
});

Please help me, i stuck with this for days
Answer: I dont know if this works for you, but probably what you can do is:
When navigating from 'Page B' to 'Page C' make a

void _moveToPageC() {
  Navigator.pushReplacementNamed(context, '/routeC');
}

That way, your stack would be page a > page c
Then if you want to go back to page a then you can simply pop page C
Hope, this helps
Comment: Thanks for the response. I want to remove PageB completely from the route.


How to debug: How Can I see the form arrays with its components (fields) in a loaded page?

Question: I would like to changing a title of a button in a form, and I would like to have a tool for debug, like devel or another, so I can see in real time, after a page is loaded, what is the structure in forms, subcomponents, name of every field.
So I know how could add a line to the code in my custom module to change the title of a form button.
How would you do it? Steps, method, tools, please share.
Note: These are my first steps in programming modules, changing simple things for now.
Thanks for your suggestions!
Answer: Debugging in Drupal can be a bit frustrating when you first start out but you'll get the hang of it quickly :)
Debug is a really convenient Drupal function to output your form array (or any array/object) from any custom module/template.
In the case of your form, you can invoke hook_form_alter in you custom module to call the debug of your form. (You can find the form ID by looking at the page code and replacing the - with _. For example "user-login-form" would be "user_login_form" here)
<code> function YOUR_MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
   if($form_id == 'your_form_id') {
     debug($form,'form',TRUE);
   }
 }
</code>
Then (after clearing caches) once you visit the page with the form, Drupal will output the $form array as an entry in your watchdog log (admin/reports/dblog).
Comment: That's what form_alter does, regardless of which module created the form. You can find the button's ID in your browser's source code as well (for the Search magnifying glass button on Drupal.org home page, it's "edit-submit" for example) In the hook_form_alter page I linked to above there is lots of information and examples. In your case, you can use the function sample in my answer and replace the debug line with something like: `$form['edit_submit']['value']='NewTitle';`
Comment: sure thing @bunset you can output the debug function [more info here](https://api.drupal.org/api/drupal/includes%21common.inc/function/debug/7.x) anywhere to inspect the variable of your choice. So if you want to inspect the node object of a specific content type, add `debug($node,'Node',TRUE);` at the top of that content-type's template. Or you can just add that to your main template with an `if ($node) { debug($node,'Node',TRUE); }` Hope that helps.
Comment: Hi @longboardnode!. Thank you for your help. In my particular issue, my button is displayed by vbo views module. And I want to create a custom module to change the title of the button. I need a tool or method to know the name of the form and the name of the submit button to change the title.
Comment: thanks @longboardnode! very instructive. I would like too, install a debug environment on my localhost to inspect the values of variables while loads the page in realtime. Can you give me any suggestion about this?


To find value of $\tan^2 C$

Question: In a $\triangle{ABC}$ , if $\tan A + 2\tan B=0$ to find range of values of $\tan^2 C$
I don't know how to begin
Thanks for help
Comment: See https://in.answers.yahoo.com/question/index?qid=20130121010705AAwzxPk
Answer: We have $$\tan A+\tan B+\tan C=\tan A\tan B\tan C$$
$$\implies-2\tan B+\tan B+\tan C=(-2\tan B)\tan B\tan C$$
$$\tan C\cdot2\tan^2B-\tan B+\tan C=0$$ which is a Quadratic Equation in $\tan B$
As $\tan B$ is real, the discriminant must be $\ge0$
Again, $\tan C=\dfrac{\tan B}{1+2\tan^2B}$
What if $B\to0$ or $\to\dfrac\pi2$
Answer: For every triangle $ABC$ we have
$$\tan A+\tan B+\tan C=\tan A\tan B\tan C$$
Then
$$\tan C-\tan B=-2\tan^2 B\tan C$$
and, completing the square,
$$2\tan C\left(\tan B-\frac1{4\tan C}\right)^2-\frac1{8\tan C}+\tan C=0$$
Hence
$$\frac1{8\tan^2C}-1=2\left(\tan B-\frac1{4\tan C}\right)^2\ge 0$$
Answer: See if you can get these hints
$$ t_C= t_{\pi-A-B} = \dfrac{-t_A-t_B}{1-t_A t_B} =\dfrac{2t_B}{1+2 t_B^2}$$

To find value of $\tan^2 C$


what does the class modifier do in cil call command?

Question: looking at the code generated by monodis, I see that the call to Console.WriteLine is translated to call void class [mscorlib]System.Console::WriteLine. I know that the void at the beginning is the return value, but what does the class mean?
Comment: I'd assume that `class` means this method is called **without an object context** tmt **a static method**. You may have a look at this tutorial at [codeproject.com](http://www.codeproject.com/Articles/3778/Introduction-to-IL-Assembly-Language#Object)
Comment: "class method" is a geeky way to say "static method".
Answer: The class keyword just says that System.Console is a class.
The relevant part of the CLI specification is §II.7.1 Types. It describes the Type rule of the CIL grammar, which requires class to refer to any "user defined reference type".
Though the call instruction actually takes a TypeSpec, which means that omitting the class keyword is also allowed.


Associate URL with Windows Phone 8.1 application

Question: is it possible to associate specific URL with Windows Phone 8.1 application?
When there is a request to open URL in format e.g. http://myservice.mydomain.com?Params... from e-mail or page in browser, my application will process an URL.
On Android it is possible in manifest with intent-filter for some activity:
<code>...
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:host="myservice.mydomain.com" android:scheme="http" />
</intent-filter>
...
</code>
Thanks.
Comment: as far as I know, you can associate a file format with your WP8.1 app, but no way can associate URL except IE.
Answer: You can make an URI association with a custom URI schema, like "myapp:"
Read more here: URI Associations


Endogenous controls in linear regression - Alternative approach?

Question: I have a cross-section of $x$, $y_1$, and $y_2$. These are individual level data used in labor economics. I have random variation in $x$ and I'm interested in the effect of $x$ on $y_1$. It is well established in earlier research that $x$ causally affects $y_2$ positively. Economic intuition says that $y_2$ will affect $y_1$ positively as well. Hence, $x$ has an effect on $y_1$ through $y_2$.
Estimating the regression $y_1 = a_1+a_2x + a_3y_2$ I believe is problematic since $y_2$ is endogenous. What type of model(s) can I estimate to identify the "direct" effect of $x$ on $y_1$ (the $a_2$ parameter) while controlling for the effect $x$ has on $y_1$ through $y_2$?
Comment: Your OLS estimate for $a_2$ would be biased not because $y_2$ is endogenous, but because $x$ itself is endogenous due to multicolinearity between $x$ and $y_2$. One strategy would be to find a valid IV that affects $x$, but not $y_2$. This IV would affect $y_1$ only through $x$. The first stage of your IV estimate would sort of partial out the effect of $x$ on $y_1$ that is uncorrelated with $y_2$.
Comment: could you explain what real-world variables are behind $y_1$, $y_2$ and $x$? This would help sorting out your problem.
Comment: @sgtbp, I see that you do not accept my answer, no ask clarifications nor give opinions. What do you think?
Comment: @sgtbp; First of all you have to realize that concepts like "endogeneity" and "direct effect" are causal. My reply here (https://stats.stackexchange.com/questions/493211/under-which-assumptions-a-regression-can-be-interpreted-causally/493905#493905) can be interesting for you. Said that, you give some causal assumptions above.
Comment: Moreover  you write "Hence, $x$ has an effect on $y_1$ through $y_2$. … can I estimate to identify the "direct" effect of $x$ on $y_1$ …?". From your words is not clear if you assume direct effect (of $x$ on $y_1$) and want to estimate it, or if you do not assume it. This point is crucial for write down correctly the associated structural equations. Now I'm too busy but if you clear this point i give you my reply later.
Comment: Thanks for you reply, @markowitz. I'm struggling to see what you need clarified. However, I'm interested in the causal or direct effect of $x$ on $y_1$. To be clear, in the model I pose in my question the effect of $x$ on $y_1$ is given by $\frac{\partial y_1}{\partial x} = a_2 + a_3 \frac{\partial y_2}{\partial x}$. I want an unbiased and consistent estimate of $a_2$. My challenge is that it is not reasonable to assume the latter derivative to be zero.
Answer: If $y_2$ can be observed, there is nothing wrong with your approach. You are interested in the effect of $x$ on $y_1$ and you control for the partial influence of $y_2$. Estimating
$$ y_1 = \alpha + \beta_1 x + \beta_2 y_2 + \varepsilon $$
will yield a unbiased estimate of the effect of $x$ on $y_1$ if everything else (captured by $\varepsilon$) does not affect $y_1$ for given values of $x$ and $y_2$. I might have misunderstood what you mean by the 'direct effect', but $\widehat{\beta_1}$ will give you the effect of $x$ on $y_1$ net of the impact from $y_2$.
Comment: \beta_1 is biased due to endogeneity
Comment: I don't think you misunderstood what I meant, but I'm pretty sure that @bellmaneqn is right about the endogeneity problem.
Answer: You are interested in causal inference with linear models, therefore with linear regression. In situation like that we have to deal with regression and causality, this is a widespread and slippery problem. I tried to summarize this problem here: Under which assumptions a regression can be interpreted causally?
Following the approach that I suggest there, we have to write down some structural causal equations that encode the causal assumptions. My question in the comments come from clarifications about these. From what you said it seems that we have two structural equations:
$y_1 = \beta_1 y_2 + \epsilon_1$
$y_2 = \beta_1 x + \epsilon_2$
So there is not direct effect of $x$ on $y_1$; however there is and indirect one. Indeed we can see that $y_1 = \beta_1 \beta_2 x + \beta_1  \epsilon_2 + \epsilon_1 = \beta_3 x + \epsilon_3$
and $\beta_3 = \beta_1 \beta_2$ represents the indirect (and total) effect of $x$ on $y_1$
Now I add some needed (causal) assumptions more. In the initial two structural equation the structural errors are exogenous  ($E[\epsilon_1 | y_2]=0$ and $E[\epsilon_2 | x]=0$) and them are independent.
So, as consequence, in the last structural equations the structural error $\epsilon_3$  is exogenous ($E[\epsilon_3 | x]=0$)
Then, you can perform the regression    $y_1 = \theta_1 x + u_1$   and  $\theta_1$ identify $\beta_3$, what you looking for.
Moreover in this example a regression   $y_1 = \theta_2 y_2 + u_2$   the coefficient $\theta_2$ identify $\beta_1$.
Modifying the model as suggested in comments we have two structural equations:
$y_1 = \beta_1 y_2 + \beta_2 x + \epsilon_1$
$y_2 = \beta_3 x + \epsilon_2$
Here $\beta_2$ is the direct effect of $x$ on $y_1$; what we are interested in. Moreover there is an indirect one too.
Now, we can see that
$y_1 = \beta_1 \beta_3 x + \beta_2 x +  \beta_1 \epsilon_2 + \epsilon_1 = \beta_4 x  +  \epsilon_3$
where $\beta_4 = \beta_1 \beta_3 + \beta_2$ represents the total effect of $x$ on $y_1$
and $\epsilon_3 = \beta_1 \epsilon_2 + \epsilon_1 $
Now, as before, I add some needed (causal) assumptions more. In the initial two structural equation the structural errors are exogenous  ($E[\epsilon_1 | y_2, x]=0$ and $E[\epsilon_2 | x]=0$) and them are independent.
So, as consequence, in the last structural equations the structural error $\epsilon_3$  is exogenous too ($E[\epsilon_3 | x]=0$)
Then, you can perform three useful regressions
$y_1 = \theta_1 x + u_1$
$y_2 = \theta_2 x + u_2$
$y_1 = \theta_3 y_2 + \theta_4 x + u_3$
here  $\theta_1$ identify $\beta_4$, $\theta_2$ identify $\beta_3$, $\theta_3$ and $\theta_4$ identify $\beta_1$ and $\beta_2$ (what you looking for).
Moreover from $\theta_1 - \theta_3 \theta_2$ (like $\beta_4 - \beta_1 \beta_3$) we identify $\beta_2$ again. So if the restriction
$\theta_4 = \theta_1 - \theta_3 \theta_2$ do not hold, we have evidence against the SEM (the causal assumptions).
Moreover we can note that, obviously, not all regressions are good.
For example if we run this regression
$y_1 = \theta_5 y_2 + u_4$
the coefficient $\theta_5$ do not identify any parameter of the SEM. $\theta_5$ is biased for $\beta_1$ ($x$ play as omitted/confounder variable).
(I dropped out the constant terms for simplicity)
Finally, the initial regression that you had in mind was good, no endogeneity (but it can happen by chance). However I suppose that you had in mind other approach for the problem. I suggest you this one.
Comment: There is a direct effect of $x$ on $y_1$ in addition to the relation specified by your second equation. $x$ is missing from your first equation.
Comment: Ok, later I add the case that account for that. However this was precisely what I feared. From your explanation was clear that you are interested in the causal effect of $x$ on $y_ 1$ and also that have an indirect one (through $y_ 2$), but was not clear if you assumed a direct effect too. Now it is clear. Note that the causal assumptions have to precede the estimation procedure. From your question I fear that you conflated them (common mistake).


How to input Unicode character in Rails console?

Question: While using Rails console, when I input ä, \U+FFC3\U+FFA4 appears.
 Of course I can input Unicode characters outside of rails.
I'm using Ruby 2.0.0p247, Rails 4.0.0 in Max OS X 10.7.5.
How can I input Unicode characters in Rails console?
Comment: Thanks, but I can input unicode character in terminal without problem. I can't input only in rails console.
Comment: Do you use rvm? Most likely you've got readline issue, https://github.com/wayneeseguin/rvm/issues/1016 or http://blog.rlmflores.me/blog/2012/04/25/adding-utf-8-support-to-rubies-compiled-through-ruby-build/
Comment: I'm using rbenv, but as you said readline was the problem. I reinstall the ruby and works fine now! Could you write it as a answer so that I can accept it.
Answer: I did have the same problem. After done a lot of things, including the complete reinstall of RVM, I'd realized I just need to define the LC variables. To do the same, run these commands on terminal:
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
export LANG LC_COLLATE LC_CTYPE LC_MESSAGES LC_MONETARY LC_NUMERIC LC_TIME LC_ALL

One good idea is save this code in .bash_profile or .bashrc files in the App folder.
Comment: 3 years after your answer, I was having the same issue. Thank you very much, Fernando, it was really helpful!
Comment: in case of .zshrc it helps too
Comment: Yeah, @okliv. I do think this solution can helps everybody. Just change `en_US.UTF-8` to your right character set.
Answer: Most likely you've got readline issue, try to re-install Ruby with readline support. https://github.com/wayneeseguin/rvm/issues/1016 or http://blog.rlmflores.me/blog/2012/04/25/adding-utf-8-support-to-rubies-compiled-through-ruby-build/


Are Maximal Consistent set of formulas unique?

Question: I know that for any consistent set of formulas $\Gamma$, there exists a maximal consistent set of formulas $\Theta$, such that $\Gamma\subseteq\Theta$.  Given this, do we know if $\Theta$ is unique?
Comment: [These](https://www.google.com/search?q=%22maximal+consistent+set+of+formulas%22+AND+%22unique%22+AND+%22math+stack%22+site:math.stackexchange.com&client=ms-android-samsung-ga-rev1&sxsrf=ALeKk023wAntrZwgbfiCqUrKT_7BkO3TzA:1592852354203&sa=X&ved=2ahUKEwi_xIG2jZbqAhUSmIsKHW05BIwQrQIoAjAAegQIAhAL&cshid=1592852428302&biw=1261&bih=2372&dpr=2.63) are some related questions.
Answer: No, having a unique maximal consistent extension is equivalent to a theory being complete and consistent. So any incomplete consistent theory (e.g. PA) has more than one maximal consistent extension.
If $T$ is consistent and incomplete, and $\varphi$ is undecidable in $T,$ then $T\cup\{\varphi\}$ and $T\cup \{\lnot \varphi\}$ are both consistent, so have (necessarily different) maximal consistent extensions which are both maximal consistent extensions of $T$.


Why is my filtered collection being populated by my main collection, whenever I fetch my main collection from the server?

Question: I have a main collection of models that I then filter into 3 separate collections (Think categorized menu).  I have a timer to do a fetch on my  main collection to make sure it is in sync.  Each of my filtered collections is the basis for a Marionette CollectionView and renders properly the first time through.  As soon as my main collection fetch is completed by the timer, each filtered collection refreshes with the main collection's data.
Update: My guess is, that since I am wrapping my filtered collection in a new Backbone.Collection, The reset is applying to each of my collections that share the same models, and so the fetch triggering the reset on my collection, actually triggers the reset on all my filtered collections as well, and then populates it with the full collection.
How do I get around this?
Answer: It seems to me that you are sharing certain objects by reference. If you would like to contain 3 isolated collections based on some original shared state, but without creating any relation to that state, I would copy all data and create new objects. This can be done via _.extend.
It is possible I may be misunderstanding your situation altogether. Some context/code would be helpful.
Answer: The issue was me. :)
I wasn't thinking, and I was creating new instances of the main collection type, even for my filtered collections.  This was creating the timer on all the filtered collections too, and was, of course, refreshing the filtered collections with the main collection data.


Retract of contractible space is contractible [proof verification]

Question:
Retract of contractible space is contractible.

Let $r:X\to A$ where $A\subset X$: subspace and $r$ is retraction, $X$ is contractible.
Statement is so famous anybody can find the proof. But I found that many proofs is much longer than I thought. Here's my proof: $\text{id}_X\simeq C_{x_0}$ and $r\circ i = \text{id}_A$ where $i:A\hookrightarrow X$: inclusion. So, $\text{id}_A =r\circ i  = r\circ\text{id}_X\circ i \simeq r\circ C_{x_0}\circ i=C_{r(x_0)}$ noting the fact that $f\simeq g\Rightarrow f\circ h\simeq g\circ h$ and $k\circ f\simeq k\circ g$ where each composition are well defined. I've never seen such proof in Google so far. They all use explicit homotopy $H:X\times I\to X$ from $\text{id}_X$ to $C_{x_0}$ so I wonder if my proof is wrong or have some serious problem.
Answer: Your proof is indeed correct. You rely on the critical notion that if $f \simeq g$ and $h \simeq k$ then $f \circ h \simeq g \circ k$. This observation is critical in another short proof of the fact.
Background:
Consider the "homotopy 1-category", where the objects are topological spaces and the arrows are continuous functions, quotiented by $\simeq$. The fact that this is actually a category is equivalent to the above observation about composition preserving $\simeq$
$\DeclareMathOperator{\id}{id}$
The terminal object of this category is the singleton space 1, because this is the terminal object of the category of topological spaces. In other words, there is only one map from a space $T$ to the singleton space 1, up to homotopy.
It can easily be seen that a space is contractible iff the space is isomorphic to 1 in the homotopy category.
If the space is isomorphic to 1, then consider the homotopy-isomorphism $f : 1 \to A$ and inverse $g : A \to 1$. Then we see that $\id_A \simeq f \circ g$, and $f \circ g$ is a constant function $C_{f(x)}$ where $x$ is the unique element $x \in 1$.
On the other hand, if $\id_A \simeq C_{a_0}$, then define $f : 1 \to A$ by $f(x) = a_0$ and let $g : A \to 1$ be the unique function. Then we see that $C_{a_0} = f \circ g \simeq \id_A$, so $A$ is homotopy-isomorphic to 1.
Thus, a contractible space is exactly a space which is a terminal object in the homotopy category.
End background
In general, if we have a terminal object $1$ and arrows $i : A \to 1$ and $r : 1 \to A$ such that $r \circ i = \id_A$, then $i$ is an isomorphism. This is because we have $i \circ r : 1 \to 1$ and $\id_1 : 1 \to 1$, and hence $i \circ r = \id_1$.
Thus, the retract of a contractible space is contractible.
Comment: Actually my question is whether my proof is correct.
Comment: @barista Yes, your proof is correct. I added some commentary at the top of my answer.


django get latest release QuerySet

Question: class Release(models.Model):
    version = models.PositiveIntegerField(default=1)
    project = models.ForeignKey('projects.Project', related_name='releases', on_delete=models.SET_NULL, blank=1, null=1)

class Project(models.Model):
    # pass

def getObjects():
    releases = []
    for project in Project.objects.all():
        if project.releases.all():
            releases.append(project.releases.all().order_by('-version')[0])
    return releases

is it possible to get a queryset of latest releases of each project if it has release? sorry I literally have no idea how to write the queryset.

I am sorry that I posted the wrong model, project field is meant to be on Release model, just a copy and paste issue.
Answer: There is a way to do this in a single query, you will need to combine annotate and filter together.
The method is to annotate each object with the highest version for each project related to the release. So we use a double-underscore through relation of project__releases__version. This gets the project related to each release, gets all of the related releases to that project and thus all of the versions.
We can apply Max to that field to get the highest one. Once we know what the latest version is, we can simply filter the queryset for that value using an F() object, which gets the field value.
from django.db.models import Max, F

Release.objects.annotate(
      latest_for_project=Max(project__releases__version)
   ).filter(
      latest_for_project=F('release')
   )

Comment: thanks, this actually inspire me to add a `BooleanField` to `Release` model, which turn previous to `False` when new one is created, will save much more work.
Comment: Nice idea, keeps things more obvious
Answer: You have to set relation properly. You should not connect Project to Project, if you want to have relation with Release :)
It is much better to use direct relationship or model's method. Then you can easier use it anywhere outside.
class Release(models.Model):
    version = models.PositiveIntegerField(default=1)
    project = models.ForeignKey('projects.Project', related_name='releases', on_delete=models.SET_NULL, blank=1, null=1)

class Project(models.Model):
    # project fields

    def latest_release(self):
        return self.releases.order_by('-version').first()

Then in fuction (or shell):
def get_latest_releases():

    releases = []
    for project in Project.objects.all():
        if project.latest_release():
            releases.append(project.latest_release())
    return releases

Comment: thanks very much for you help, sorry that I posted the wrong model, however I needed a queryset solution for further usage.

django get latest release QuerySet


paginação no vue js

Question: Estou observando o parâmetro da url para fazer uma paginação no vue.js3
No meu onMounted eu pego o parâmetro e busco a pagina referente  do parâmetro no beck end (se for 1 vou buscar a primeira pagina 2 a segunda a assim vai), o beck end vai me retorna 5 registros o numero total de registros numero total de paginas e numero da pagina atual.
Eu pego isso e monto a tela

   const {
      params: { page },
    } = useRoute();
    const getpage = () => {
      return page ? page : store.state.page;
    };
   onMounted(async () => {
      const onGetTributo = async page => {
        if (!page) page = 1;
        try {
          var resp = await servico.getGridPage(page);

          return [resp.itens, resp];
        } catch (err) {
          console.error("Erro ao buscar Tributo!", err);
        }
      };

      itensPaginacao = await onGetTributo(page);

    });

Retorno do back end

ai pra fazer a navegação eu tenho uma função que faz

 router.push("/tributo/" + page)

O comportamento que eu espera que ele tivesse era navegar para a nova url com o novo parametro e que ele montasse o componente de novo mas ele so navega e eu tenho que dar um f5 para mostrar o conteúdo novo
Para funcionar por enquanto eu fiz:

 const newContentTable = (page) => {
      router.push("/tributo/" + page)
      setInterval(function(){ document.location.reload(true); }, 10);
      console.log("/tributo/" + page)
    };

Minha duvida é qual a forma certa de recarregar esse componente quando eu navego para a próxima pagina
Answer:
O comportamento que eu espera que ele tivesse era navegar para a nova url com o novo parâmetro e que ele montasse o componente de novo, mas ele só navega e eu tenho que dar um F5 para mostrar o conteúdo novo.

Você precisa fazer o Vue forçar a re-renderização do componente para que ele seja recarregado. Existem duas formas de fazer isso, quando você utiliza VueRoute.
A primeira forma é utilizando key.
<router-view :key="$route.path" />

Quando você usa o key e ele é modificado, o Vue escreve o componente novamente.
A segunda é usando um watch para verificar mudanças no $route.
methods: {

    created() {
        this.carregarDados();
    },
    carregarDados() {
         api.get(`dados/${this.$route.params.id}`);
    },
},
watch: {
   $route() {
       this.carregarDados();
   }
}

Uma terceira opção é usar os Navigations Guard:
beforeRouteUpdate (to, from, next) {
  // just use `this`
  api.get(`dados/${to.params.id}`);
  next();
}

paginação no vue js


Como autocompletar um valor sem sobrecarregar o banco de dados

Question: Bem, estou trabalhando com uma tabela com um pouco mais de 60.000 registros e surgiu uma situação em que, através de um input o usuário pode persquisar algum texto que contém em um registro. Inicialmente o usuário apenas digitava o texto a ser buscado e pressionava o botão buscar para assim realizar o filtro, mas agora surgiu uma necessidade de, enquanto o usuário digita aparecer uma lista prévia com 10 resultados referentes ao texto que ele digitou no input.
Imagino que ir fazendo a consulta enquanto o usuário digita não seria também uma alternativa viável, uma vez que, vai gerar uma grande quantidade de requisições sobrecarregando o servidor.
Em algumas situações que prcisei fazer isso com uma tabela menor, eu simplesmente já trazia essa lista pronta como um array e já ia filtrando através desse array para mostrar essa prévia de resultado para o usuário, mas com essa base maior eu já não sei se seria viável essa solução.
Explicado o contexto, existe alguma "solução pronta" para casos como esse?
Estou utilizando banco de dados MySQL, php com o framework lumen como backend, ReactJS no front e fazendo requisições via axios.
Comment: Se for usar o meu código, atenção que eu havia cometido um erro. Atualizei agora. Esqueci de dizer, mas tem várias bibliotecas que implementam isso, se quiser pode pegar uma implementação pronta.
Comment: @bfavaretto Queria ter mais uma ideia de como é feito isso sem pesar o servidor mesmo, acabei achando algumas bibliotecas para atender essa situação, mas vou acabar implementando uma eu mesmo. Obrigado pelo esclarecimento! :)
Answer: Nesses casos, o que se faz é limitar a quantidade de requisições ao servidor. A técnica tradicional para isso é o debouncing dos eventos de keyup do browser no input de busca. Em vez de enviar uma nova requisição a cada keyup (que seria um desperdício de recursos tanto no servidor quanto no browser), você envia somente no último keyup da sequência.
Para implementar isso, você agenda o envio da requisição para um futuro próximo, por exemplo 500ms. Se antes desse tempo o evento ocorrer novamente, você substitui esse agendamento por uma nova requisição baseada no novo evento.
Exemplo de implementação:
const intervalo = 500;
let timer, anterior;

function trataKeyup(e) {
    const agora = Date.now();
    if(agora - anterior < intervalo) {
        // Anula agendamento anterior
        clearTimeout(timer);
    }
    // Agenda nova requisição
    const val = e.target.value;
    timer = setTimeout( geraBuscaPor(val), intervalo );
    anterior = agora;
}

function geraBuscaPor(valor) {
    return function() {
        axios.get('/?q=' + encodeURIComponent(valor));
    }
}


Having 2 independent segments made by 4 cartesian points, calculating x points of a smooth curve connecting the two segments

Question: Drawing with an example of what Im trying to do
I'm trying to make a sort of turtle program as a toy programming project.
I can send instruction to go from A to B straight giving direction and distance and generating the needed cartesian point to draw the final image.
But I need a method of telling the turtle to travel from B to C using a smooth curve, like in the example I drawn. A function will have to calculate a variable number of equidistant points (In the example, 5) from B to C sequentially. I only need to be pointed to the right mathematical formula...
I will also like to be pointed to relevant material (websites, books) I can study to acquire the knowledge involved in this type of task.
Thanks.
Answer: You gave a good example, but it is not clear what the general case is. It is also not clear what you mean by "smooth curve." In my answer I assume that by the latter you mean a curve with endpoints at $B$ and $C$, tangent vector at starting point $B$ parallel to vector $\overrightarrow{AB}$, and tangent vector at ending point $C$ parallel to vector $\overrightarrow{CD}$.
If your general case is where point $A$ is on the horizontal line through $B$ and to the left of $B$, point $D$ is on the vertical line through $C$ and below $B$, and point $C$ is down and to the right of $B$ at a $45°$ angle, a "smooth curve" is the quarter circle with center at $(x_a,y_c)$, and the $n$ points
$$(x_n,y_n)=\left( x_a+\cos\left[\frac{k\pi}{2(n+1)}\right] ,
  y_c+\sin\left[\frac{k\pi}{2(n+1)}\right] \right)$$
for $k=1,2,\ldots,n$, and the angle in radians.
If your general case is the same but allows any angle from $B$ to $C$, then a good curve would be an ellipse. However, getting the points to be equidistant is much more difficult. You could approximate that by just using equal angle increments, as in my previous formulas (putting constants in front of the cosine and sine makes that an ellipse), but for a general ellipse that does not give equidistant points. You get a better approximation by using numerical methods to find the arc length of the ellipse arc and choosing the angles appropriately. For more on this, do a search for "arc length of an ellipse."
If your general case allows for any locations for your four points, you may want to use a Cubic Bézier curve. That will make a smooth curve, and this is the technique commonly used in car design and other graphing applications. Again, however, finding equidistant points will be a challenge. You probably could use the approximation by using equally spaced parameter $t$ values, and a better approximation by using numerical methods to find the arc lengths involved. For more information on this, just do a search for "Bezier curve" (I don't know if you should include the accent or not in your search terms).
Answer: Check out Bezier curves,
they are a very popular choice for similar tasks in computer graphics.
For example, one way to do something similar
in the turtle graphic project is
to find point $E$ as the intersection
of extensions of the segments $AB$, $DC$
and draw
a quadratic Bezier segment, defined as
\begin{align}
\mathcal{B}(t,P_0,P_1,P_2)
&=
P_0(1-t)^2+2P_1(1-t)t+P_2 t^2.
\end{align}
While parameter $t$ changes from 0 to 1,
the curve goes smoothly from $P_0$ to $P_2$.

But there is a cost for simplicity:
points, generated using constant $\Delta t$
are not equidistant, but for a simple graphic project
this may be not so important.


Running http checks over SSL with HAProxy

Question: I'm trying to check my application (which runs on SSL) with haproxy. As I read the documentation, my options for health checks are:

httpchk, which sends an HTTP request to a configurable URL
ssl-hello-chk, which sends an SSL HELLO to the server, but you can't configure a URL.

It appears these options are mutually incompatible - specifying one does not let you specify another. Is there a way to make an SSL request to a specific URL and check if it's up?
Answer: In Haproxy 1.5, it is/will be possible to run httpchk over SSL connections.


Why don't baseball players get involved with the spectators when something good happens?

Question: When soccer players celebrate a goal, many times they celebrate "with" the public.
Why do baseball players pretty much ignore the public when celebrating? Or even don't show much emotion when a good play occurs?
For example, when running the bases after a home run many times the batter will show no emotion and not respond to the crowd cheering.
Comment: *When soccer players celebrate a goal, many times they celebrate "with" the public.* No, not always. There are fences and nets in the baseball stadium especially around home plate, and first and third base. Where do you expect it to happen? If a player shows too much emotion and performs excessive home run ceremony after hitting a home run, he can expect a hit by pitch at the next bat. That's for sure.
Comment: Many times players will take a curtain call and/or tip their cap.  What would you have them do?
Comment: I don't mean physically with the spectators. This rarely happens in soccer. I mean things like looking toward the spectators, making gestures toward the spectators, etc. You'll find that most soccer celebrations involve gestures toward the crowd: https://www.youtube.com/results?search_query=soccer+goal+celebrations
Comment: @user1167442 Celebrate like soccer players?
Answer: While browsing through the Major League Baseball rules I think I found a clue:

4.06 (3.09) No Fraternization Players in uniform shall not address or mingle with spectators, nor sit in the stands before, during, or after
  a game. No manager, coach or player shall address any spectator before
  or during a game. Players of opposing teams shall not fraternize at
  any time while in uniform.

Reference: MLB Official Baseball Rules
Comment: That's an interesting rule, and I don't think it's ever enforced (what's the punishment?), but I found that its origins probably have to do with avoiding the appearance of collusion for gambling. But like you said, this rule is just a clue; I don't think it really explains why baseball players don't engage the crowd in a general celebratory way (if you take that premise to even be true).