Material UI ListItemSecondaryAction vertically align in ListItem

Question: I came across @material-ui/core issue when creating ListIem with Action. I want to keep the ListItemSecondaryAction on top as ListItemAvatar when the secondary text goes longer, is there any way to overcome it:
<ListItem alignItems="flex-start">
        <ListItemAvatar>
          <Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" />
        </ListItemAvatar>
        <ListItemText
          primary="Brunch this weekend?"
          secondary={
            <React.Fragment>
              <Typography
                component="span"
                variant="body2"
                className={classes.inline}
                color="textPrimary"
              >
                Ali Connors
              </Typography>
              {
                " — I'll be in your neighborhood doing errands this…I'll be in your neighborhood doing errands this…I'll be in your neighborhood doing errands this…"
              }
            </React.Fragment>
          }
        />
        <ListItemSecondaryAction>
          <IconButton edge="end" aria-label="delete">
            <DeleteIcon />
          </IconButton>
        </ListItemSecondaryAction>
      </ListItem>

As you see here the delete icon is broken when the text goes longer, so I want vertical-align to keep it like the ListItemAvatar. any help will be appreciated, thanks!
CodeSandBox to play around
Answer: adding this style will fix your issue:
    <ListItemSecondaryAction style={{top:"0%", marginTop:"35px"}}>

Comment: Thanks! But why not simplify to something like `style={{ top: "40%" }}`? That worked for me.


Can't drupal_execute('filter_admin_format_form') on hook_install?

Question: I'm attempting to configure an input format on hook_install() with the following code:
module_load_include('inc', 'filter', 'filter.admin');
$form_state = array(
  'values' => array(
    'name' => 'Full HTML',
    'format' => '2',
    'roles' => array(
      1 => 0,
      2 => 0,
      3 => 1,
    ),
  ),
);
$arg = filter_format_load(2);
drupal_execute('filter_admin_format_form', $form_state, $arg);

However this produces the error:
Filter format names need to be unique. A format named Full HTML already exists.

However if I run the same code on hook_init(), then it runs without error.
Answer: You can execute that code, but you need to give a unique name for the input format being saved.
As alternative, if you want to be sure there is an input format called Full HTML, you can save the input format in the database using db_query(), and using the code of filter_admin_format_form_submit(), the form submission hander for the form you are executing, as guideline.
The involved database tables are two: filter_formats, and filter_formats; the first contains the data about the input format, and the latter contains the data about the input filters associated with an input format. The relevant executed queries are the following ones.
  if (!$format) {
    $new = TRUE;
    db_query("INSERT INTO {filter_formats} (name) VALUES ('%s')", $name);
    $format = db_result(db_query("SELECT MAX(format) AS format FROM {filter_formats}"));
    drupal_set_message(t('Added input format %format.', array('%format' => $name)));
  }

db_query("DELETE FROM {filters} WHERE format = %d", $format);

  foreach ($form_state['values']['filters'] as $id => $checked) {
    if ($checked) {
      list($module, $delta) = explode('/', $id);
      // Add new filters to the bottom.
      $weight = isset($current[$id]->weight) ? $current[$id]->weight : 10;
      db_query("INSERT INTO {filters} (format, module, delta, weight) VALUES (%d, '%s', %d, %d)", $format, $module, $delta, $weight);

      // Check if there are any 'no cache' filters.
      $cache &= !module_invoke($module, 'filter', 'no cache', $delta);
    }
  }

In Drupal 7, it would be easier, as you can call filter_format_save(), which always save the input format passed as argument, and eventually merge the format you passed as argument with the existing one.
The function that shows the error you are noticing is the form validation handler,  filter_admin_format_form_validate(), which contains the following code.
if ($result) {
  form_set_error('name', t('Filter format names need to be unique. A format named %name already exists.', array('%name' => $name)));
}

As the form validation handlers, and the form submission handlers are executed when you call drupal_execute(), the same error is returned, even when drupal_execute('filter_admin_format_form', $form_state, $arg) is called from hook_init(); it just happens that the error message shown with form_set_error() is not immediately visible when hook_init() is invoked, but the input format is not saved.
To notice that filter_admin_format_form_submit() executes the following code.
  $format = isset($form_state['values']['format']) ? $form_state['values']['format'] : NULL;
  $current = filter_list_format($format);
  $name = trim($form_state['values']['name']);
  $cache = TRUE;

  // Add a new filter format.
  if (!$format) {
    $new = TRUE;
    db_query("INSERT INTO {filter_formats} (name) VALUES ('%s')", $name);
    $format = db_result(db_query("SELECT MAX(format) AS format FROM {filter_formats}"));
    drupal_set_message(t('Added input format %format.', array('%format' => $name)));
  }
  else {
    drupal_set_message(t('The input format settings have been updated.'));
  }

Supposing that the form validation handler doesn't return an error, the form submission handler is not saving any data in the "filter_formats" table, if the input format is not new; in such case, the function executes the else part of the control statement, which just output a message.
Comment: When I run it with hook_init, I get a successful form submission drupal_set_message on every page load, and the settings save perfectly. However my OCD is going to have to take a backseat as I've decided as you suggest to go the db_query route. Thanks!
Comment: I found an explanation for the message about the settings being updated.
Comment: Thanks for the comprehensive explanation! I'm still feeling frustrated about why my code wasn't working though. I'm clearly setting $form_state['values']['format'], so why it fails isset() is a mystery to me :S.


Refreshing server repository after server files have been changed

Question: We have a server with svn acting as source control for a set of directories.
In an emergency, someone directly edited the files using vi.
How do I move the changes that they made outside of svn into the svn repository?
Then I'd do an "update" on the local working copies ... right?
Comment: also, the a number of new files were added to the dir structure ... how do I merge those new files into svn?
Answer: One way is that you can have a fresh working copy, copy the files on the server to the working copy and commit the modifications.


Which has more overtones: vowels or consonants?

Question: When comparing frequency patterns(e.g. using an FFTSCOPE) for spoken vowel sounds and that of consonants, some of us found vowel sounds to have more overtones(i.e., a larger number of peaks in the power spectrum) than consonants while others found the opposite. Is there a correct answer for this question or does it depend on an individual's way of pronouncing them?
Answer: Consonants are primarily just noise—largely high, semi-random frequencies. Vowels are generally the only part of speech that have harmonic content as opposed to the inharmonic content of consonants. Bright, forward vowels like EEEEEE have way more overtones than dark, back vowels like AHHHHHH. Most consonants other than the nasals are so brief that I'd be surprised if any overtone content can be seen at all that relates only to them—the overtones would surely mostly come from any preceding and following vowels. Again, the nasals like mmmmm and nnnnnn are an important exception, and I would expect fairly strong overtone content from them.
Otherwise, the fricatives and especially sibilant plosives should cause brief bursts of more-or-less random high-frequency blasts that might look like "more overtones", but are actually just noise.
Comment: Agreed with Pat here - just also want to clarify that his comments are probably specific to the romantic languages. Other languages, such as Mandarin, Cantonese, or Japanese sound very differently and as such need to be treated differently.
Comment: Well, I know what I said applies to far more than just the Romance languages, because it's true of English and German, in fact all of the European languages I'm familiar with. I think what I've said is pretty universal--obviously, what consonants and vowels are used vary substantially, and the relative proportions of them will be very different--but the actual nature of consonants vs. vowels should be the same. If your point is that the tonal nature of those languages makes them different, then that's true, but only vowels and nasals can carry tone, so it's still similar.
Answer: It depends on your way of quantifying matters.  Normal speech converts airflow into energy somewhat efficiently so you have similar amounts of energy per time.  Consonants fall into several different classes, voiced and unvoiced, and orthogonally nasal, fricatives, and plosives.
Vowels are directed rather well, so they tend to carry better than most consonants in the direction of talking.  Particularly if they are well-supported with a relaxed low larynx.  The unvoiced components of fricatives and plosives are basically all across the spectrum, with the fricatives having random phase (distributing energy evenly across time) and the plosives linear phase (focusing a high amount of energy to one point of time).  Vowels have a line spectrum, with the first line being the fundamental frequency and additional lines being shaped out of the harmonics by the vowel tract.  The lines obviously have higher peaks than the broad spectrum unvoiced sounds.  There are more harmonics to start before shaping when there is good vocal closure and/or chest voice involvement.
Flute/Falsetto registers are weak in harmonics for formants to start with, and the vowel tract is more apt shaping the harmonics at lower pitches, so vowels become badly distinguishable in those registers.
In operatic settings, consonants tend to get lost, partly due to their worse directivity, partly because particularly fricatives are limited in volume, and plosives need more conscious exaggeration than vowels.  I've witnessed an American "Siegfried" who was basically vowels-only.  Totally annoying.
So it very much depends on the windows in frequency and time that you are considering to figure out where most energy is available/focused.
Answer: Short Answer:
Consonants Mostly
Long Answer:
The important point here is less the vowel/consonant definition, but more the phonetic sound that they represent.  E for Example can be from eeeeeexample, or seeeee, which have a different set of overtones
consonants work to punctuate the vowels and give shape to the language because they are mostly short bursts of density.  They have generally more overtones in a short space of time which allows your mind to pick them up.
At their simplest you have Open Vowel sounds like AAAAAAAh, EEEEE etc
then you have Nasals in the middle, like mmmm or nnnnn
I believe a sound which can't be sustained is called a plosive.  So T for example
I took a spectrometer recording of a T(as in Ticking) sound against an E(as in speech) sound and found that the T sound had far, far more overtones packed into a small space. (I'll post the image in a bit)
Think of it like an opera singer hitting a long sustained note(say e) vs a snare drum.  The Snare Drum is a short sharp burst of sound like a plosive, but it penetrates the long sound because there're a lot of overtones hitting at one short burst.
Then you have the weird sounds like (Mira)ge, or the ch in Loch.
Hope that helps :)
Comment: Just case across this post. Do you still have, or can you recreate, the spectrometer images? They would be very interesting to see.


Given an encryption key in a transposition cipher, find the decryption key

Question: I am continuing my practice on problems for my cryptography class. I'm starting to get the hang of basic ideas of ciphers. At least i thought this until I attempted to do the follwng problem:
The encryption key in a transposition cipher is
$(5, 12, 3, 7, 9, 6, 4, 14, 1, 13, 10 , 8, 15, 2, 11,16)$.
Find the decryption key
I'm not even sure where or how to begin this problem. I've looked online to see if i came across any problems similar to this, but i have not found anything like this. Any help in pushing me in the right direction towards solving this would be greatly appreciated. Thanks!
Most of the stuff i've found involves words unlike this one.
Comment: What kind of transposition cipher? That key suggests columnar transposition, but for that you wouldn't have a separate decryption key.
Comment: That is all the info I am given for this problem.
Comment: How would you go about starting to solve this problem?
Comment: I would need more information than is present in the actual problem statement. I can only guess that this information is implicit in the context of the material that you've been studying, to which I don't have access.
Answer: Suppose your plaintext is 16 long: $p_1,p_2,\ldots,p_{16}$. Then the ciphertext, when we apply your key $(5,12,3,7,9,6,4,14,1,13,10,8,15,2,11,16)$ as a columnar transposition, equals $c_1 = p_9, c_2 = p_{14}, c_3 = p_3, c_4 = p_7, c_5 = p_1, c_6 = p_6, c_7 = p_4, c_8 = p_{12}, c_9 = p_{5}, c_{10} = p_{11}, c_{11} = p_{15}, c_{12} = p_2, c_{13} = p_{10}, c_{14} = p_8, c_{15} = p_{13}, c_{16} = p_{16}$.
So the key to go back from ciphertext to plaintext equals $(9,14,3,7,1,6,4,12,5,11,15,2,10,8,13,16)$


What is the intuition behind the Metropolis-Hastings Algorithm?

Question: I've been studying Bayesian Statistics lately, and just came across the Metropolis-Hastings Algorithm. I understand that the goal is to sample from an intractable posterior - but I'm not really able to understand how the algorithm achieves what it sets out to achieve.
Why and how does it work? What's the intuition behind the algorithm?

To clarify the parts I've problems with, in particular, I've attached the algorithm above.

How is the $q$ distribution (the proposal) related to the intractable posterior? I don't see how $q$ popped out of nowhere.
Why is the acceptance ratio calculated the way it is? It doesn't make intuitive sense to me - it'd be great if someone could explain that better.
In Step 3, we accept the $X$ we sampled from the $q$ distribution with some probability - why is that? How does that get me something closer to the intractable posterior, which is our goal? (right?)

Please help me out here. Thanks!
Comment: Do you understand [Metropolis method](https://bayes.wustl.edu/Manual/EquationOfState.pdf)? Section II in particular, Eq.(3) and its explanation
Comment: @Xi'an http://www2.geog.ucl.ac.uk/~mdisney/teaching/GEOGG121/sivia_skilling/mterop_hastings.pdf
Answer:
How is the $q$ distribution (the proposal) related to the intractable
  posterior? I don't see how $q$ popped out of nowhere.

The posterior is not intractable: $f(x)$ must be available (in a numerical sense) up to a multiplicative constant for the Metropolis-Hastings algorithm to apply. Otherwise, latent or auxiliary variables must be called in. Or else approximate methods such as ABC are needed.
The density $q(\cdot|\cdot)$ is essentially arbitrary, provided it operates on the same "space" as $f$. Meaning events measurable under $f$ should also be measurable under $q$. It is chosen when running the algorithm with competing goals of (i) a manageable enough simulation of $y\sim q(y|x)$ (ii) a computable density function $q(y|x)$ [up to a multiplicative constant] (iii) a sufficient coverage of the neighbourhood of $x$ towards ensuring eventually (in the number of iterations) a likely exploration of the whole support of the density $f$ (which leads to irreducibility for the associated Markov chain).

Why is the acceptance ratio calculated the way it is? It doesn't make
  intuitive sense to me.

The acceptance probability$$\alpha(x,y)=1 \wedge \frac{f(y)q(x|y)}{f(x)q(y|x)}$$is one of several choices that ensures $f$ is the stationary distribution density of the associated Markov chain. This means that (i) if $X_t\sim f(x)$, then after one iteration of the algorithm $X_{t+1}\sim f(x)$ (invariance of $f$) (ii) whatever the choice (or distribution) of $X_1$, the limiting distribution of $X_t$ as $t$ grows to $\infty$ is $f$.
One direct explanation for this stationarity is that
$$f(x)q(y|x)\alpha(x,y) = f(y)q(x|y)\alpha(y,x)$$
which is called detailed balance. It shows that the flow of the Markov chain is the same looking toward the future and looking toward the past (this is called reversibility). Any other function $\alpha$ that satisfies detailed balance works as well. Take for instance Barker's ratio
$$\alpha(x,y)=\dfrac{1}{1+\frac{f(x)q(y|x)}{f(y)q(x|y)}}=\dfrac{f(y)q(x|y)}{f(x)q(y|x)+f(y)q(x|y)}$$
Another intuitive if informal explanation for this property is that, if $X_t\sim f(x)$ and $Y|X_t=x_t\sim q(y|x_t)$, then accepting the value $Y=y$ with probability $\alpha(x_t,y)$ turns the distribution of the pair into $Y\sim f(y)$ and $X_t|Y=y\sim q(x_t|y)$.

In Step 3, we accept the X we sampled from the q distribution with
  some probability - why is that? How does that get me something closer
  to the intractable posterior, which is our goal?

The algorithm produces a Markov chain $(X_t)_{t\ge 1}$ that is converging in distribution  to the target distribution $f$. Hence the distribution of $X_t$ is eventually getting close to $f$ and hence for $t$ large enough the marginal distribution of $X_t$ is approximately $f$. But it does not make sense to consider that after each iteration $X_t$ is closer to the posterior distribution $f$.
Comment: There seems to be a typo in the final term for your definition of Barker's ratio.
Answer: Ok. Let's starting by addressing your question piecemeal. First, how is $q$, called the jumping distribution chosen? It's up to you, the model-er. A reasonable assumption, as always, would be a Gaussian, but this may change according to the problem at hand. The choice of the jumping distribution will change how you walk, of course, but it an arbitrary choice.
Now, the core of Metropolis-Hastings is the choice of $\alpha$. You can think of $\alpha$ as the way you control the sampling procedure. The main idea behind MCMC is that in order to estimation an unknown distribution, you 'walk around' the distribution such that the amount of time spent in each location is proportional to the height of the distribution. What $\alpha$ does is ask, 'compared to our previous location, how much higher/lower are we?' If we are higher, then the chance that we pick to move to the next point is higher, and if we are lower, then it's more likely that we stay where we are (this refers to Step 3 from the algorithm you reference). The precise functional form of $\alpha$ can be derived, fundamentally, it comes from the condition that we want our final distribution to be stationary.
Next, let's discuss your final question. Generally speaking, this notion goes beyond Metropolis-Hastings, you should google 'rejection sampling.' If you've heard of that, that's all this is. This is to ensure that you've fully explored the distribution, and don't get 'stuck' in one place.
Hopefully this has given you some greater intuition behind the algorithm. I do recommend spending some time delving into the math, my approach is very casual, focused on interpretability. Though the math can be intimidating, it's the best way to build intuition. Perhaps looking at a software implementation may help. As always, The Elements of Stat. Learning and Bishop are great references, and there are a plethora of online resources you could fine to further your understanding. cheers!
Comment: You could find a lengthy derivation on wikipedia, or a more constructive argument in Bishop, chapter 11.2. This resource [here](https://ermongroup.github.io/cs323-notes/probabilistic/mh/) gives a more concise proof.
Comment: Could you throw some light on how the exact functional form of $\alpha$ can be derived, starting with that the final distribution must be stationary?
Comment: @cogito_ai:  Whenever I've had to re-understand it, I've always used this paper as my go to explanation. There might be something better now ( such as recommendations above )  but I always found it enlightening. http://web1.sph.emory.edu/users/hwu30/teaching/statcomp/papers/chibGreenbergMH.pdf


What is the theoretical explanation of D/F# chord in this turnaround?

Question: Here is the sequence in harmonic Am. What is the function of D/F# in terms of tonal harmony. Borrowed chord from parallel major? Chromatic inflection?
Am-D/F#-F-E-A
Comment: It doesn't matter. There is no "theoretical explanation" There is a functional explanation which is ultimately whatever you you can come with that "makes sense" and ideally is as simple as possible. Clearly in harmonic minor the iv chord is a IV chord and this is just an inversion to create a smooth chromatic bassline. In music theory, theory doesn't come before music it comes after. Don't confuse the map with the territory as it will get you nowhere.
Comment: @Gupta it certainly doesn't matter _in some contexts,_ but that doesn't mean that we should abandon attempts to create theoretical frameworks to explain music.  While it's true that a lot of theory is developed descriptively, that doesn't stop it from being used prescriptively by subsequent composers -- who then innovate to the point that the theory needs to be changed in order to describe their music.  But still, composers do typically write music with a preconceived set of theoretical rules describing what "makes sense."
Comment: Is the last chord A or Am?
Comment: @phoog What makes "sense" is relative. In an insane asylum such as the US government what makes sense is entirely different, than, say a farmer who has to grow his own food to survive. Sure there is some common underlying "logic" but it is very small relatively to most of the artificial rules created by men. For example, much of music pre-cpp was founded on religious "theory" such as 3 and 7 is the perfect number. This then shaped everything to come afterwards but really had nothing to do with actual foundations of music.
Comment: @phoog "Theory" is only used to give us a walking cane because we are blind. It helps guide us imbeciles in to being able to accomplish something. The more "gifted" we are the less theory we need. There are some great musicians who know no formal theory.  Theory as we know it, formal theory, is just for communication. Music theory is not a theory in the sense of a mathematical theory except for nomenclature(naming chords and the taxonomic topological structure of "music theory" is relevant). 95% of the "rules" of theory is BS.
Comment: @phoog What modern "music theory" gives us when it describes functional progressions, for example, is not a theory but a documentation of what certain cultures and masters did. It doesn't tell you what should be done unless you want to sound like them. I'm not saying theory is bad but one must always temper it's conclusions so one doesn't fall into the myopic trap of thinking theory = reality.
Comment: @phoog for example, many of the rules for counterpoint, while some based entirely on logical reasons, produce a certain sound. If you follow those rules you will get that sound. If you want a new sound you must change the rules. Much of contemporary music has to break the rules("theory") to have created a new sound. E.g., take Jazz... If Jazz used the classical rules it would not be Jazz.  The point here is that music theory should not be taken as some absolute rule-set that one cannot break. In fact, learning theory should come after learning music.
Comment: @Gupta other than the role of 3 in mensuration theory, I don't see much evidence for a preference for 3 or 7 driving music theory.  It's more that they got excited when the number 3 or 7 turned up than that they did things based on those numbers.  Do you have any evidence to the contrary?  I'd be interested to see it.  "There are some great musicians who know no formal theory": not from the common practice period!  "theory should not be taken as some absolute rule-set that one cannot break": absolutely.  But it's also a useful tool for people learning to compose, if not an indispensable one.
Comment: @phoog Surely you realize the important of 3 in 7 in the Christian religion? No doubt then it would shape Christian music. Music is far more cultural than mathematical. "Meter in Music" by Houle goes rather deeply in to the discussion of ternary meter as do several other books. I believe Kent Kennan's Counterpoint book also discusses it. Most books that discuss historical music usually at least touch on this aspect. Most (western) pre-cpp music was written in ternary as most music.  "A History Of Musical Style" by Crocker also discusses it in depth.
Comment: @phoog As far as what musicians new about theory in cpp isn't debatable since there is no way to prove either side. Clearly though the best musicians are the only ones remembered and generally have any historical record. Also, modern theory is based on the *COMMON PRACTICE* of those musicians and was not a theory at the time. The theory as we know it is much different than what they new(although some of it hasn't changed at all).  Given that many cultures form their own musical sense and their "theories" are different suggest that theory is not as relevant as you seem to think.
Comment: @phoog What is more important is to immerse oneself in music to develop a coherent personal understanding of how music works. The greats all did this or they wouldn't be great. There are many musicians today who are known to not have any understanding of "music theory" but create good music. I'm sure the same was true back in CPP. Of course not knowing theory might limit their abilities but theory can also hinder people who think they have to create music "by the numbers".
Answer: It's just a predominant (IV) chord borrowed from A major. It serves the same harmonic function as the F (bVI) chord that follows, but allows for the creation of a chromatic bass line F#-F-E leading to the dominant (E) chord.
Comment: Does Dekkadeci's answer negate this one?
Comment: @Tim No. It's a difference in how theorists consider the basis of the major IV chord in minor. But regardless which point of view one adheres to, it's still a predominant function chord, and it still participates in a chromatic descending bass line. The debate over the theoretical basis of the major-IV's origin doesn't impact it's function within the chord progression.
Answer: The D/F♯ chord is a IV6 chord in A minor.
While the IV chord in a minor key does often end up sounding borrowed in practice, my Royal Conservatory of Music Harmony lessons all said that IV in a minor key does not count as borrowing from the tonic major, as IV is already a fully acceptable chord in minor keys.
Comment: Due, I guess, to the existence of the melodic minor scale.
Comment: @Tim I'd say it's the other way around: the melodic minor scale exists because composers routinely used the major IV chord (i.e., raised scale degree 6) in minor.
Comment: @Aaron - or - were they thinking more in Dorian mode..?
Comment: @Tim I don't know the history well enough, but it certainly seems plausible that the raised sixth in minor was a holdover from dorian.
Comment: I have to say, the "fully acceptable" argument doesn't convince me.  Is V is a first-class citizen in minor or borrowed from the parallel major?  What about V/V?  Or should that be V/v?  Is any chord somehow not "fully acceptable" in any key?  What criteria do they use to decide which are or aren't?
Comment: @phoog - My RCM lessons said that V is a first-class citizen in minor keys, while V/V is not. Only cases like the Neapolitan (bII) were shaky.
Comment: @Dekkadeci I figured as much, but why?  Is it because they consider that there are 9 "acceptable" pitch classes in a minor key (namely seven diatonic to the natural minor plus raised ^6 and ^7)?  I just don't find that convincing as a useful distinction.  But then again I never found the concept of "borrowing" to be particularly helpful.


Rails Bootstrap Active class with ordering

Question: I'm trying to implement the bootstrap active class to my navigation links but currently it's not working with my ordering in rails. The class is supposed to be applied when the clicked link matches the current URL.
This is the URL when the ordering is set
http://localhost:3000/posts?order=hot

But it's not actually applying the active class, as I'm guessing it's the '?' that's breaking it.
var url = window.location;
// Will only work if string in href matches with location
$('.sorting ul li a[href="'+ url +'"]').parent().addClass('active');

This code doesn't seem to be working with the '?'. From this question here
Comment: When you click the link, does it reload the whole page, or is this done dynamically?
Answer: As you're reloading the whole page (as mentioned in the comment), you could skip the Javascript altogether, and do something in the view like (HAML example, let me know if you need an ERB example);
%li
  %a{href: '#', class: "#{'active' if params[:order] == 'hot'}"}
    Link text here

This will read the GET parameter (?order=) from the URL, then add the active class to this a tag, if it is set as hot.
The Javascript example in the Bootstrap docs is how you would do it if you were dynamically updating the content.
Edit: and here's the untested ERB version;

  <a href="#" class="<%= if params[:order] == 'hot' %>active<% end %>">
    Link text here

Comment: Don't use `<%= %>` inside another, use `"#{ }"` instead. `<%= %>` identifies whats inside it as Ruby, so, put simply, it won't nest!
Comment: ERB would be brilliant - you knew it would happen! ;)
Comment: Have added an example! Let me know how you get on!
Comment: <%= link_to posts_path(order: :hot), class: "<%= if params[:order] == 'hot' %>active<% end %>" do %>
            Popular
          <% end %>
Comment: That is throwing a huge error in my face. 'index.html.erb:10: syntax error, unexpected '<', expecting keyword_end  ^ '


What is the standard procedure for evaluating a user-based CF algorithm with a dataset offline?

Question: I have read some papers and other materials about the evaluation of recommender systems (RS). Most of them discuss the various properties of RS (e.g. accuracy, diversity, etc.), and metrics for different tasks (e.g. RMSE, precision, recall, etc.), and some protocols. But I am still not very clear about data partitioning and the detailed validation procedure. [Shani, Guy, and Asela Gunawardana. "Evaluating recommendation systems." Recommender systems handbook. Springer US, 2011. 257-297.]
For example, I want to evaluate a basic user-based CF algorithm with rating feedback. The data format is user-item-rating. There're 100 users in the dataset. Now I want to use 5-fold cross validation method. This is my way:

According to users, I randomly separate the original dataset into 5 folds. Each fold contains 20 users.
For all users I set one same time instant, so that before and after this time instant, each user contains a number of ratings. The data of any user x before the instant is for creating user profile, the data after the instant is for validating rating prediction (user x as user being predicted) or just being hidden(user x in neighborhood selection).
For each user i in all 5 folds, I create a user profile represented by rating vector{} for user i.
For fold-1, for each user i in fold-1 I calculate user similarities between user i and the users in the fold-2 ~ fold-5, and set an appropriate value of k-NN to obtain the neighbourhood for each user.
For each user i in fold-1, I get predicted ratings from his neighbourhood users (items no t used by the tested user) by an appropriate rating averaging equation.
calculate prediction error for user i.
Repeat step 2~6 for each fold (5 times all) and get the average prediction error. This is one round.
Use different parameter combinations(e.g. k-NN neighborhood size), repeat step 2~7 with many times, so as to obtain the lowest prediction error (meaning best parameter combination).
With the best parameter combination, I get the lowest prediction error, and this is the final evaluation result.

I have two questions:

Is this procedure correct for evaluating a user-based CF algorithm?
If so, what are the specific data in this procedure corresponding to the concepts of "training set", "testing set" and "validation set" from Statistics?
Comment: a well formulated question plus showing the amount of research you have already done. Wish more questions would be like that one.
Comment: I really enjoyed your question and the way you asked it.. every line was useful..
Answer: Regarding "The three sets"

training set: The users in the training folds restricted to the ratings before the split date. This data is used to build the model.
validation set: The users in the validation fold restricted to the ratings after the split date. This data is used to evaluate the model.
testing set: The users put aside beforehand (currently not happening in your setup), restricted to the ratings after the split date. This is done in the following way:

Use all data in the training and validation set to build the model (restricted to the ratings before the split date)
Calculate the neighborhood using the user data in the testing set before the split date and calculate the error using the ratings after the split data (standard procedure)

The important point is, that the testing set is used to evaluate
what the generalization error and quality looks like when put into practice (after all optimization has been done). If the quality at this step is
strongly inferior to the one obtained in the validation set, overfitting has slipped in.
See also this question: What is the difference between test set and validation set?
Regarding inner vs outer crossvalidation
The inner crossvalidation is used to optimize the so called hyperparameters (http://en.wikipedia.org/wiki/Hyperparameter_optimization) like the neighborhood k.
It is done by splitting the training set again. The outer crossvalidation is used to evaluate the generalization power and error of this optimization.
See also this question: Nested cross validation for model selection
Now one may ask: Why resplitting the training data ? Why not just say that

the training part of the inner crossvalidation corresponds to the training set
the validation part of the inner crossvalidation corresponds to the validation set
the validation part of the outer crossvalidation corresponds to the testing set

One can do this. But given this split without any data put aside beforehand, one must be careful not to e.g. rerun the outer crossvalidation with different settings,
because in this case you do not have untainted data to use for the final estimation of the generalization power and error.
Regarding the validation procedure ignoring the testing set and hyperparameter optimization argument
Basically, the validation itself is good and valid ! Splitting the users into  folds varies
the mixture of interests present in the training data meanwhile splitting every user profile
at a certain date takes timely aspects like "new items coming in" or "what is hot a the moment" etc.
into account.
Some thoughts based on my own experience ...
Repetition of the (outer) crossvalidation
You may repeat the crossvalidation with different user and rating splittings without varying the hyperparameters
of the model to gain a more reliable estimate of the generalization error. Beware of repeating it not to often
(I recommend 6-10 based on Kohavi's analysis of crossvalidation), since the more repetitions, the higher the probability
that the same type of split occurs again.
Contemplation: Drop the splitting at a date ?
One suggestion: Splitting at a certain date has the disadvantage that the amount of training data and validation data may vary heavily across users, depending on their levels of activity. Distinguishing between these types of users may help to first build a good recommender, then make it work for small amounts  of data, too.
To account for this one can ...

either do not use users for validation where the amount of training data is to small.
drop the splitting at the date and split the ratings randomly (e.g.2/3 / 1/3  or something like this). This is  only appropriate for items with less dynamics (books, movies) then items with a high dynamics (fashion). To somehow balance this, myself has restricted the validation to items which occurred at least once in a certain time frame (e.g. a month). The time frame is chosen based on the dynamics of the items, i.e. it represents the time frame where the item / rating occurrences can be considered as stable.

Contemplation: Drop the splitting of users ?
When the recommender system is applied in practice, all users with activity up to the launch date are known. So splitting the users in such a way that some are put into the training folds and other in the validation folds is not very realistic. It would be more realistic to just split the ratings per user at a certain date or just random (2/3 / 1/3), using all data from all users in the training part of the split for building and the rest for validation accordingly.
HOWEVER, the only difference to the user-and-rating-splitting is, that the rating-splitting-only can utilize the ratings of the user in the validation fold before the date split. So all in all not much of a difference. The user-and-rating-splitting makes the model training a little bit harder, but forces more stability on the other hand. It is some sort of regularization.


Unable to locate element using Selenium Chromedriver when it's there in C#

Question: I am trying to get my program to click on a button however I receive errors.
My code:
driver.FindElementById("couponsinc-gallery-selectall").Click();

Error:
An unhandled exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll
no such element: Unable to locate element: {"method":"css selector","selector":"#\couponsinc\-gallery\-selectall"}

Here is the code of the button on the page:

            <input type="checkbox" class="selectall-chk" id="couponsinc-gallery-selectall">
            Clip All

I've also tried my using FindElementByClassName but nothing is working. What am I doing wrong?
Answer: The checkbox with text as Clip All an  so you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use either of the following Locator Strategies:

Using CSS_SELECTOR:
((IJavaScriptExecutor)driver).ExecuteScript("return scrollBy(0, 800);");
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.CssSelector("iframe[title='Coupons']"));
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("input.selectall-chk#couponsinc-gallery-selectall"))).Click();

Using XPATH:
((IJavaScriptExecutor)driver).ExecuteScript("return scrollBy(0, 800);");
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.XPath("//iframe[@title='Coupons']"));
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[@class='selectall-chk' and @id='couponsinc-gallery-selectall']"))).Click();

Browser Snapshot:

Reference
You can find a couple of relevant discussions in:

Ways to deal with #document under iframe
How to wait for a frame to load before locating an element?
Comment: Awesome! The solution seems to work and I've marked it as the soltuion but I still don't understand why my simple code doesn't work as it definitely worked for a different button on a different website.
Comment: I've tried this and have gotten this error: OpenQA.Selenium.WebDriverTimeoutException: 'Timed out after 20 seconds' with the same inner exception: NoSuchElementException: no such element: Unable to locate element, here is the website: https://www.keyfood.com/store/keyFood/en/printable-coupons, you can test it for yourself, it's the "Clip All" button near the bottom of the page.
Comment: @africohal Checkout the updated answer and let me know the status.
Comment: This time I got this exception: OpenQA.Selenium.WebDriverTimeoutException: 'Timed out after 20 seconds' followed by this inner exception: InvalidSelectorException: invalid selector: An invalid or illegal selector was specified which occured on this line: new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("//input.selectall-chk#couponsinc-gallery-selectall"))).Click();
Comment: @africohal My bad, it was a typo, fixed it, please check now both the locators and let me know the status.
Comment: @africohal I tried my best to provide you all the reference in the form on embedded links. Happy coding


Western vs Indian Carnatic style of violin playing

Question: I am a trained Indian Carnatic style violin player. Can I play Western songs on a violin with carnatic fingering techniques or do I need to re-learn everything to adopt to the Western style?
Comment: @ggcg it doesn't help you because you're not familiar with carnatic violin technique...  What do you want from them?  A rundown of the entire tradition and technique of south Indian classical violin playing?
Comment: You might have a question like "how difficult is it for a classical guitarist to attempt to play the blues", and you wouldn't expect that person to outline everything that classical guitar technique consists of in order for it to be a well-asked question; it's just understood that if you don't know something about classical guitar playing and about blues guitar playing that you won't be able to answer the question...
Comment: Help us help you.  What specifically is carnatic fingering.  I am familiar with carnatic scales, which do seem to be based on chromatic scale, 12 equal tones.  Can you verify that.
Comment: @ggcg just asking the generalised idea here . i.e how difficult is for Indian Carnatic style violin player to play western music.
Comment: That doesn't help
Comment: @ggcg I know this was two years ago, but no, the carnatic _raga_ (not scale) is based on many things. Please see my answer down below.
Answer: You can play western songs with the fingering techniques of carnatic violin if you are skilled enough to give up the traditional basic finger positions to follow. If you can play any notes with any finger spontaneously this is possible either to play carnatic music in western violin or western music in carnatic violin. The challenge is when it comes to the continuity of notes from third string to the second string. In carnatic way of tuning, the strings are Sa, Pa, Sa, Pa in the order of strings 4,3,2 and 1. Same swaras in the next octave is arranged for strings 4 and 3 in 2 and 1 respectively.  But in Western way of tuning, it is G, D, A, E. This difference exist because the fourth note (third finger) in the third string is same as the first note (without finger) in the second string for Carnatic violin. But it is the fifth note (fourth finger) in the third string for Western violin that is tuned same as the first note (without finger) in the second string. These become confusing for a beginner if to try both together when you start learning. Once expertise in either of the style first and then learning the other style afterwards will provide some stability. However, once you master the basic finger chart and go beyond to attain a freedom of fingers to play any note with any finger, it will be easy.
Edit: One easy workaround is to use 'D' string (third) as base swara for 'Sa'. In this way we are able to play 'Sa' on the third string of western violin and 'Pa' on the second string. By doing this, we can have one complete octave (and another half octave if the higher second positions played in this new second string 'pa' up until the higher 'pa'). This leave us with the option of only two strings to play Carnatic music on western violin. However, we can have one more string if we slightly adjust the fourth string as the lower 'pa'. Here the fourth string has to work as the third string of Carnatic. Now it adds half octave below too. Usually most of the songs require this much range of pitch only (most of the humans sing within these). The flute is having this much range only. But remember that this is just a workaround. Even if we get the 'pitch' equal, may be we have to compromise the 'tone' when it is significant for some particular pieces/songs (because we are using a thicker strings for 'Sa' and 'Pa'). Although it is okay for just simple play if we ignore tone, etc. If it is 5 string violin, we can dedicate separate strings for the G of western and Pa of Carnatic rather than changing the pitch each time. Then it would be like G, Pa, D, A, E.
Answer: If you already play a very difficult music style, I think to pass to western music will be easier for you. The only difficulty will be to adapt to this other system with different "rules".
Watch this video,
If You Can Play Carnatic Music, You Can Play Anything | Akkarai Subhalakshmi | Music of India:


Alterar o .NET Frameworks aplicação

Question: Desenvolvi um app em c# usando o sqlite. Porém ao compilar e instalar em outro computador com o OS XP, deparei com o seguinte erro:

CreateProcess falhou cod. 193 %1 não é um aplicativo win32 válido

Ao pesquisar no google, pude verificar que o problema estaria no .NET Framework que foi desenvolvido na versão 4.5. Alterei para o 3.0, mas deu conflito ao executar diretamente pelo meu VS 2013, mostrando alguns erros de Linq, etc. ) meu computador é o OS Windows 8.
Existe outra forma de fazer essa alteração para que funcione no XP?
Obrigado
Comment: Windows XP é um problema mesmo e será cada vez mais. EU nem acredito que as pessoas tem coragem de usá-lo ainda. Não sei dizer muita coisa, mas vai ter que usar tudo para versões antigas do .Net, talvez tenha que pegar versão antiga da DLL do SQLite, talvez tenha que evitar certos códigos que usam recursos não disponíveis nas versões antigas de todas as DLLs.
Comment: O Windows XP já foi até descontinuado. Não sei se vale a pena escrever um sistema pra algo tão antigo.
Comment: Posso estar enganado, mas acho que não. Se você desenvolveu com o .Net framework 4.5 a aplicação precisa rodar nessa versão ou em uma maior.
Comment: Certo. Porém ao começar a desenvolver a app, não me atentei a esse detalhe e o computador onde será instalado o programa usa o XP. Tentei mudar o .NET Framework, mas deu problema ao executar na minha máquina. Teria algum outro modo sem dar conflitos?
Comment: Desculpe bigown, estava digitando quando você postou sua resposta ; ) É verdade, somente o computador da recepção tem esse XP. Já pedimos para trocar, mas até agora nada.
Answer: O Linq foi introduzido na versão 3.5 do .Net! Tente portar sua aplicação para essa versão do framework, que também é compatível com WinXP.

Alterar o .NET Frameworks aplicação


Running through if/else statement and getting lost

Question: I'm having a brain dead moment and getting lost in my logic, please can someone help!
I'm looking to recreate 3 scenarios:

If downloads AND resources exist.
If only downloads exist.
If only resources exist.

These are decided by the two statements:
Downloads = have_rows('downloads')
Resources = get_sub_field('resources')
How can I run through the 3 scenarios in an if/else loop?
Comment: Maybe you can edit your title if/else is not a loop it's a control structure
Answer: $downloads = have_rows('downloads');
$resources = get_sub_field('resources');

if($downloads && $resources) {
  // do something
} elseif($downloads) {
  // do something else
} elseif($resources) {
 // yet another something else
}

Answer: If I correctly understood your question
if(have_rows('downloads') && get_sub_field('resources'))
{
//some stuff
}
else if(have_rows('downloads'))
{
//Some other stuff
}
else if(get_sub_field('resources'))
{
//More stuff
}

Answer: Something like this???
$bDL = have_rows('downloads');
$bRE = get_sub_field('resources');

//  If downloads AND resources exist.
if ($bDL && $bRE){

}

// If only downloads exist.
if ($bDL && !$bRE){

}

// If only resources exist.
if (!$bDL && $bRE){

}

Comment: I know, but readability is much better. I avoid nested if/then/else/elseif's whenever possible.
Comment: nested if meaning is a little bit different from what you have mentioned. nested if's are those which are actually "nested inside" other if's and I agree, in this case it could be not very good practice [http://php.net/manual/en/control-structures.if.php](http://php.net/manual/en/control-structures.if.php)
Comment: Yes, but even a few if's isn't that bad (programmers can read that easily). Personally I just like to read an if-statement, almost as if it was plain English. Matter of taste I guess.


Performance vs readability: multiple selectors vs. multiple statements in jQuery/JS

Question: I'm writing some jQuery code that hides or displays numerous table columns from a large table at the same time.  I wanted to know if it would be faster to use code like this:
$("selector 1, selector 2, selector 3").css("display", "none");

or code like this:
$("selector 1").css("display", "none");
$("selector 2").css("display", "none");
$("selector 3").css("display", "none");

So I used jsperf.com to create a performance test case.  With that I established that the first type of code (which uses one long string with multiple selectors) is faster than the second type of code (which hides columns one at a time) by about 53%.  However, by the time I'm done writing it, it will be borderline unreadable, looking something like this:
$("#table tr *:nth-child(4), #table tr *:nth-child(5), #table tr *:nth-child(6), #table tr *:nth-child(7), #table tr *:nth-child(8), #table tr *:nth-child(9), #table tr *:nth-child(10), #table tr *:nth-child(11), #table tr *:nth-child(12)").css("display", "none");

So my question is, which is the greater evil for jQuery/JS code--inefficient performance, or lack of readability?  My background is in Python so I tend to value readability above performance, and 53% doesn't seem like a huge drop-off in real world terms.  But on the other hand, I plan to minify my JS code once I deploy it, so it will end up not being readable anyway...though I know there are de-minifiers out there that can return my code to its original readable or unreadable form.  As you can see I can talk myself around in circles on this topic, and I'm not looking to start a debate or discussion, so I'm just posting this here in case there's a generally accepted way of handling this in the jQuery/JS community.
Answer: You could store the selectors in an array, then join them when needing them:
var selectors = [
    "selector 1",
    "selector 2",
    "selector 3"
];
$(selectors.join(", ")).css("display", "none");

The reason your long selector works is because only one jQuery object is created, and only one browser method could be called, improving speed. I'm guessing document.querySelectorAll would be used, and can be passed that whole selector and return results. While jQuery would be calling n number of document.querySelectorAll methods for n number of $().css calls.
Another option, is to use the .add method to "improve" readability:
var selectors = $("selector 1");
selectors.add("selector 2");
selectors.add("selector 3");
selectors.css("display", "none");

Although I'm sure this will be faster than the multiple selector/css statements, it won't be as fast as document.querySelectorAll's capability with one big selector.
Comment: Your first method seems very similar to @elclanrs's, but has noticeably better performance. In fact it performs even better than my original single statement with the long selector.  I wonder why?
Comment: @GChorn Haha that makes no sense (why it's faster than your original). Mine basically **produces** your original. But with the storage in an array and having to call `join`, I would only think it could be slower. elclanrs's solution is a little more complex; I was just trying to store/retrieve the selectors in a different way.
Comment: Oops, yeah I just noticed that when I benchmarked the two methods I gave the list variable two fewer selectors than in the original statement.  Now they're testing about the same.
Answer: Maybe you just have to think about alternative ways to write that code and have both worlds. For example:
var nth = [4,5,6,7,8,9,10,11,12];

$('#table tr *')
  .filter(':nth-child('+ nth.join('),:nth-child(') +')')
  .css('display', 'none');

Comment: Interestingly, upon benchmarking I found that this method is actually slower than the multiple-statement method.
Comment: I think you might be testing wrong...Use the "setup" field to define your initial variables otherwise you're introducing the creating of the array in the test as well. I tried in a bunch of browsers and this is way faster than multiple selectors. http://jsperf.com/6b11404dd2f0
Comment: The weird thing is, when I tested @Ian's version without the variable setup against the single-statement-with-long-selector version, they performed about the same.  When I did that with yours, it was much slower.  But when I tested your version against Ian's directly, it was slightly faster.  This was all without pre-defining variables.  But you're right, in my actual code I can define the variable just once, and if I do that in jsperform both of your guys' code is much faster than the multiple-statement one.  Anyway thanks!
Answer: It should probably depend on how often that code gets hit (is it run once during the life of a page? is it attached to a timer or click event or something that could cause it to fire multiple times?)
I would always favor readability over efficiency UNTIL/UNLESS you identify that a certain bit of code is a bottleneck and needs to be optimized. Remember the classic programming lesson about premature optimization.
Also keep in mind your jsperf test might vary wildly across browsers and clients (especially old IEs and mobiles). Sometimes you'll see a drastic performance difference even between the latest versions of Firefox and Chrome due to differences in ECMA implementation!
Finally, a 53% difference sounds like a lot expressed as a percentage, but look at the times in ms and determine for yourself if this could be a potential bottleneck for the app.
Answer: Definitely value readability above performance. After all you are using JS. That said you can increase the performance in readable ways as well. e.g. generating this selector with a more understandable for loop instead of an inline huge string.
Additionally with minification you should not overwrite your code. For any modifications you would still go back to your non-minified version, edit it, and minify again. The minified code is for the browser not human eyes. So any comment about its readability is irrelevant.


hook_ENTITY_TYPE_insert never called

Question: Initially I wanted a list of Authors in an exposed filter (as a checkbox) but after looking into BEF (better exposed filters) it seems this isn't possible.
Instead I am trying to create a taxonomy term for each user created but have found regardless of what entity I am trying to create, the hook for insertion is never called.
I am using xdebug and was expecting at least a single breakpoint inside one of the functions to work but it never triggers, I have cleared my cache and other preprocessing functions inside this file (bare.theme).
A few examples of functions I have tried (my theme is called "bare"):
<code>function bare_entity_insert(Drupal\Core\Entity\EntityInterface $entity){}

function bare_user_insert(\Drupal\user\UserInterface $user) {}

function bare_entity_create(Drupal\Core\Entity\EntityInterface $entity){}

function bare_user_create(\Drupal\user\Plugin\Core\Entity\User $user){
</code>
I feel I have missed something very crucial, perhaps I can't call these functions inside a .theme file?
Answer: Yes if you're trying that in a theme then it won't work and will need to be done in a module (Obviously changing the "bare" to whatever your module name is)
Comment: Thank you, this has caused more anguish than its worth.

hook_ENTITY_TYPE_insert never called


Make footer stay at bottom without body { height: 100% }

Question: If I set html,body { height: 100% } for my template, something weird happens. Its difficult to describe and also not possible to recreate the problem in a fiddle because it happens only at localhost. When I tried saving the page and then ran that page, the problem disappeared.
This is my problem:
I am trying to make the footer stay at bottom of my page if content doesn't fill the page, but if content overflows the page along y, footer should be at bottom of content, ie behave like a normal element.
I tried doing this:
html, body {
    height: 100%;
}

body {
    position: relative;
}

footer {
    position: absolute;
    left: 0; bottom: 0;
    width: 100%; height: 60px;
}

This does work, but gives me a slight delay. When I refresh the page (when content not overflowing) the footer is at end of content not at bottom of page, as expected. But after about 0.5s, the footer goes at the bottom.
I have a CSS switcher button at bottom of my page, and when I use it, footer doesn't show this weird behaviour. So I think this is not CSS's fault. Also saving the page using ctrl+s and then running that saved page doesn't show this problem, so it probably is because of Django.
Here's my code: fiddle and here's a RAR of that saved page: dropbox
Comment: It's HTML/CSS issue. If it's not working right, then maybe the styles are overlapping. Use the `Inspect Element` feature of your browser to check. It can only be Django issue if the style tags or css files are not loading right.
Comment: Use `min-height` style in `.book-container`
Comment: @mshsayem I can't use `min-height` as it won't work on all resolutions.
Comment: @Bibhas if it is HTML/CSS problem, then why isn't it happening in saved page?
Comment: Do you want [sticky footer](https://www.google.co.in/search?q=sticky+footer)?
Comment: @Sourabh saved page can break things in so many ways for a dynamic website. I don't know why you're doing that. When you save the page, maybe some 3rd party style fails to load, something that was colliding with your style. Or maybe you're loading some styles dynamically which are unavailable in saved page. So many other things can go wrong. Inspect and check.
Comment: And if it's a Django problem, there is absolutely no way for us to understand that from the given code.
Answer: Apply a min-height to your container div && apply a padding-bottom to your body div that matches the height of the footer.
jsFiddle

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
#container {
   min-height:100%;
   position:relative;
}
#header {
   background:#ff0;
   padding:10px;
}
#body {
   padding:10px;
   padding-bottom:60px;   /* Height of the footer */
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;   /* Height of the footer */
   background:#6cf;
}

Comment: the problem occurs if `body` has `height: 100%` so this doesn't solve the problem. Also, making `container { height: 100% }`, which is `book-container` in my case, makes it as long as `body`


If $f: \mathbb{R^{N}} \rightarrow \mathbb{R}$ is a differentiable function and $f(0)=0$ then...

Question: ... prove that there exist functions $g_{i}:\mathbb{R}^{N} \rightarrow \mathbb{R}$ such that
$$f(x)= \sum_{i=1}^{N} x_{i} g_{i}(x).$$
Well, my fist attempt is to use linear algebra and think of the functions $g_{i}$ as a base. Then I need to prove these function generates the set of the codomain of $f$ and also that they're linear independent, and here is where I use the fact that $f(0)=0$.
But I not sure how can I use the fact that $f$ is differentiable. Maybe saying that is a linear transformation that is continuous.
Answer: We have: $f(x)=\int_0^1df(tx)dt=\int_0^1\sum_{i=1}^{i=n}x_i{{\partial f(tx)}\over{\partial x_i}}dt$.
Write $g_i(x)=\int_0^1{{\partial f(tx)}\over{\partial x_i}}dt$.
Comment: So you are saying that we can understand $f(x)$ as the sum of it's partials?


Como plotar um gráfico de linha com cores diferentes dependendo do valor?

Question: Suponha os seguintes dados:
set.seed(1)
y<-rnorm(101)
x<-seq(from=0, to=100,by=1)

Quero fazer um plot com uma linha que tenha cor diferente para valores negativos.
Para fazer um gráfico de pontos basta o comando abaixo:
plot(x,y,col=ifelse(y>0,"blue","red"))

No entanto, se altero para um gráfico de linha não funciona.
plot(x,y,col=ifelse(y>0,"blue","red"),type="l")

Se tento fazer com o ggplot2 também não está dando certo. Ele atribui ao segmento da linha a cor do ponto anterior.
library(ggplot2)
df<-data.frame(x,y)
df$cat<-y>0
ggplot(df,aes(x,y,color=cat)) + geom_path(aes(group=1))

Como fazer para o R atribuir corretamente a cor vermelha para valores negativos e cor azul para valores positivos no plot de linha?
Answer: Uma "solução" parcial seria gerar um spline com muitos pontos (uns 100 por exemplo) que aí as cores teriam menor probabilidade de ficarem em lugar errado.  Mas essa solução pode gastar muita memória se sua base de dados for grande e vai suavizar o gráfico. Ex:
df2 <- data.frame(spline(df$x, df$y, n = 100*nrow(df)))
df2$cat <- df2$y>0
ggplot(data = df, aes(x, y))+ geom_line(data=df2, aes(color=cat, group=1))


Get the coordinates of the toggle button of the switch widget

Question: I'm using this to get the x & y coordinates of the switch:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    int[] location = new int[2];
    mySwitch.getLocationOnScreen(location);
    int x = location[0];
    int y = location[1];
}

This gives the x and y of the whole switch. How do I get the coordinates of the toggle button on the right hand side?

The whole switch is the yellow rectangle, but I'm trying to get the x, y of the toggle button that's circled with red.
Answer: Use addition.
Just get the width and height of the View and add the width to the x and add the height to the y.
Comment: I've looked at your image, and you could try `x + switch.getWidth() - switch.getPaddingRight() - (switch.getSwitchMinWidth() / 2)`. An alternative, since you have the rare requirement of needing the particular center of only the Switch, is to not use the Text field provided by the Switch. Instead, create your own TextView and place it next to the Switch where your image shows. Then in your code, use `switch.setOnCheckedChangeListener()` to toggle the text in the TextView you created. This way, the `switch.getWidth()` will be the proper width of just the Switch itself.
Comment: I've tried this and it doesn't give the exact x,y positions of the toggle button. After adding the width and subtracting the right padding, I'm getting the x,y of the right side of the toggle button. But I need the dead center x,y, of the button.
Comment: If you use padding, then you'll have to consider the use of subtraction too after getting the padding from `getPaddingRight()`.
Comment: I edited my previous comment and saw your answer only after the edit. I need the x, y of the center of the button.
Comment: If you're trying to get the center of the button, then you'll need division too. `x + (width / 2)`. The same is needed for the height. If your padding is only on one side of the view, you'll have to include the subtraction too for the padding.
Comment: I'm doing `x + switch.getWidth() - switch.getPaddingRight()` which almost works - it gives the location of the right limit of the toggle button. The toggle button is not on the center but is located on the right. If only I can get the width of the toggle button I can divide it by 2 and subtract from the calculation.
Comment: Have you tried `x + ((switch.getWidth() - switch.getPaddingRight()) / 2)`? But if it's the padding that's messing you up, does the layout you're using allow for margins instead of just padding? Padding affects the View itself, whereas Margins is how the layout affects the View. So if your layout allows the use of Margins, your switch.getWidth() will be the actual width of the toggle button.
Comment: I've edited the question and added an image to clarify what I'm trying to achieve.
Comment: Thanks for the hint. Have posted the answer.
Answer: Here's how I did it:
int [] location = new int [2];
Switch sw = findViewById(R.id.mySwitch);
sw.getLocationOnScreen(location);
int buttonX = location[0] + sw.getWidth() - sw.getPaddingRight() - (getResources().getDimensionPixelSize(R.dimen.switch_width))/2;
int buttonY = location[1] + (sw.getHeight()/2);

The default width of the toggle button seems to be approximately 50dp. getResources().getDimensionPixelSize(R.dimen.switch_width) was used so that we get the width in pixels based on the resolution of the screen.

Inside res > values > dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="switch_width">50dp</dimen>
</resources>


Can we validate text alignment on a webpage/Mobile App using Selenium/Appium

Question: Imagine that a mobile app or a web form contains 2 buttons "OK" and "Cancel".
As per the requirement, OK should be placed to the left side of Cancel button.
Ex:
OK     CANCEL
Is there a possible way to validate that Cancel button is present to the right side of OK button using Selenium/Appium.
Currently, I am manually validating this scenario by taking screenshot.
I am using C#.
Any suggestions or advises would be highly appreciated.
Comment: On iOS or Android?  What browser?  What display resolution?  Creating a one-size-fits-all solution will not be trivial IMHO.  You will likely have better luck with a commercial tool.
Comment: We usually perform testing on all three devices (a web browser, Android device and an IOS device.)
Answer: There is a location property on IWebElement which returns a point value.

Gets a Point object containing the coordinates of the upper-left corner of this element relative to the upper-left corner of the page.

So you could compare the 2 objects to see if the relative position of one element is to the left or right of another.


Plotting a skew ellipse

Question: I tried to make a geometers sketchpad toolkit for spherical geometry that is more exact (and easier to understand)  than the present available one.
but then I soon realised my background is not good enough so I need some help.
so my first (of a lot) of problems.
To plot a great circle
a great circle is an ellipse with:

the centre is at the origin (0,0)
the length of the semi-major axis is 1 (the ellipse touches the unit circle)
the length of the semi-minor axis is $h$ ($0  \le h \le 1 $ )
the angle between the (positive) x axis and the major axis of the ellipse is $\alpha $

What are the coordinates as a parametric function of the angle between the point, origin, X axis?
(I need get two functions x = some function (t) and  y= some other function (t) where $t$ is the angle x-axis, origin , point on ellipse.
Second problem
Given two points $A (a_x, a_y) $ and $B (b_x, b_y) $ in the unit disk's interior, then there is a unique ellipse that:

containins A and B.
the semi-major axis is 1,
the semi-minor axis is less than 1,
the arc of the ellipse from A to B does not meet the major axis.

What is the formula of this ellipse?
More to come but this will help me on my way (any references to books are very welcome)
Comment: There's no *need* to go to the third dimension; I agree with Andrew (having written such software myself several times over the last 40 years) that actually representing things on the sphere leads to far simpler code in general. But if you're sure that's wrong, go for it and do it in the plane -- it's not a whole lot more tougher.
Comment: To do spherical geometry, it seems you'd want to represent and compute with great circles (and points) in three dimensions, then project them to the plane, rather than plotting directly to the plane...? In any case, Patrick Ryan's [_Euclidean and Non-Euclidean Geometry_](http://www.worldcat.org/title/euclidean-and-non-euclidean-geometry-an-analytical-approach/oclc/12313703) may be worth a look.
Comment: no just a direct plot on the plane , no need to go into the 3rd dimension
Comment: First learn about  great circle orbit inclination... relation between longitude and latitude in spherical coordinates. Later about projections of point on principal planes.
Answer: Part 1:
\begin{align}
x(t) &= \cos(\alpha) \cos(t)  - h\sin(\alpha) \sin(t) \\
y(t) &= \sin(\alpha) \cos(t) + h\cos(\alpha) \sin(t)
\end{align}
I don't understand the question for part 2. Are the two point supposed to be on the ellipse? If so, then $h$ and $\alpha$ cannot be determined, because there can multiple ellipses at the origin containing the same two points. (Quick proof: draw a (non-circular) ellipse $E$ at the origin. Rotate it by 30 degrees to get another ellipse $E'$. Now look at $E \cap E'$. It will typically contain four points. If any two of these are called $A$ and $B$, then both $E$ and $E'$ are possible solutions to the "find $h$ and $\alpha$" problem, but the $\alpha$ values for $E$ and $E'$ differ by 30 degrees.
Post-comment remarks
The squared distance from $(x(t), y(t))$ to $(0,0)$ is
\begin{align}
d(t)^2
&= \left[\cos(\alpha) \cos(t)  - h\sin(\alpha) \sin(t)\right]^2
       +  \left[\sin(\alpha) \cos(t) + h\cos(\alpha) \sin(t)\right]^2 \\
&= \cos^2(\alpha) \cos^2(t)  + h^2\sin^2(\alpha) \sin^2(t)
   - 2h\cos(\alpha) \cos(t)\sin(\alpha) \sin(t)
       +  \sin^2(\alpha) \cos^2(t) + h^2\cos^2(\alpha) \sin^2(t)
   + 2h\cos(\alpha) \cos(t)\sin(\alpha) \sin(t) \\
&= (\cos^2(\alpha) +   \sin^2(\alpha)) \cos^2(t)  + h^2(\sin^2(\alpha) + \sin^2(t)) \sin^2(t) \\
&= \cos^2(t)  + h^2 \sin^2(t)
\end{align}
This varies from $1$ (at $t = 0$) to $h^2$ (at $t = \frac{\pi}{2}$). Hence one (semi-) axis has length $1$ and the other has length $h$. If $h < 1$, then the major (semi-)axis will have length $1$.
Note that at $t = 0$, we have
$$
\begin{align}
x(0) &= \cos(\alpha) \cos(0)  - h\sin(\alpha) \sin(0) &= \cos(\alpha) \
y(0) &= \sin(\alpha) \cos(0) + h\cos(\alpha) \sin(0) &= \sin(\alpha)
\end{align}
which is an angle $\alpha$ from the positive $x$-axis, as required.
It's possible that you still don't believe me, so here's some Matlab code:
<code>function y = ellipseTest()
hList = [0.1, 0.3, 0.7];            % three different eccentricities
alphaList = [20, 50, 130] * pi/180; % three different major-axis angles
t = linspace(0, 2*pi, 100);         % sample values from 0 to 2pi
colorList = ['r', 'g', 'b'];
figure(gcf);
clf;
hold on

for i = 1:3
   h = hList(i); alpha = alphaList(i); color = colorList(i);

    x = cos(alpha) * cos(t)  - h * sin(alpha) * sin(t);
    y = sin(alpha) * cos(t)  + h * cos(alpha) * sin(t);
    plot(x, y, color)
end
hold off;
set(gca, 'DataAspectRatio', [1 1 1]);
figure(gcf);
</code>
and the resulting figure:

I find these pretty compelling.
Note that each pair of ellipses intersects in two points in the first quadrant, so if you picked one of these sets-of-two-points for your part 2 question, you'd find two different ellipses that fit them.
Comment: thanks , but it looks incorrect ( the major axis is not fixed at 1) and the angle  also looks incorrect. For point 2 i need to think about that , something that the arc connecting them does not intersect with the major axis)
Comment: Can you say **why** it looks incorrect? I've added comments to show that in fact the distance to the origin varies from $1$ to $h$; if $h \le 1$, then the major (semi-) axis is indeed 1. (If you want the major axis to have length 1, then you need to include a factor of $1/2$ in both $x$ and $y$). I've also shown that this major axis point lies at an angle of $\alpha$ from the positive $x$-axis (again in the $h \le 1$ case).
Comment: Note that your suggest method to address my counterexample for part 2 doesn't actually work: Pick two points on the unit circle at, say, angles 40 and 50 degrees from the $x$-axis. You can find a whole family of ellipses of varying eccentricity, all symmetric about the $45$-degree line, that pass through those two points.
Comment: sorry i mixed up my cos and sins, sorry , about your counter example for part  2 only the unit circle connects them (for all all others ellipses  the major axis > 1) for points inside the unit circle i think  there are only two ellipse  that have  a major axis of 1 (and only one where the major axis is not between the two points. ps $h$  does not stands for the excentricity is stands for half the length of the minor axis, the length of the major axis is fixed) .
Comment: The ratio of the semi-axis lengths *is* the eccentricity; if $h > 1$, then the eccentricity is $h$; if $h < 1$, then the eccentricity is $1/h$. Your revised conjecture seem to be this: "Given points $A, B$ in the unit disk's interior, there's a unique ellipse with semi-major axis 1, and semi-minor axis no greater than 1, containing $A$ and $B$, and such that the each arc of the ellipse from $A$ to $B$ does not meet the major axis." Once you restrict to say that the segment $AB$ may not contain the origin, I suspect this might be true...at least dimension-counting  suggests that. Good luck!
Comment: Thanks  I will puzzle with it, sorry for all the problems, could you add the unit circle and the major axis to your drawing (makes it more clear what i mean )

Plotting a skew ellipse


How to add a trusted origin to gorilla websocket's CheckOrigin?

Question: I'm developing a websocket-based app where the frontend is in vue.js running on port 127.0.0.1:8080 and the backend is in golang running on port 127.0.0.1:3000.
The frontend is suppose to communicates to:
serverUrl: "ws://127.0.0.1:3000/ws",
To avoid CORS problem I had to return true for CheckOrigin:
var upgrader = websocket.Upgrader{
    ReadBufferSize:  4096,
    WriteBufferSize: 4096,
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

However I know that it is not secure bacuase this leaves the door open to any IP to connect to backed. My question is that how can I limit it so that it only allows request from 127.0.0.1:8080 ?
I've looked at the docs but could not find how to do so.
Answer: Return true from the CheckOrigin function if the origin is the trusted site.
CheckOrigin: func(r *http.Request) bool {
    origin := r.Header.Get("Origin")
    return origin == "http://127.0.0.1:8080"
},


How to model the effect of an intervention on survival times?

Question: I have data that includes the survival times as well as the times of an intervention.
I believe that the intervention will shorten survival times i.e. increase the hazard ratio for some time period following the intervention, after which the effect of the intervention will wear off.
I would like to find out whether this intervention increases the hazard rate, and if so what is the time-profile of the effect.
How can this be modeled most accurately?
Thanks!
Comment: Part III of Hernán, M. A., & Robins, J. M. (2020). [*Causal Inference: What If*](https://www.hsph.harvard.edu/miguel-hernan/causal-inference-book/). Chapman & Hall/CRC is devoted to counterfactual formal causal inference in longitudinal models, including survival time models. I suspect that especially of note for you in this book is **Fine Point 17.2: The hazards of hazard ratios** (tl;dr hazard ratios have no valid causal interpretation).
Answer: Usually when the question is whether an intervention affects the survival time, then time-dependent methods are generally required. The simplest case is when there is a single predictor, like an intervention. In this can one can use a Kaplan-Meier method to compare survival times between the interventions. If there are many predictors (e.g. age, gender, disease severity, etc...) then a regression approach is generally used and the most commonly utilized model is the Cox proportional hazards model (but it has some assumptions that you have to check).
For example, let's assume your data is in a file called mydata and looks something like this:

id
time
status
intervention

1
2
1
A

2
3
0
A

3
4
0
A

4
3
1
B

where
id - The variable identifying each subject
time - The follow-up time from the start of the intervention until an event occurs (i.e. death in your example) or last follow-up. For example, if you got your intervention on 1/1/2020 and died on 1/1/2021, your time would be 1 year or 365 days. If you got your intervention on 12/1/2020 and then study ended on 1/1/2021, then your time would be 31 days.
status - Indicates what happened at the follow-up time, 1 = death and 0 = censored (meaning the subject did not die and you don't know what will happen in the future).
intervention - The intervention (A or B in this example).
Ideally, you would have as many subjects as possible in your dataset. In R one would could fit a model to this using the survival package (there are many alternatives, but this is the standard go-to option).
fit <- survfit(Surv(time, status) ~ intervention, data = mydata)
This would generate a Kaplan-Meier type model of your data stored in an object called fit.

A classic example dataset in the survival library called aml and can be used to demonstrate using real data.
> library(survival)
> data(aml)
> aml
   time status             x
1     9      1    Maintained
2    13      1    Maintained
3    13      0    Maintained
4    18      1    Maintained
5    23      1    Maintained
6    28      0    Maintained
7    31      1    Maintained
8    34      1    Maintained
9    45      0    Maintained
10   48      1    Maintained
11  161      0    Maintained
12    5      1 Nonmaintained
13    5      1 Nonmaintained
14    8      1 Nonmaintained
15    8      1 Nonmaintained
16   12      1 Nonmaintained
17   16      0 Nonmaintained
18   23      1 Nonmaintained
19   27      1 Nonmaintained
20   30      1 Nonmaintained
21   33      1 Nonmaintained
22   43      1 Nonmaintained
23   45      1 Nonmaintained

There are 23 subjects in this dataset and the treatment/intervention is called x. We fit the Kaplan-Meier model.
> fit <- survfit(Surv(time, status) ~ x, data = aml)
> print(fit)
Call: survfit(formula = Surv(time, status) ~ x, data = aml)

                 n events median 0.95LCL 0.95UCL
x=Maintained    11      7     31      18      NA
x=Nonmaintained 12     11     23       8      NA

The output shows the survival time for each treatment arm. Maintained subjects have a median survival of 31 months and non-maintained have a median survival of 23 months. You can compare the plots of these survival curves.
> plot(fit)

Finally, you can test whether these curves are really different from one another using a logrank test.
> survdiff(Surv(time, status) ~ x, data = aml, rho = 0)
Call:
survdiff(formula = Surv(time, status) ~ x, data = aml, rho = 0)

                 N Observed Expected (O-E)^2/E (O-E)^2/V
x=Maintained    11        7    10.69      1.27       3.4
x=Nonmaintained 12       11     7.31      1.86       3.4

 Chisq= 3.4  on 1 degrees of freedom, p= 0.07

Read more on this and related topics:
https://www.datacamp.com/community/tutorials/survival-analysis-R
Comment: The question's author already appears to know about event history models, and appears interested specifically in *causal inference* in event history models. (Also: welcome to CV, Brant Inman!)
Comment: One additional and very useful exercise that might apply to the user's question is to examine the hazard function visually. In R this can be done using the `bshazard` and `muhaz` packages, among others. It is very interesting in many applications to understand how the hazard function is changing over time. This could inform the use of flexible models for the baseline hazard, like the Royston-Parmar model.


Prove that $p$ is prime in $\mathbb{Z}[\sqrt{-3}]$ if and only if $x^2+3$ is irreducible in $\mathbb{F}_p[x]$.

Question: I'm having trouble with this particular homework problem. I think I have one direction:
Let $R=\mathbb{Z}[\sqrt{-3}]$. If $p$ is prime, then $p$ is irreducible in $R$, since $R$ is an integral domain. Thus, $(p)$ is maximal, so
$$
R/(p) \cong \mathbb{F}_p[x]/(x^2+3)
$$
is a field. Hence, $(x^2+3)$ is maximal in $\mathbb{F}_p[x]$, so $x^2+3$ is irreducible.
However, if we assume $x^2+3$ is irreducible in $\mathbb{F}_p[x]$, then that only implies that $p$ is irreducible in $R$ by the same reasoning. Since $R$ isn't a UFD, this doesn't imply $p$ is prime, so I'm stuck.
Thanks so much!
Comment: Doesn't it imply that $(p)$ is maximal ideal in $R$?
Answer: If $R/(p)$ is a domain, then that does imply that $p$ is prime in $R$ (see the Wikipedia article). In other words, an element is prime precisely when the ideal it generates is prime, which is the case precisely when quotienting by that ideal produces an integral domain. If you assume that $x^2+3$ is irreducible, then you have that
$$\mathbb{Z}[\sqrt{-3}]/(p)\cong \mathbb{Z}[x]/(p,x^2+3)\cong \mathbb{F}_p[x]/(x^2+3)$$
is an integral domain (indeed, a field in this case).
Comment: Doesn't $p$ irreducible imply $p$ prime only in unique factorization domains?
Comment: No, it is more generally true in [GCD domains](http://en.wikipedia.org/wiki/GCD_domain) (and I'm not sure if this is necessary either); however, irreducibility is not the issue here.
Comment: Ahh, I see. The book I'm using is Artin, and he doesn't introduce prime ideals until the next chapter. Is there a similar argument that doesn't make use of them?
Comment: @N.S. No, for example $2$ is irreducible in $\mathbb{Z}[\sqrt{-5}]$ but it is not prime because $(1+\sqrt{-5})(1-\sqrt{-5})$ is divisible by $2$ even though neither factor is.
Comment: @ZevChonoles Yea remembered it after posting... Anyhow, $(p)$ maximal implies $p$ prime element.
Answer: Hint $\ $ If $\rm\ R/p\, \cong\, S/q\  $ then $\rm\ p\: prime\ in\,R\!\iff\! domain\: R/p \,\cong\, S/q\!\iff\! q\: prime\ in\ S$


Recurring payments

Question: Looking for feedback from those who have experience or have done research on recurring payment options for Drupal 7.
I'm familier with Ubercart UC Recurring for Drupal 6, but have not looked at Ubercart for D7.
My hope, since I'm rebuilding the site from the ground up in with D7, was to use Commerce. But so far, it doesn't appear that there is much support for recurring payments via the Commerce module.
Or... is there something besides Ubercart or Commerce that integrates well with Drupal 7?
Answer: If what you want/need is an order (multiple products) to be recurring:
Commerce Recurring
If what you want/need is a product (often times a service like hosting or a software license or a paid subscription) to be recurring:
Commerce License Billing + Commerce License
Regardless of those two options, you should definitely use the following module to deal with people who have credit cards that expire (everyone!):
Commerce Dunning
Comment: Oh, that's fantastic.  Thanks!  I thought cardonfile required local storage of credit card data; happy to know I was wrong about that.
Comment: Looks like this requires storing credit card data on the site (at least for the license billing).  Any other options that don't require this?
Comment: Colan, this isn't so bad. You can use https://www.drupal.org/project/commerce_cardonfile which has a number of payment gateways. It stores an anonymized token that the payment gateway will recognize as a saved credit card when used with your payment gateway credentials. Keeping the PCI Compliance requirements back at the Payment Gateway, where we want it.

Recurring payments


Help solving a system of differential equations -- more variables than derivatives

Question: I need help solving this system of equations:
$\dot{x}_1=-3x_1-2x_2\\ \dot{x}_2=2x_2-x_3.$
I'm confused by the inclusion of $x_3$ since we don't have an equation for $\dot{x}_3$.  I'm not sure how to make the coefficient matrix for the system without an equation for $\dot{x}_3$.
Comment: You are right, I think there is a missing context.
Answer: $x_3$ can be considered as an input function for the system
$$
\left(
\begin{array}{c}
\dot x_1\\
\dot x_2
\end{array}
\right) =
\left(
\begin{array}{cc}
-3& -2\\
0 & 2
\end{array}
\right)
\left(
\begin{array}{c}
x_1\\
x_2
\end{array}
\right)+
\left(
\begin{array}{c}
0\\
-1
\end{array}
\right) x_3
$$
Comment: Thank you so much for your reply, but unfortunately I'm still not sure where to go from there.  I've never solved a system like this before...can you elaborate on what you mean by "x3 can be considered as an input function for the system", or what the next step would be?
Comment: The characterization of $x_3$ as input is associated with the control system concept. According to this paradigm, $x_3$ would serve to make the dynamic system of state variables $(x_1, x_2)$ reach and be maintained in some region of the phase plane $(x_1, x_2)$ with the proper action of $x_3$. This is possible depending on certain systematic characteristics.


Birthday paradox

Question: I want to simulate the birthday paradox in java. For some reason my output(probability) keeps getting very close to 1 e.g. simulation(10)->0,9268. In start you can see the probabilities my simulations should be close to. I have been looking for a mistake in my code for quite a while now so i hope any of you might be able to help me. I've looked up other codes of the birthday paradox but none of them seem able to help me with my strange output.
p.s. you can ignore the //TODO, ill fix that once i get the code up and running.
Thanks is advance!
static final int DAYS_IN_YEAR = 365;
static final int NUMBER_OF_SIMULATIONS = 500;

LCG random;
HashSet<Integer> birthdaySet = new HashSet<Integer>();

BirthdayProblem2(){
    birthdaySet.clear();
    random = new LCG(); //random numbers between 0 and 1
}

int generateBirthday(){ //generates random birthday
    return (int) Math.round(Math.random()*DAYS_IN_YEAR); //TODO use LGC
}

double iteration(int numberOfStudents){ //one iteration from the simulation
    int sameBirthdays = 0;

    for (int i = 0; i < numberOfStudents; i++){
        int bd = generateBirthday();

        if (birthdaySet.contains(bd)){
            sameBirthdays++;
        } else {
            birthdaySet.add(bd);
        }
    }
    return (double) sameBirthdays/numberOfStudents; //probability of two students having the same birthday
}

void simulation(int numberOfStudents){
    double probabilitySum = 0;
    for (int i = 0; i < NUMBER_OF_SIMULATIONS; i++){
        probabilitySum += iteration(numberOfStudents);
    }
    System.out.printf("For n=%d -> P=%.4f \n", numberOfStudents, probabilitySum/NUMBER_OF_SIMULATIONS);
}

private void start() {

    simulation(10); //should be about 0.1
    simulation(20); //should be about 0.4
    simulation(23); //should be about 0.5
    simulation(35); //should be about 0.8
}

public static void main(String[] argv) {
    new BirthdayProblem2().start();
}

}
Comment: Method `iteration()` should return boolean, for whether or not there are students with same birthday. Number of true values returned divided by number of calls equals probability.
Answer: You are not clearing the birthdaySet between iterations. Change it from a field to a local variable will prevent errors like that, because why would you need it as a field in the first place?
On a different note, generateBirthday should use Random.nextInt(DAYS_IN_YEAR). An instance of Random is a prime candidate as field. What is that LCG random; line anyway?
UPDATE
Method iteration() should return boolean, for whether or not there are students with same birthday. Number of true values returned divided by number of calls equals probability.
Since there is a relative small number of days in a year, a boolean array will be faster than a Set, so here is updated code:
private static final int DAYS_IN_YEAR = 365;
private static final int NUMBER_OF_SIMULATIONS = 500;
private Random rnd = new Random();
private int generateBirthday() {
    return this.rnd.nextInt(DAYS_IN_YEAR);
}
private boolean iteration(int numberOfStudents) { //one iteration from the simulation
    boolean[] present = new boolean[DAYS_IN_YEAR];
    for (int i = 0; i < numberOfStudents; i++) {
        int birthday = generateBirthday();
        if (present[birthday])
            return true;
        present[birthday] = true;
    }
    return false;
}
void simulation(int numberOfStudents){
    int count = 0;
    for (int i = 0; i < NUMBER_OF_SIMULATIONS; i++)
        if (iteration(numberOfStudents))
            count++;
    System.out.printf("For n=%d -> P=%.4f%n", numberOfStudents, (double)count/NUMBER_OF_SIMULATIONS);
}

Sample Output
For n=10 -> P=0.1340
For n=20 -> P=0.4120
For n=23 -> P=0.5080
For n=35 -> P=0.8160

For n=10 -> P=0.1200
For n=20 -> P=0.4120
For n=23 -> P=0.5260
For n=35 -> P=0.8140

For n=10 -> P=0.1260
For n=20 -> P=0.3920
For n=23 -> P=0.5080
For n=35 -> P=0.7920

Increasing NUMBER_OF_SIMULATIONS to 5_000_000:
For n=10 -> P=0.1167
For n=20 -> P=0.4113
For n=23 -> P=0.5075
For n=35 -> P=0.8145

For n=10 -> P=0.1168
For n=20 -> P=0.4113
For n=23 -> P=0.5072
For n=35 -> P=0.8142

Comment: Thanks for your help, changed it into a local variable so it would refresh every iteration.  After that it worked! LCG stands for linear congruential generator, it is a way of making random numbers. Because I had to implement it into the birthday paradox, part of its code was already there.
Answer: As andreas already states birthdaySet should be cleared between iterations or the set will contain data from the previous simulation
However there's another fatal flaw in your design, to see it look at the wikipedia page:
In probability theory, the birthday problem or birthday paradox concerns the probability that, in a set of n randomly chosen people, some pair of them will have the same birthday.
It's the chance that there exists at least 2 people with the same birthday. That means that as soon as 2 are equal 1 should be returned.
I've summed it up in the code below
import java.util.HashSet;
import java.util.Random;

public class BirthdayProblem2 {
    static final int DAYS_IN_YEAR = 365;
    static final int NUMBER_OF_SIMULATIONS = 500;

    Random random;
    HashSet<Integer> birthdaySet = new HashSet<Integer>();

    BirthdayProblem2() { random = new Random(); }

    int generateBirthday() { return random.nextInt(DAYS_IN_YEAR); }

    double iteration(int numberOfStudents) { //one iteration from the simulation
        birthdaySet.clear();

        for (int i = 0; i < numberOfStudents; i++) {
            int bd = generateBirthday();

            if (birthdaySet.contains(bd)) {
                return 1.0;
            }

            birthdaySet.add(bd);
        }

        return 0.0;
    }

    void simulation(int numberOfStudents) {
        double probabilitySum = 0;

        for (int i = 0; i < NUMBER_OF_SIMULATIONS; i++) {
            probabilitySum += iteration(numberOfStudents);
        }

        System.out.printf("For n = %d -> P = %.4f \n", numberOfStudents, probabilitySum / NUMBER_OF_SIMULATIONS);
    }

    private void start() {
        simulation(10); //should be about 0.1
        simulation(20); //should be about 0.4
        simulation(23); //should be about 0.5
        simulation(35); //should be about 0.8
    }

    public static void main(String... whatever) { new BirthdayProblem2().start(); }
}

Comment: Thank you too, I interpreted the birthday paradox wrong. I updated my code and it works!

Birthday paradox


Img moving all column?

Question: So i've been trying to make this gallery for a web we are making in school and it seems to work but there's a small bug when on mouse over the img as you can see in the  gif.
I don't know if it's because of the border size or i should have used a table instead of divs. I appreciate any help.

div#img {
 border-radius: 5px;
    margin: 5px;
    padding: 5px;
    border: 3px solid #3781FF;
    height: 140;
    width: 100;
    float: left;
    text-align: center;
}

div#img img {
    margin: 4px;
    border: 2px solid #000000;
}

div#img a:hover img {
 border-radius: 40px;
    border:0px solid #3781FF;
 text-align: center;
}

div#desc {
    text-align: center;
    font-weight: normal;
    width: 100px;
}
<!DOCTYPE HTML>
<meta charset="utf-8" />

  <link rel="stylesheet" type="text/css" href="estil.css" />
  <link rel="stylesheet" type="text/css" href="galeria.css" />
  <link href='https://fonts.googleapis.com/css?family=Poiret+One' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Raleway:400,200' rel='stylesheet' type='text/css'>
  <title> LoL - Stats </title>

    LoL Stats

     Champions

     Worlds

     Patch

     Rotación Setmanal

Campeones

Todos

Magos

Tanques

Asesinos

Suports

Aatrox
6300 RP

Ahri
4800 RP

Akali
1350 RP

Alistar
450 RP

Ammumu
450 RP

Anivia
3150 RP

Annie
450 RP

Ashe
450 RP

Azir
6300 RP

Bardo
6300 RP

Blitzcrank
1350 RP

Brand
3150 RP

Braum
6300 RP

Caitlyn
4800 RP

Cassiopeia
4800 RP

Cho'Gath
450 RP

Corki
3150 RP

Irelia
3150 RP

Answer: You forgot  to add "px" for width and height properties of div#img.
div#img {
  border-radius: 5px;
  margin: 5px;
  padding: 5px;
  border: 3px solid #3781FF;
  height: 140px;
  width: 100px;
  float: left;
  text-align: center;
}

Answer: Try this:
Demo
div#img a:hover img have border:0px solid #3781FF; this is problem. this is changed to border-color:transparent; or border: 2px solid #3781FF;

Img moving all column?


Angular [Innerhtml] renders static files different from webapi response

Question: Need to display HTML file content in a DIV, works in static file, fails on dynamic file.
What Works:
I have an EML file, which I suspected I had to parse.
Renaming file extension to HTML, as is pleasantly rendered it somewhat decent, with all tags removed and formatted correctly, if served from static file.
public getOneFileStatic(fn: string): Observable<any> {
    return this.http.get(fn, { responseType: 'text' })
      .pipe(tap(_ => console.log('== getOneFileStatic ')));
  }

and  called simply:
svc.getOneFileStatic('/assets/files/eml-test.html')
            .subscribe(x => {
                    this.theinner = x;
                });

and the template is

What doesn't, and shows raw text with tags
Then tried the dynamic way to return from a webapi:
public getOneFile(fn: string): Observable<any> {
    return this.http.get( this.baseUrl + '/api/ServerFiles/GetStream/' + fn , { responseType: 'text' })
      .pipe(tap(_ => console.log('== getOneFile '))
      );
  }

results are a stream of text with all tags and MIME content dumped as is.
I looked into
I checked content headers and tried: text, blob etc., also application/octet.
But they all come across fine and are displayed raw with the HTML tags never honored.
Headers:
When static file is served
Referrer Policy: no-referrer-when-downgrade
HTTP/1.1 304 Not Modified
X-Powered-By: Express
Access-Control-Allow-Origin: *
Accept-Ranges: bytes
ETag: W/"cb81-Rb8BCAxZvy4eWO/lkggYEFPkXzo"
Date: Wed, 16 Jan 2019 21:33:45 GMT
Connection: keep-alive

when the dynamic file comes across:
HTTP/1.1 200 OK
Date: Thu, 17 Jan 2019 00:52:35 GMT
Content-Type: text/html
Server: Kestrel
Content-Length: 97197
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200

Note: there is no Content-Type header in case of static. But I need to supply one in my server code when streaming file content, which is Kestrel and in .Net Code.
Comment: try this `responseType: 'document'`
Comment: Tried 'document' response type, no change, same result.
Answer: You might want to try to sanitize the resulting raw text with tags.
Check out the Angular Sanizitation API example (basic but might be enough).