Year as a fixed or random effect in GLM with only two levels

Question: I'm using glm to predict species richness from different combinations of environmental variables. Species data were collected at 40 to 125 sites in summer over two or three years, depending on the region. These sites were the same across years.
For each of the four regions, I'd like to include year in the model. However, I'm not sure if a fixed or random effect is most appropriate. I understand the philosophical argument that a random effect is appropriate for broad inference across years, whereas a fixed effect is appropriate when the particular years in question are of interest. In this case, I'd specify year as a random intercept: lme4::glmer(richness ~ conifer + shrub + herb + (1|year), data). But with only two to three levels within year, perhaps this is not suitable.
Another consideration is that I am using stepwise model selection to select covariates at different spatial scales. However, glmmLasso, which I attempted for the process, returned the following error: 'Error in n %*% s : requires numeric/complex matrix/vector arguments'. I suspect that this may be due to there only being two to three levels within year.
Guidance on whether year should be fixed or a random intercept (or included with an alternative approach) is much appreciated. Thank you!
Answer: With only three levels you should not add year as a random effect.
Reason for this is covered in this Post
What is the minimum recommended number of groups for a random effects factor?

One point of particular relevance to 'modern' mixed model estimation (rather than 'classical' method-of-moments estimation) is that, for practical purposes, there must be a reasonable number of random-effects levels (e.g. blocks) — more than 5 or 6 at a minimum.

So if you want to add year to your model it would suggest to add it as a fixed effect:
lme4::glmer(richness ~ conifer + shrub + herb + year, data)
and maybe if it makes sense in your experiment check for interactions with year:
lme4::glmer(richness ~ (conifer + shrub + herb) * year, data)


Opt for a pass grade or a relative grading system?

Question: Consider a class consisting of $n$ students with their CPI ranging from $0$ to $10$. All of them are scored on a test given by an instructor. Each student in the class knows the CPI and test marks of every student. Following the scoring process, each student is given a choice in the method of evaluation.
Either a student can opt for no evalution, in case of which, the CPI of the student remains the same as before.
Or, a student can submit for the evaluation process.
The evaluation process is as follows: consider that a total of m students apply for evaluation. If a student has a position of $i$(out of the $m$) in the rank list, the student is awarded a CPI of $10({1−{i\over m+1}})$.
What should be the strategy of each student assuming every student wants to improve one's own CPI?
I realise that this would strongly depend on the distribution of the initial CPIs as well. Also, there can be certain situations where everyone being greedy is helpful for everybody. But for the general case, even if a student enumerates all the possible $2^n$ outcomes along with the payoffs of every other player, what should a student choose?
Comment: What does CPI mean?
Comment: CPI stands for Cumulative Performance Index in many Indian colleges
Answer: If we assume that the student cares about his/her ranking among everyone who took the test, it doesn't really matter. The conversion does not alter the ranking of the student; if the student has a lower score than another before conversion he/she/it will also have a lower score than the other after conversion. As the ranking is constant, the only difference is the score itself.
Assuming the student only cares about his / her own score, the student would opt to submit if the conversion positively affects the score, i.e.
$$
10(1- \frac{i}{m+1}) \geq \text{CPI}_i
$$
where $\text{CPI}_i$ is the mark for the student.
Comment: I think you've misunderstood the question. $m$ is the number of students who apply for evaluation. A student's grade is affected by the number of students who applied, not the total students in the class.


How is "smaller than" defined on $\mathbb{R}$?

Question: According to http://en.wikipedia.org/wiki/Binary_relation

Binary relations are used in many branches of mathematics to model concepts like "is greater than", "is equal to", and "divides" in
  arithmetic, "is congruent to" in geometry, "is adjacent to" in graph
  theory, "is orthogonal to" in linear algebra and many more. The
  concept of function is defined as a special kind of binary relation.
  Binary relations are also heavily used in computer science.

AFAIK on the set of real numbers we can define a binary relation $<$ which represents a subset of the cartesian product $\mathbb{R} \times \mathbb{R}$. How do we decide which pairs are contained in this subset? Do we know that by set inclusion? I know about the definition of real numbers with the concept of a Dedekind cut, so I suppose that to know which pairs are in this subset we can view the first element of any pair $(a,b)$ as a set of rationals and if it is included in the second element $b$ than we conclude that the pair $(a,b)$ is contained in the subset of the cartesian product $\mathbb{R} \times \mathbb{R}$ and we can say that $a < b$. Am I right?
Comment: As far as *I* know, however you decide to define the real numbers (or rationals etc...) you also have a definition of addition and multiplication, and hence subtraction.  From there you also have a definition of "positive" and "negative" numbers.  Define $a>b$ iff $a - b$ is positive.  (or equivalently $a<b$ iff $b-a$ is positive) for the usual "greater than / smaller than" binary relation
Comment: @MingusMingusMingusMingus A Dedekind cut is positive if it contains $0$. A Dedekind cut $r$ is negative if there is a negative rational number that is not in the cut. You need to prove that a Dedekind cut which is neither positive nor negative is zero.
Comment: AFAIK? What does that mean?
Comment: AFAIK = as far as I know
Comment: You're overthinking this.  Any subset of $\Bbb R\times\Bbb R$ is a relation on $\Bbb R$. There's no need to think of this in terms of Dedekind cuts.
Comment: @TimRaczkowski There is if you want to define the relationship.
Comment: @ThomasAndrews Yes I see what you're saying.  I misinterpreted the question.
Comment: Well, it was confusing with the relationship definition quote. @TimRaczkowski
Comment: @JMoravitz How do you define positive and negative without defining < first?
Comment: @ThomasAndrews Then it seems quite easier to define $a<b$ as $a\subsetneq b$ and only after that define positive and negative, doesn't it?
Comment: That sentence made no sense. Did you mean "rather than after..."? @MingusMingusMingusMingus
Comment: @ThomasAndrews what Mingus$^4$ was saying was, having already decided to use Dedekind cuts, it seems that it is easier to define $<$ before positivity (that is define $<$ and, only after that, positivity).
Answer: If you define the reals with Dedekind cuts, yes:
$$\forall a,b\in\mathbb R(a\leq b\iff a\subseteq b)$$
$$\forall a,b\in\mathbb R(a<b\iff a\subsetneq b)$$
It's a little harder to define ordering on the reals if you use Cauchy sequences. (This is because Dedekind cuts are specifically designed to "complete" the ordering of the rationals, while Cauchy sequences are designed to complete the metric space.)
Comment: That suggestion, though, requires you to already know what "positive" means for real numbers - if we're starting "from scratch," i.e. building the real numbers via Dedekind cuts, we don't have that. It all depends on what we start with.
Comment: No, the definitions can vary. You can prove they end up with the same relationship, however. Still, if you use Dedekind cuts, it is better to stick to the subset definition because it really is more natural, and you can do it immediately, even before you define addition and multiplication. You can even prove the real numbers have the "least upper bound" property before you define the arithmetic operations. @notorious
Comment: There is a very nice suggestion from @JMoravitz above in the comment: "*Define a>b iff a−b is positive. (or equivalently a<b iff b−a is positive)*".
Comment: @notorious To be fair, that requires a definition of positive/negative which *doesn't* involve < already being defined, so I worry about my definition being circular, which is why I hesitated to put it as an answer.
Comment: @notorious Sure, that works, but it isn't "natural." Addition and subtraction are much harder definitions to add to Dedekind cuts, while set inclusion is much easier.
Comment: @JMoravitz Yes you are right that a definition of positive/negative doesn't involve defining < and I think that the definition you proposed is not circular. It only involves addition and subtraction to be defined and that's all.
Comment: One thing I am curious about, is there a ***standard*** definition/reasoning for this? For example, all mathematicians using only one definition for this etc? Or I can define it the way I want it to be defined?
Comment: (Addition is easy to define for Dedekind cuts, but additive inverses gets a little verbose.)
Answer: It all comes down to how we're setting the reals up.

If we're using Dedekind cuts, then yep, that's how to do it!
If we're using equivalence classes of Cauchy sequences, then we have to say something messier: $a<b$ if, whenever we pick representative sequences $\alpha\in a$ and $\beta\in b$, there is some $n$ such that for all $m>n$, $\alpha(m)<\beta(m)$. That is, $a<b$ if "$a$'s Cauchy sequences always eventually become smaller than $b$'s Cauchy sequences."
Comment: Do you know any materials I can read to learn more on this topic?
Comment: Hm . . . you might be interested in [the way of analysis](http://www.amazon.com/Analysis-Revised-Edition-Bartlett-Mathematics/dp/0763714976). It's also worth reading Dedekind's original article - it's quite good! And on the historical side, Jeremy Gray's book "Plato's Ghost" covers much more ground, but is a hugely awesome read!
Answer: Depends on the construction you make of $\mathbb{R}$. Assuming that you already have built the operators $+,\cdot$, a simple way to notice it would be to make a subset $\mathcal{P}\subset\mathbb{R}$ which represent the positive numbers, then $a\leq b \iff b+-a\in \mathcal{P}$, where $-a$ is the additive opposite of $a$ such that $a+-a = 0$.
Answer: In Dedekind's construction $\alpha < \beta$ is defined to mean $\alpha$ is a proper subset of $\beta$. What you say is correct.
Answer: If we use dedekind cut to complete Q then then for a < b we must have a $\subset$ b proper subset that is.


vb.net : DateTimePicker switches formats when queried

Question: So my DateTimePicker's format on Visual Basic 2010 is dd/MM/yyyy but whenever I query the date it queries itself in this format MM/dd/yyyy
Example:
I have 3 registers on my database which are...
02/07/2016  (format is dd/mm/yyyy)
03/07/2016
04/07/2016
If in my datetimepicker I select 02/07/2016 and 05/07/2016 it reads it as 07/02/2016 and 07/05/2016
Why does this happen?
Here is my code
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    Dim provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    Dim dataFile As String = "E:\Serna Impresos 2016\Serna Impresos 2016\Serna Impresos 2016\bin\Debug\SIDB.accdb"
    Dim connString As String = provider & dataFile
    Dim myConnection As OleDbConnection
    Dim cmd As OleDbCommand

    Dim qHrsTrab As String = "SELECT SUM(Horas_trabajadas) FROM Trabaja WHERE IdEmpleado = " & IdEmptxt.Text & " AND Fecha >= #" & consultaIniDTP.Value.ToString("dd/MM/yyyy") & "# AND Fecha <= #" & ConsultaFinDTP.Value.ToString("dd/MM/yyyy") & "#"

    myConnection = New OleDbConnection(connString)
    Try
        myConnection.Open()
        cmd = New OleDbCommand(qHrsTrab, myConnection)
        Dim reader As OleDbDataReader = cmd.ExecuteReader()

        While reader.Read
            hrsTrabajadastxt.Text = reader.Item(0)

        End While
        reader.Close()
        cmd.Dispose()
        myConnection.Close()

    Catch ex As Exception
        hrsTrabajadastxt.Text = 0
    End Try

Answer: Just use the same yyyy-mm-dd formatting as showed in your last question:
Can't retrieve data from Access DB query to my VB program


Action of module automorphism group

Question: It can be proven that for any vector space $V$ the action of $\mathrm{GL}(V)$ on $V \setminus \{0\}$ is transitive, and its stabilizer is $U^* \rtimes GL(U)$, where $U$ is a complement to the subspace spanned by some non-zero vector from $V$. The proof that I found relies heavily on the fact that any non-zero vector can be extended to a basis, so naturally it's a useless tactic for modules.
Can this proposition be generalized to modules or at least some class of modules larger than vector spaces? What proof strategy would you suggest?
Answer: Here is one counterexample: for $\mathbb{Z}$-modules, we have that $\text{GL}(\mathbb{Z})=\{\pm1\}$, which does not act transitively on $\mathbb{Z}\setminus\{0\}$.
If we want even the claim that $\text{GL}(M)$ acts transitively on $M\setminus\{0\}$ for any $R$-module $M$ to be true, then it must be true for $R$ treated as an $R$-module, so we need $\text{GL}(R)=R^\times$ to act transitively on $R\setminus\{0\}$, i.e. for any $x,y\in R\setminus\{0\}$ there is a unit $u$ such that $y=ux$. In particular, for every $x\in R\setminus\{0\}$, we have that $x=u\cdot1=u$ for some unit $u$, i.e. every non-zero element is a unit, i.e. $R$ is a field. So this won't be true for anything other than vector spaces.

Action of module automorphism group


Last pair of map in vector of maps

Question: vector<multimap<string, int> > allCount;

I want to get last pair of map from vector of maps and I don't know how.
int x = 0;
for(iter = patternBase.begin(); iter != patternBase.end(); iter++) {
    Tree t;
    for(int j = 0; j < iter->second.size(); j++) {
        for(int k = iter->second[j]->getPath().size() - 1; k >= 0 ; k--)
            sets.push(iter->second[j]->getPath()[k]);

        t.insertNode(sets, here I want to use last pair (value) of allCount[x] map);
        cout << endl;
    }
    cout << endl;
    x++;
}

Answer: You will need to create the iterator like this:
multimap<string, int>::iterator it = allCount[x].end();

Then decrement it to make it point at the last element:
it--;

Finally:
t.insertNode(sets, it->second);

Last pair of map in vector of maps


Matrix equation - find $a,b,c,d$

Question: How do I find a,b,c and d in this matrix equation?
$$
  \begin{bmatrix}
    3 & 2a \\
    b & -2 \\
  \end{bmatrix}
+
\begin{bmatrix}
    b & -a \\
    c & d \\
  \end{bmatrix}
=
\begin{bmatrix}
    a & 2 \\
    2 & 6 \\
  \end{bmatrix}
$$
So far, I've worked out $d$ by using doing 6-(-2) which equals to 8. I'm not so sure on how to work out the rest.
Answer: Adding each component:
$$3+b=a$$
$$2a-a=2$$
$$b+c=2$$
$$-2+d=6$$
I'm sure you can work out the rest.
Comment: You can use the result of another equation. For example, equation 2 gives you $a$. Then use that value of $a$ in the first equation, you can solve for $b$.
Comment: Yes, that's what I had done before as well. But for example, for the first one - how do I work out b or a if I only have 3 there? This is what I'm confused about here. I'm also having the same problems for the second and third one.
Comment: You have 4 linear equations in 4 unknowns. Have you not learned how to solve such a system, Penny? It seems strange that you would be asked to do such a question before you've been taught to solve systems of linear equations.
Comment: Are you still here, Penny?

Matrix equation - find $a,b,c,d$


What are the available hooks for views

Question: I cannot find the list in the api documentation.
https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/group/views_hooks/8.5.x
Nor am I able to enter such functions in a theme when loading a page with a view.
Answer: They're here

In the codebase: core/modules/views/views.api.php.
On the web: https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/8.5.x

As always, only *_alter hooks and hook_theme can be implemented in a theme. Any other hook needs to be implemented in a module.

What are the available hooks for views


Execute window[func].apply(this, args)

Question: I am trying to execute a function stored in a variable and pass params to it. However, on the .apply line, I am getting an error; Uncaught TypeError: Cannot call method 'apply' of undefined
Fiddle: http://jsfiddle.net/valamas/vzesm/
function target(msg)
{
    alert(msg);
}

function mainfunc (func)
{
    var args = new Array();
    for (var i = 1; i < arguments.length; i++)
        args.push(arguments[i]);

    console.log('args: ' + args);

    //-- different attempts
    window[func].apply(this, args);
    //window[func].apply(null, Array.prototype.slice.call(arguments, 1));
    //this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}

$(function ()
{
    console.log('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n');
    console.log('ready');
    mainfunc('target', 'hello,', 'there!');
});

Answer: jsFiddle doesn't put the JS into the global scope, so target isn't actually a property of window.
Adding this code will make your script work:
window.target = target;

Or to be more explicit:
window.target = function() { ...

Demo: http://jsfiddle.net/Blender/vzesm/3/
Comment: wherever it puts it, if you change onload to "no wrap - head" it works
Comment: It probably wraps it with a `(function() { ... })();` wrapper. I didn't know about the no wrap option, thanks.
Answer: This is because in jsfiddle javascript gets executed in a different scope. Your code will work in firebug console if jQuery is loaded. For jsfiddle you have to rewrite as given below
target = function(msg)
{
    alert(msg);
}

function mainfunc (func)
{
    var args = new Array();
    for (var i = 1; i < arguments.length; i++)
        args.push(arguments[i]);

    console.log('args: ' + args);

    //-- different attempts
    window[func].apply(this, args);
    //window[func].apply(null, Array.prototype.slice.call(arguments, 1));
    //this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}

$(function ()
{
    console.log('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n');
    console.log('ready');
    mainfunc('target', 'hello,', 'there!');
});

Execute window[func].apply(this, args)


clock() and CLOCKS_PER_SEC on OSX 10.7

Question: I'm having a problem using clock() in OSX.
I just want to display the time elapsed since my program started.
The thing is, when I divide the clock_t struct by CLOCKS_PER_SEC I get strange results.
Running my program for 10 seconds will display 1.0.
CLOCKS_PER_SEC is set to 1,000,000 on my system.
Here is a sample of my code :
    //startTime = clock() at the start of the program
    //This is called in each program loop
    elapsedTime = (double)(clock() - startTime)/CLOCKS_PER_SEC

If I'm doing elapsedTime * 10 I get the accurate value in seconds.
I don't do any sleep or wait at all during the program execution.
Any help understanding what's happening would be really appreciated.
EDIT:
Ok, I corrected the cast, but it doesn't change the fact that if I run the program for 10 seconds I get 1.0, 1 seconds is 0.1 . This is what I don't understand. My CLOCKS_PER_SEC is like a CLOCKS_PER_TEN_SEC.
Comment: Just what are you doing between the two `clock()` calls?
Comment: Just drawing a simple image with SFML. (no fps limit involved). I'm also displaying the elaspedTime on each frame, and I see each second adds about 0.1 to  the elapsedTime.
Comment: Then maybe most of the processing is being done by the GPU and not being counted by `clock()`.
Comment: Didn't think about that. But I don't know how I can verify it. I just found SFML has a Clock class, I think I'll stick with it, but still don't understand why I get something pretty accurate by multiplying elapsedTime by 10.
Answer: I think your cast is in the wrong place, so you're getting an integer division. Try this:
elapsedTime = (double)(clock() - startTime)/CLOCKS_PER_SEC;

EDIT:
Also note that on most systems, clock() measures CPU time. Maybe you're not using as much CPU time as you think.
Answer: move your cast to the inside of the first parenthesis:
 elapsedTime = ((double)(clock() - startTime)/CLOCKS_PER_SEC)

Now clock() -startTime becomes double, forcing CLOCKS_PER_SEC to be a floating point value too, and you get floating point result. Otherwise, it's an integer divide, and you get only integer results.
Answer: clock() with CLOCKS_PER_SEC is not fit for purpose on Mac OS X. clock() returns the processor time in ticks, while POSIX stipulates that CLOCKS_PER_SEC is 1000000, as noted in the man clock page.
In my case of running into this, like you, the calculation is off by a factor of ten. So, clock() is running at 100000 clocks per second. On Windows, I'm seeing 1000 clocks per second. But if you check into this, the actual resolution and precision can be far worse than this, so clock() is not a good solution in general. For Mac OS X, gettimeofday is a much better solution. I also suppose std::chrono is a good solution, and should be a better cross platform choice, but I haven't tried it yet.
Comment: If you decide to try `chrono`, here's a video tutorial to help get you started: https://www.youtube.com/watch?v=P32hvk8b13M :-)  However, `chrono` will only measure elapsed time, not processor time like `clock()` does.
Comment: Yes, in my case I'm only interested in elapsed time, roughly millisecond accuracy. And you are right, I hadn't noticed that although clock() under Windows is defined as "wall-clock time", the unix version is processor time. (I was using gettimeofday on the Mac side from the start, but went to clock() for the Windows builds—I was just experimenting to see if I could use clock() and avoid minor conditional compilation ugliness.) The bottom line is clock() is very rough on Windows, and on Mac it's the wrong thing. Obviously, chrono is the best cross-platform choice.
Comment: FWIW, a one-liner for the current time in milliseconds (#include ):

std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count();

clock() and CLOCKS_PER_SEC on OSX 10.7


Can I run Numpy (or other Python packages) on Android?

Question: I have implemented a python script, which imports Numpy and Pandas and I would like to run this script on Android. To be more precise, I would like to embed this script into an application.I would like to know whether it is possible? If so, what are the best-practices to implement it?
I would greatly appreciate any help!
Answer: If you do not want to build a website or app and have Python/Pandas running as a backend. You can use Kivy as a packager to run Python on Android. Further, if you check out the answer to this question it points to the documentation for using numpy too - which is to use a "recipe" for compilation.
If using Kivy and not using a pure python library - these recipes will need to be used or created if they do not exist. So with Pandas, you would need to build this recipe yourself. Even if you do build this resource, the size of trying to load Pandas (not to include the resources it can require when performing analysis on dataframes) might be a bottleneck if trying to include it directly in the app and it still might be better to do this in a backend situation.
Comment: Thank you very much for your reply! I've started to use kivy and managed to create the necessary recipes (pandas wasn't among these after all). Having these apk files, I would like to ask whether it is possible to use them in android development (i.e. import the numpy package).
Comment: pandas is big so using it in mobile (directly on the device) would be difficult no matter the package used - which is why most move to using numpy for calculations and then matplot directly for visualizations. If you have the apk -> [I would follow the instructions from kivy](https://kivy.org/docs/guide/packaging-android.html). After that it is a process so [ask direct questions](http://stackoverflow.com/help/how-to-ask) when you run into problems


Bootstrapping with repeated measurements

Question: I am trying to estimate a linear relation between body temperature and body mass, and I have a sample of measurements from subjects, with most subjects having one measurement, but several subjects having two measurements in different times.
In order to estimating the slope 95% confidence interval, I could have used the usual formula, but since my data is partially correlated (due to having two measurements from the same subjects, for some of the subjects), I understand this will not be correct. So I was told it is better to use bootstraping technique.
My question is: How do I use bootstrapping while accounting for the fact that some of the subjects were sampled twice? Should I just take those subjects with 1/2 the probability of other subjects?
Is that a common practice, and if so - how is it called? (possibly "Inverse Probability Bootstrap Sampling"?)
(In fact, there is an additional twist here, since I am using Passing-Bablok linear model, due to the nature of data; but answers related to ordinary linear regression, or even bootstrapping of 1 variable alone, are welcome as well).
Comment: In another comment you write that the dataset is "not large."  This ought to lead you away from bootstrapping, whose theoretical legitimacy holds only for large datasets (that is, asymptotically).  Instead, use an appropriate model.  A simple and likely effective one is to suppose independent, homoscedastic measurement errors, permitting direct application of standard (ordinary least squares) modeling.
Answer: We use the bootstrap when we want to know how some function will behave when applied to different datasets drawn from a particular population. Obtaining new datasets is expensive, so instead the bootstrap pretends that the dataset you have is the population, and simulates new sampled datasets by resampling from the dataset you have.
Therefore, you want your resampling procedure to mimic how you obtained your original dataset in the first place. In your case, your original dataset was obtained by sampling a person, and then measuring them some number of times. Your resampling procedure should mimic this by resampling people, and including all of a person's measurements each time they are resampled.
Answer: If the dataset is large, it shouldn't be a problem. In fact, if your dataset is large, repeated observations may even help you to get a better idea of the underlying true distributions.
It is worth noting that even with the regular bootstrap, sooner or later there are bound to be repeated obsevations in the bootstraped dataset anyway.
Comment: 1. The dataset is not large.
2. Only part of the measurements are repeated.
3. Obviously this helps narrowing the CI, the question is - by how much?
4. In regular bootstrap, you have euqal probability for every point to be sampled repeatedly, while in my data only some of the points are.

I guess I can make bootstrap with lower probability for repeated subjects (so that all subjects have equal probability). But is this a common practice?


Rails 3 Alert Not Working with Ajax

Question: I've implemented a "like" button in ajax on my rails application, and I'm wondering why alert is not working.
In my controller,
 def like
    @post = Post.find(params[:id])
    if current_user
        if @like.empty?
            @post.num_likes += 1
            @post.save
        else
            alert = "You already liked the post :)"
        end
    end
  end

and my like.js.erb file
$("#post_like_<%= @post.id %>").html("<%= @post.num_likes %>");

I initially wanted to redirect the user to the log in page if he's not logged in, but I learned that it's impossible to use redirect in a XML request. Could there be any workaround for me to request the user to log in when the user clicks the "like" button, while showing the alert message at the same time?
I thought including bootstrap popover in my js file as follow would be a workaround to using "alert" in my controller, but it didn't work. I expected to see a popover under the number of likes.
$("#post_like_<%= @post.id %>").html("<%= @post.num_likes %>");
$("#post_like_<%= @post.id %>").popover('show')

Could anyone provide answers to my questions?
I appreciate your help!
Answer: To show a flash message triggered by an Ajax request, you can do something like this in your like.js.erb file (this presumes the presence of a division with the id "flash" on your page):
<% if @alert %>
  // displays the alert message and makes it "blink"
  $("#flash").html("<%= escape_javascript(@alert)%>").effect('highlight', {}, 1500);
<% else %>
  $("#post_like_<%= @post.id %>").html("<%= @post.num_likes %>");
<% end %>

To redirect a user to the login page from an Ajax request can be done by changing the window.location. Again in your like.js.erb file:
<% unless current_user %>
  window.location = '<%= new_user_session_url %>';
<% end %>

However, it might be sufficient to just display a flash message urging the user to log in with a link to the login path.

Rails 3 Alert Not Working with Ajax


Cannot access other machines on remote network with OpenVPN

Question: I am trying to set up OpenVPN so that I can access machines inside an Azure subnet from my pc which is outside Azure.
I have successfully installed OpenVPN on both server (Windows Server 2019) and pc (Windows 10) using the instructions here: https://community.openvpn.net/openvpn/wiki/Easy_Windows_Guide?__cf_chl_jschl_tk__=pmd_889e3e419b8b865ffd4da6e493bef6df0782273e-1629275604-0-gqNtZGzNAfijcnBszQgi, and I can successfully connect from client to server, however, I cannot connect to any other machine on the Azure subnet upon which the server is sitting.
The server and the other machines I want to connect to are on a 10.0.0.0 subnet, and the VPN is coming up on the 10.8.0.0 network as I would expect from the examples.
I have enabled IP routing on the server as recommended in the OpenVPN FAQ but this has not fixed the issue.
I have also added a 'push "route 10.0.0.0 255.255.255.0"' line to the server config, and I can see from the client log (and the client routing table) that this has been executed, but I am still unable to connect to other machines in the subnet.
I was looking into using Tap instead of Tun, but when I dug into at what was actually being used, it looks as if as if both ends are using the Tap adaptor anyway, even though I have specified 'dev tun' in both the client and the server configs.
I have had bit of a trawl but can't find anything about the Tap adaptor when the Tun adaptor has been configured, so that is a bit of a mystery.
The only other thing that I have read is that it might be necessary to set up a route back to the OpenVPN subnet on the gateway server for 10.0.0.0, but that's not a server I control as it's part of the Azure infrastructure.
What do I have to do to get access to other machines on the 10.0.0.0 subnet?  And why is the Tap adaptor being selected despite the config specifying the Tun adaptor ?
Answer: I made a number of other changes before I finally got it sorted out - I do not know if they were all necessary but in addition to the above:

I changed 'dev tun' to 'dev tap' in the server and client configs.
I followed the instructions here NAT-hack to add NAT to the server.
And finally, I added 'route 10.0.0.0 255.255.255.0 10.8.0.1' to the
server config file.


call_user_func() and external functions problem

Question: I'm trying to create some logic in order to have my code better organized, so I am creating a module and trying to separate functions in different files according to it's content type.
For example, I have a module called my_module and I'm creating two content_types content_type1 and content_type2
So I created this structure:

my_module.install
my_module.module
my_module.content_type1.inc
my_module.content_type2.inc

This logic inside install:
function my_module_install() {
  // During installation, the t() function is unavailable, so we use get_t()
  // to store the name of the translation function.
  $t = get_t();

  //List of objects to be created
  $nodes = array('content_type1','content_type2');

  //Create all the content-types from the array
  foreach ($nodes as &$node_name) {
    error_log('Create: '.$node_name, 0);
    call_user_func('_'.$node_name.'_create_node',$node_name);
  }

  unset($node_name);
}

And this logic inside each file ( content_types )
function _content_type1_create_node($node_name='type1') {}

function _content_type2_create_node($node_name='type2') {}

Since I added this lines to the my_module.info:
files[] = my_module.content_type1.inc
files[] = my_module.content_type2.inc

I was expecting to have all the logic working as it should but
//content_type1_create_node()
call_user_func('_' . $node_name . '_create_node', $node_name);

It cannot find the callback and I think it's because the callback.
Am I over engineering, or doing it wrong?
Answer: Your functions are in files that haven't yet been included, try changing your code to this:
foreach ($nodes as &$node_name) {
  module_load_include('inc', 'my_module', 'my_module.' . $node_name);

  $func = '_'.$node_name.'_create_node';
  if (function_exists($func)) {
    call_user_func($func, $node_name);
  }
}

I've never been able to get the files[] key in the .info file to work, I don't think it's used for arbitrary files but rather those that will form part of Drupal's code registry (using hook_hook_info() or something like that), but I haven't delved too deeply so it's worth checking yourself.
To answer your final question, yes I think you're over-engineering this a bit :)
It would make sense to do this if your module is going to become generic (so more content types can be catered for) but if it's really just 2 content types I'd put the code inside the .module file to be honest.
Obviously if you think these files will end up having a lot of code it makes sense to separate them, but if not I don't think you're really getting much benefit for doing so.


Limit facets (exposed filters) based on contextual filters in a view

Question: I'm trying to limit terms in a view facet (exposed filter) based on a contextual filter.
I have products with a 'category/type' taxonomy term. The terms are 2-level, looking roughly like this:

Category 1

Type a
Type b
Type c

Category 2

Type d
Type e
Type f

We can assign multiple terms from the 2nd level to each product.
I have a view that shows only products within a 1st level category (e.g. Category 1) by contextual filter, and then allow the user further filter by 'Type' from a facet (should show 'Type a', 'Type b', 'Type c' when contextual filter is 'Category 1').
The problem is that, since we can assign terms from multiple categories to the same product, we are seeing types from 'Category 2' in the facets, despite the fact that we're filtering by 'Category 1'.
Is there a hook to alter the facets, based on the contextual filter applied to the view?

So far, I got as far as eliminating an option from an exposed filter:
<code>use \Drupal\Core\Form\FormStateInterface;
/**
 * Implements hook_form_views_exposed_form_alter().
 */
function cd_general_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $view_ids = [
    'duplicate_of_product_category_by_material',
    'product_category_by_material',
  ];
  if ($form_id == 'views_exposed_form' && in_array($form_state->get('view')->id(), $view_ids)) {
    unset($form['field_category_target_id']['#options'][118]);
  }
}
</code>
To test, I duplicated my view so that I have one with normal exposed filters, and the original with facets related to those filters. The code above works on the exposed filters, but not on my facets.
My next step is to look again for hooks in the facets and core_views_facets modules.
Answer: I was able to use hook_preprocess_facets_item_list.
<code>/**
 * Implements hook_preprocess_facets_item_list().
 */
function mymodule_preprocess_facets_item_list(&$variables) {
  $facet_id = $variables['facet']->id();

  if ($facet_id === 'content_category') {
    // In the product categories by material view, remove category
    // facets based on the contextual parent category.
    $path = \Drupal::service('path.current')->getPath();
    $contextual_category_name = explode('/', $path)[2];
    $contextual_category_term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties([
        'name' => $contextual_category_name,
        'vid' => 'product_category',
      ]);
    // First array element, only.
    $contextual_category_term = reset($contextual_category_term);
    foreach ($variables['items'] as $key_item => $item) {
      $tid = $item['#attributes']['data-drupal-facet-item-value'];
      $term = Term::load($tid);
      $parent = \Drupal::entityTypeManager()
        ->getStorage('taxonomy_term')
        ->loadParents($tid);
      // First array element only.
      $parent = reset($parent);
      $parent_id = $parent->id();
      if ($parent_id !== $contextual_category_term->id()) {
        // Remove facets not within the current parent category.
        unset($variables['items'][$key_item]);
      }
    }
  }
}
</code>


Why are CentOS mirrors HTTP and not HTTPS?

Question: As far as I know, HTTP is prone to man-in-the-middle attacks. As such, the repositories in Alpine Linux or the CentOS Mirrors are not HTTPS.
In the olden days, having HTTPS used to be an expensive matter. It cost server CPU time and the certificates weren't free. But it's 2022 now, and we have plenty of ways to overcome those problems and security has been top priority than ever!
How can we obtain binaries smarter?
Also is this a problem in the wider Linux community? I.e., Ubuntu, Linux Mint, openSUSE, etc.?
Comment: See https://security.stackexchange.com/questions/18853/why-arent-application-downloads-routinely-done-over-https
Comment: Many CentOS mirrors are *both* HTTP and HTTPS (and all CentOS 9 Stream mirrors are both), so just pick an HTTPS one to use.
Comment: If the mirrors required credentials over HTTP and you comply and/or you are not verifying the checksum after downloading then you might not be the target audience for CentOS.
Comment: @Randall Since OP mentions Ubuntu as well, a lot of Ubuntu mirrors are unfortunately HTTP-only. I can't use them because my ISP runs (well-intended?) virus scans on all HTTP traffic and often blocks certain packages as false-positive.
Answer: The packages are indeed signed, hence a manipulation would be noticed.
Also the packages are not secret, so there isn't any need to encrypt them on the transfer.
With the mass of downloads from mirrors, this probably saves them a lot of resources.
It is the same on Debian and Ubuntu.
Comment: It is doubtful that "this probably saves them a lot of resources" https://istlsfastyet.com/
Comment: Traffic analysis is a nice tool to discover what a server is installing, and thus what potentially vulnerable packages its pulling - so I disagree with your assertion that "the packages are not secret so no need to encrypt them".
Comment: @AndrewSavinykh AES CPU time is not the only thing that increases resources. https being inherently anti MITM makes it impossible for http acceleration proxies to reduce the server load. HTTP accelerators like Squid.
Comment: Plus for users in (and using the network of) a business, school or other organization that inspects network traffic, such inspection is transparent for HTTP, but HTTPS must be decrypted then re-encrypted with a different certificate which client software probably doesn't recognize, making system maintenance fail, which is typically bad.
Comment: @moo I have read before that traffic analysis still allows you to know what is downloaded with https since you can observe the size of the download, and it's not secret. Maybe you can't differentiate packages by weight in every case, but you can make assumptions (if you installed 3 php modules, the next one is more likely another module than a Paint program if I doubt between those 2)
Comment: Many Ubuntu mirrors reply on HTTPS now, for anyone that cares to type it in.
Comment: Thanks @Virsacer and all the editors of question and answers. One more clarification on the answer: Is it possible to manually check the package integrity? In my view the package and the Hashes can be changed through a man in the middle attack. Also, does the OS automatically check the signatures during installation?
Comment: @SydMK If a transmission is signed, and the attacker doesn't have a copy of the sender's private key, and you have a (untampered) copy of the sender's public key, then it is not possible for the attacker to sign a transmission they have changed through MiTM. Therefore you'd be able to detect such a change by using the sender's public key to see whether or not it was they who signed it.
Comment: @Moo is correct, the primary threat of information disclosure that HTTPS would protect against here is not that package xyz has some specific contents, it's that a system at IP address 192.0.2.1 has downloaded package xyz (and therefore probably installed package xyz), which is _exceedingly_ useful information for someone attacking that system.
Comment: @Einacio traffic analysis of encrypted streams can and does still elicit usable info (see the analysis of encoded transmissions to and from spies during the cold war), but its still substantially harder to identify individual packages downloaded - with http, the info for an attacker is right there and they can move directly on to "oh, that web server is using package X which is vulnerable to exploit Y" with no further effort in analysis.  Security isnt about complete protection, its always about layers to make it more difficult for attackers.
Comment: @AustinHemmelgarn, HTTPS doesn't hide the size of the transfer, and transfer size alone will tell you what packages were downloaded for all but the smallest files.
Comment: @trognanders That is not my experience. I had to specifically search Google for one that allows HTTPs because my ISP runs (well-intended?) virus scans on HTTP traffic and blocked some packages as false-positive.
Comment: @AndreKR The mirrors list for CentOS specifies which ones do HTTPS, so that should be pretty easy without Google. Also, off topic, but this is the mirror I always use when possible. It is hosted by a local university. https://mirror.arizona.edu/
Answer: From a technical perspective the fact plain HTTP content can easily be cached by proxy servers can make quite a bit of difference when you need to manage and update more than a handful of systems.
Setting up local mirrors is often overkill and not practical, but when your proxy server can serve updates from a cache at LAN speeds, rather than every client in your network connecting to an online source...
Comment: I'd rather have a local mirror at 10Mb/s than a remote mirror at 9600bps.
Comment: Is something missing at the end? E.g., the implied *not overkill* is not that clear.
Comment: HTTP Caching is interesting. That definitely helps with edge-servers and fast downloads to the client machines. However don't you think at-least the keys should be securely transmitted? Otherwise manipulation in both ends (hard, but possible in my view) would cause malicious packages to be distributed. Don't you think?
Answer: The packages are signed by an off-channel method (GPG keys stored on your system).
The main use of having HTTP is to make it easy to have a dependency proxy between the Internet and your machines, which can save a lot of bandwidth and time by only having to download once (the first time) upgrades for potentially 1000s of (virtual) machines.
HTTPS prevents it (not completely, but makes it harder), because being end-to-end encrypted, you can't easily put something that'd intercept the downloaded packages to store them and serve them later.
Answer: Lots of mirrors will reply on HTTPS if you change the URL, even if the link to them is only HTTP. Using this is better than not verifying anything at all, but puts absolute trust in the mirror host. Using the official GPG signatures to verify the downloads leaves the trust with only parties you already trust completely.
If you follow the instructions here, you only need to trust the certificate for canonical.com, for example. https://ubuntu.com/tutorials/how-to-verify-ubuntu
Answer: A system time error could cause issues with HTTPS. It is not a real issue, but it is sometimes unnecessary.
An out of date system that don't have trusted certificates is a pain to get them updated.
Mirrors that need to respond to the same anycasted hostname.
It takes time to set up distributed mirrors with valid certificates.
Answer: CentOS distribution uses GPG to sign both rpm packages and yum/dnf repository metadata, so that MITM attack will be prevented.
See also How Fedora Secures Package Delivery, which is discussing Fedora, but package and repository metadata security tooling and policy is the same.


Regex pattern to find the longest vowel sequence

Question: My below code works for locating the first match of vowel(s), in this case 'ua' but how do I configure the regex to 1) search the entire string before ending at the first find and 2) once step 1 is fulfilled, determine which of all patterns shows the longest concurrency of vowels?
import re
s = "quality"
matches = re.search(r"[aeiou]+", s)
matchlist = matches.group().split(', ')
print(len(matchlist))

Comment: Grab all matches, then find the longest one, see [this demo](https://ideone.com/yiw5LZ).
Comment: Why you hating on `y`? It's a vowel sometimes too!!! `((?:[aeiou]|y(?![aeiou]))+)`
Comment: Mr Jibz, any feedback?
Comment: @WiktorStribiżew your solution was spot on
Comment: @Mr.Jibz Great, please consider upvoting/accepting the answer below.
Answer: Grab all matches, then find the longest one:
import re
s = "quality"
matches = re.findall(r"[aeiou]+", s) # Finds all chunks of vowel letters
print(max(matches, key=len))         # Gets the longest item in the list
# => ua

See the Python demo.


Finding the expected value of the cdf?

Question: I have this question on a homework assignment, and I'm not sure how to solve it.
Assume $X \sim \exp(\lambda=2)$, define $Y=F(x)$, where F(x) is the cdf function of $X$. Calculate the expected value of $Y$, i.e., $E(Y)$.
I thought maybe you could use the Law of the Unconscious Statistician and have the integral of $F(x) * f(x)$? Any help would be appreciated.
Comment: You made a good start.  Why not take the next step and evaluate that integral?
Comment: I wonder what the derivative of $\frac12 (F(x))^2$ equals?
Answer: Yes, you can definitely use LOTUS. Alternatively, you can use the Probability Integral Transform which says that the CDF of a continuous random variable follows the uniform distribution. You might want to see if you can arrive at the same result using both methods.

Finding the expected value of the cdf?


Convert raw image data to base64 encoded string

Question: I am downloading a thumbnail from dropbox using the following API:
https://www.dropbox.com/developers/documentation/http/documentation#files-get_thumbnail
This is part of my function from cloud code:
  }).then(function(oauthToken){
    /* Retrieve thumbnail image from dropbox */
    return Parse.Cloud.httpRequest({
      method: 'POST',
      url: 'https://content.dropboxapi.com/2/files/get_thumbnail',
      headers: {
        'Authorization': 'Bearer ' + oauthToken.get("accessToken"),
        'Dropbox-API-Arg': JSON.stringify({"path": dropboxFileId})
      }
    });

  }).then(function(imageResponse){
    if (log) {console.log(imageResponse);}
    var imageBuffer = imageResponse.buffer;
    var image = imageBuffer.toString("base64");
    response.success(image);
  }, function(error){
    response.error(error.text);
  });

Following is my imageResponse:
{ status: 200,
  headers:
   { server: 'nginx',
     date: 'Wed, 16 Mar 2016 04:30:54 GMT',
     'content-type': 'application/octet-stream',
     'content-length': '906',
     connection: 'close',
     'accept-ranges': 'bytes',
     pragma: 'no-cache',
     'cache-control': 'no-cache',
     'original-content-length': '906',
     'dropbox-api-result': '{"name": "HTS-logo-low-res.png", "path_lower": "/hts-logo-low-res.png", "path_display": "/HTS-logo-low-res.png", "id": "id:hrkr_mV5FYAAAAAAAAAAHw", "client_modified": "2015-04-05T04:16:15Z", "server_modified": "2016-02-13T06:08:02Z", "rev": "2a043d0c726", "size": 10506}',
     'x-server-response-time': '190',
     'x-dropbox-request-id': '04bb8d6b45511f2b2d7a278e230ea572',
     'x-robots-tag': 'noindex, nofollow, noimageindex' },
  buffer: <Buffer ef bf bd ef bf bd ef bf bd ef bf bd 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ef bf bd ef bf bd 00 43 00 06 04 05 06 05 04 06 06 05 06 07 07 06 ... >,
  cookies: undefined,
  text: '����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000C\u0000\u0006\u0004\u0005\u0006\u0005\u0004\u0006\u0006\u0005\u0006\u0007\u0007\u0006\b\n\u0010\n\n\t\t\n\u0014\u000e\u000f\f\u0010\u0017\u0014\u0018\u0018\u0017\u0014\u0016\u0016\u001a\u001d%\u001f\u001a\u001b#\u001c\u0016\u0016 , #&\')*)\u0019\u001f-0-(0%()(��\u0000C\u0001\u0007\u0007\u0007\n\b\n\u0013\n\n\u0013(\u001a\u0016\u001a((((((((((((((((((((((((((((((((((((((((((((((((((��\u0000\u0011\b\u0000\u0010\u0000@\u0003\u0001"\u0000\u0002\u0011\u0001\u0003\u0011\u0001��\u0000\u001f\u0000\u0000\u0001\u0005\u0001\u0001\u0001\u0001\u0001\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b��\u0000�\u0010\u0000\u0002\u0001\u0003\u0003\u0002\u0004\u0003\u0005\u0005\u0004\u0004\u0000\u0000\u0001}\u0001\u0002\u0003\u0000\u0004\u0011\u0005\u0012!1A\u0006\u0013Qa\u0007"q\u00142���\b#B��\u0015R��$3br�\t\n\u0016\u0017\u0018\u0019\u001a%&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������\u0000\u001f\u0001\u0000\u0003\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b��\u0000�\u0011\u0000\u0002\u0001\u0002\u0004\u0004\u0003\u0004\u0007\u0005\u0004\u0004\u0000\u0001\u0002w\u0000\u0001\u0002\u0003\u0011\u0004\u0005!1\u0006\u0012AQ\u0007aq\u0013"2�\b\u0014B����\t#3R�\u0015br�\n\u0016$4�%�\u0017\u0018\u0019\u001a&\'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������\u0000\f\u0003\u0001\u0000\u0002\u0011\u0003\u0011\u0000?\u0000�;ŷ��鱘\'[s,�\u0013L�\n���{\f�g޹\u000f��I�\\.�w\u0013��H~̡���\u0002�\u001b���\u000f\u0001���@�%�&�O��\u0004z����6�Z:X�"G;�GB}M%N�3��ͧ]4��̪��9`�������0�֕�+\u000b�t \u0006P�\u0001%�z��\u0003�R=ި�G$.� �U��h]���d�\u001d9����u���*O����q��|�\u0007\u0005\\�N\u000e\u0017\u0003�\u0000C�q��;�K���1\u001e��HR��z��~�N+���uy��d�بS咕�0e��91�\u001fC�\u0014���}z����.u\u0019Y�I\u0012�T.�\u0019~�\u0007ߦ\b��+���ߝ��W���_q��'
}

My code in XCode:
if let imageInBase64 = response as? String {
    print(imageInBase64)
    let decodedImage = NSData(base64EncodedString: imageInBase64, options: NSDataBase64DecodingOptions())
    imageView.image = UIImage(data: decodedImage!)
}

Following is the output for imageInBase64:
77+977+977+977+9ABBKRklGAAEBAAABAAEAAO+/ve+/vQBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSjvv73vv70AQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo77+977+9ABEIABAAQAMBIgACEQEDEQHvv73vv70AHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL77+977+9AO+/vRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDLvv73vv73vv70II0Lvv73vv70VUu+/ve+/vSQzYnLvv70JChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl677+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+977+9AB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC++/ve+/vQDvv70RAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjLvv70IFELvv73vv73vv73vv70JIzNS77+9FWJy77+9ChYkNO+/vSXvv70XGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eu+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/ve+/vQAMAwEAAhEDEQA/AO+/vTvFt++/ve+/vemxmCdbcyzvv70TTO+/vQrvv73vv73vv717DO+/vWfeuX8P77+977+9Se+/vVwu77+9dxPvv73vv71Ifsyh77+977+977+9Au+/vRvvv73vv73vv70PAe+/ve+/ve+/vUDvv70l77+9Ju+/vU/vv73vv70Eeu+/ve+/ve+/ve+/vTbvv71aOljvv70iRzvvv71HQn1NJU7vv70z77+977+9zaddNO+/ve+/vcyq77+977+9OWDvv73vv73vv73vv73vv73vv73vv70w77+91pXvv70rC++/vXQgBlDvv70BJe+/vXrvv73vv70D77+9Uj3eqO+/vUckLu+/vSDvv71V77+977+9aF3vv73vv73vv71k77+9HTnvv73vv73vv73vv71177+977+977+9Kk/vv73vv73vv73vv71x77+977+9fO+/vQcFXO+/vU4OFwPvv70AQ++/vXHvv73vv70777+9S++/ve+/ve+/vTEe77+977+9SFLvv73vv71677+977+9fu+/vU4r77+977+977+9dXnvv73vv71k77+92KhT5ZKV77+9MGXvv73vv705Me+/vR9D77+9FO+/ve+/ve+/vX1677+977+977+977+9LnUZWe+/vUkS77+9VC7vv70Zfu+/vQffpgjvv73vv70r77+977+977+9353vv73vv71X77+977+977+9X3Hvv73vv70=

When I run this, I do not get an image displayed. I suspect that I am not properly handling the response from Dropbox before converting it to base64 string. Dropbox state that their responses are raw image data.
Any help will be much appreciated. Thanks.
Comment: http://stackoverflow.com/questions/29365145/how-to-encode-string-to-base64-in-swift
Comment: I think your `options` might be wrong. Try `base64EncodedString: encodedImageData options: .allZeros` instead.
Answer: Figured it out & thanks for those who answered. The issue was with Parse.com module Parse.Cloud.httpRequest which works slightly different when you are self-hosting parse-server vs Parse.com. I just needed to include encoding: null as an option in the module and everything works fine. Code below:
  }).then(function(oauthToken){
    /* Retrieve thumbnail image from dropbox */
    return Parse.Cloud.httpRequest({
      method: 'POST',
      url: 'https://content.dropboxapi.com/2/files/get_thumbnail',
      headers: {
        'Authorization': 'Bearer ' + oauthToken.get("accessToken"),
        'Dropbox-API-Arg': JSON.stringify({"path": dropboxFileId})
      },
      encoding: null
    });

  }).then(function(imageResponse){
    if (log) {console.log(imageResponse);}
    var imageBuffer = imageResponse.buffer;
    var image = imageBuffer.toString("base64");
    response.success(image);
  }, function(error){
    response.error(error.text);
  });


Combinatorics with binary strings

Question: a)
I'm currently trying to find how many binary strings of length 10 have at least one 1 and one 0, and I've concluded that this is $2^{10} - 2$. This is because the only strings that violate the condition are 1111111111 (ten 1's), and 0000000000 (ten 0's).
b)
For a binary string with exactly five 1's or begins with a 0, I currently have $10 \choose 5$ + $2^9$ - $9 \choose 5$. This is because we want to select 5 spots out of the 10 for exactly five 1's, and then add that with how many strings can start with a 0, and the subtract $9 \choose 5$, which is how many strings begin with a 0 and have exactly five 1's.
c)A binary string has 01010101 appearing somewhere in the string. This is the only one I have no idea how to approach. I understand 01010101 can appear in three positions in the binary string of length 10 (front, middle, and end), but I have no idea how to combine all of these, or what to exclude.
d)There are five 1's in the string or it has an even amount of 1's in the string. A string with five 1's would be $ 10 \choose 5$, and a string with would be $ 10 \choose 2$, $ 10 \choose 4$, $ 10 \choose 6$, $ 10 \choose 8$, and $ 10 \choose 10$. So can I use the sum rule to combine all of these or is there an easier way?
Is my thinking for these problems correct?
Comment: Yes it is correct.
Answer: To explain the answer further, let us treat our universal set, $U$, as all binary strings of length 10.  By theorem or earlier example, we know that there are $2^{10}$ different such strings (seen easily by multiplication principle).
The negation of the phrase "at least one $1$ and at least one $0$" is:

no $1$'s or no $0$'s

Noting that there is no overlap between those cases, this leads us to discover that we may partition our universal set into the following three disjoint sets:

$A$: There are no $1$'s (only possibility is then $000~000~000~0$)
$B$: There are no $0$'s (only possibility is then $111~111~111~1$)
$C$: There is at least one $1$ and at least one $0$

As these form a partition (i.e. $A\cup B\cup C = U$ and $A\cap B = A\cap C=B\cap C = \emptyset$), we know that $|A|+|B|+|C|=|U|$
so:
$$2^{10} = |U| = |A|+|B|+|C|=1+1+|C|$$
and
$$|C| = 2^{10}-2$$
Answer: For part c), we can think of 01010101 as another string S. Because we cannot have S appear twice, we are looking for all binary strings of length 3 with one S. Then, we simply have $3\cdot2^2$ possible strings because for each of the 3 positions of S there are $2^2$ other binary strings of length 2.
The only case where it overcounts is (I believe) S01 = 01S. All binary strings xSx is different from Sxx and xxS because the third element of xSx must be a 0 while the third element of the latter two must be a 1. But for the latter two to the the same, S01 = 01S (because the first, second, second last and last characters must be 01 to match S) and therefore we have only overcounted once.
Hence our final answer is $3\cdot2^2 - 1$.
Answer: More generally the number of $n$ bit strings with at least $k$ zeroes and $j$ ones is
$$
2^n-\sum_{0\leq m \leq k-1} C_m^n - \sum_{0\leq m \leq j-1} C_m^n
$$
where $C_m^n$ is the binomial coefficient, provided $j+k\leq n.$

Combinatorics with binary strings


Sudden note end notation

Question: I've been studying musical notation for some time now and I decided to take a shot at writing my own piece. It's going pretty smooth, but I have a question to make sure I follow common practices and that my music is readable for people who didn't hear the piece.
The question is how to symbolically distinguish between a long note or chord coming to an end gradually and one that is suddenly broke.
A great example of a latter, that comes to my mind is a signal that is played in Cracow, Poland everyday on the hour which has a distinct interruption which, according to the legend, memorializes the trumpeter who was shot by a mongol archer while playing the signal to alert the city of the invasion of Tatars.
Here is the link to the video:

Case of the St. Mary's signal is a bit different since there's a pitch change at the very least of the signal. What I'm looking for is a way for denoting a sudden end of a single note.
For the score I'm working on it is essential to clearly indicate such abrupt break of long notes. I'd appreciate any help. Thanks in advance!
Answer: I actually saw this just yesterday in scores written by Bruce Broughton (Silverado, JAG, Tombstone, Dallas, Hawaii Five-O).
The way he wrote it was a note for the bulk of the duration tied to a shorter note with a staccato mark above it (first measure in the example below).
<code>X: 2
M: 4/4
K: C
L: 1/4
|B2-.Bz|F2-!>!F-F|FGAB|e2d2|]
</code>
Generally if you want to have an articulation occur at the end or middle of a note, separate the full note value into tied notes that add up to the full value to create noteheads where you want the articulation to occur (second measure in the example above).
This is not merely the style of Bruce Broughton, this is how the book Behind Bars says to do it, which is likely where Mr. Broughton got the idea from, since he is a fan of the book. Any serious study of notation should include that book.
Comment: That's what I thought at first but I wanted to confirm my guess and see if there are different suggestions. And thanks for the book recommendation!
Comment: In the first measure of the example, when the note should end? On the third or fourth beat?
Answer: In the case of Cracow's signal the effect of abruptness is created by shutting off the note right after it starts. So it will be hard to do anything specific on the long note to finish it in abrupt way (at least I can't think of anything).
I think a regular fermata that inidicates that note should be played longer but also indicates to the performer that she should wait for the conductor's singal to end could be the best notation in this situation.
So for example if a whole note should be 'broken' earlier you could write a half note prolonged by fermata instead
Comment: The note in the OP video is just a staccato. Using a fermata and relying on a conductor 1) presumes there's a conductor, and 2) begs the question of how to notate the conductor's score so the conductor knows to signal an abrupt cutoff.
Comment: Fermata won't do since I need to precisely define a point at which the note should stop.

Sudden note end notation


Put social Icons next to body field ($content['body'])

Question: I want to align my social icons vertically next to the body field, in my node.tpl.php file the body is included in the $content with everything else. The social icons sit a few lines above and look like this in my node.tpl.php file:

  <?php print render($main_node_social_share);?>

How can i get $main_node_social_share to render right before the $content['body'] field?
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
print render($content);

Answer: Try some thing like this in custom module and see it helps.
function modulename_page_alter(&$page) {
  $social=array(
    '#markup'=>'

',
  );
  array_unshift($page['content']['system_main']['nodes'][1],$social);

}

Comment: Although this didn't exactly work in my situation it is the  right solution.  Thanks


Tilde "~" expression not functioning in "R"?

Question: The tilde expression is not working on my RStudio! I am using a windows 10 OS.
Update : After looking more carefully(thanks to Dason) It seems the "~" is pointing to "user/Documents/" rather then "user/". is there any work around?

Any help?
Comment: Also never post an image when you can post the actual code/results.
Comment: Are you sure "~" points where you think it points?
Comment: no one mentioned `path.expand('~')` yet?
Comment: Ideally it should point to home directory, shouldn't it?
Ok Thanks, I will keep that in mind next time.
Comment: Dear Dason, Yes it's actually pointing to a different folder the "documents" folder. How can I rectify that?
Comment: You've not shown a single call with `~` working. What does `setwd("~/")` do? Then what does `getwd()` say after that? How do you assume it points to `user/Documents`?
Comment: Hello spacedman, actually I  'setwd("~/")' is working fine and 'getwd()' showing the path of documents folder. That's how I got to know the actual point of '~'.
Comment: Also `normalizePath("~")`, which really just runs `path.expand` here.
Answer: The home directory in Windows R is set using the environment variable R_USER Set this using Windows (search from the Start Menu for "environment variable"). Whatever you set this to will become what R uses for ~. I have mine set to C:\Users\trehman\R.
Here is how mine looks.
Comment: Thanks TARehman, Looks like a promising solution, will let you know after trying it. Thanks again for you time N help.
Comment: i added [~] to both user and system environment with value [C:/users/user/] but still no change can you guide me with a bit elaboration.
Comment: @Mrinal9 Does it look like mine?
Comment: No actually there is no R_user variable in my Environment variable. I had added [~] as a variable with a value to my home folder. Let me try like yours & see.
Comment: Yep! Now its working fine. Thanks a ton again for the generous help sir.
Comment: On Windows you can set either `R_USER` or `HOME` with priority given to `R_USER`. A bit more information here: https://cran.r-project.org/bin/windows/base/rw-FAQ.html#What-are-HOME-and-working-directories_003f
Answer: As you found out yourself, R's ~ points to your documents folder. An easy way to work around this could be to start the paths you want to reference with ~/../. So your setwd call would look like this:
setwd('~/../{your actual path from home}')

The same problem occurs on my Windows PC. I do not have a Linux machine at hand to test whether it is the same there. R gets this variable from the R_USER environment variable. You can override that in your R environment startup file. This issue is not specific to RStudio and also occurs when you start an R session from the command line.
Comment: Thank you Sir for your help, but can you tell me why its not working? or it does not work in any windows system?
Comment: @Mrinal9, I added some extra info. I hope it helps.
Comment: Can you please add a little bit info on how to & what to edit to R environment startup file?
Thanks,
Mrinal.
Answer: At startup, R looks for Renviron.site in the R_HOME directory. Open and edit it
file.edit(file.path(Sys.getenv('R_HOME'), 'etc', 'Renviron.site'))
Define R_USER in that file with the path you want '~' to point to:
R_USER = 'C:/Users/USERNAME'
References:
R for Enterprise: Understanding R's Startup


Change format of IIS HTTP Error logging

Question: HTTP.sys by default creates error log files under C:\Windows\System32\LogFiles\HTTPERR.
Is it possible to change the format of these log files to include other fields including cs-host and cs-uri-query?
Answer: Expanding on the earlier answer you need to assign a value to the following registry entry for chosen fields.
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters] "ErrorLoggingFields"=dword:0fc884c7
Basically the value is a sum of all the bit values from the list below for whichever fields you want included.

Log field
Logged by default
Bit value

Date
Yes
0x00000001

Time
Yes
0x00000002

Client IP Address
Yes
0x00000004

Server Computer Name
No
0x00000020

Server IP Address
Yes
0x00000040

Method
Yes
0x00000080

Protocol Status
Yes
0x00000400

SC-Bytes
No
0x00001000

CS-Bytes
No
0x00002000

Time Taken
No
0x00004000

Server Port
Yes
0x00008000

User Agent
No
0x00010000

Cookie
No
0x00020000

referrer
No
0x00040000

Protocol Version
Yes
0x00080000

Host
No
0x00100000

Client Port
Yes
0x00400000

URI
Yes
0x00800000

SiteId
Yes
0x01000000

Reason Phrase
Yes
0x02000000

Queue Name
Yes
0x04000000

Stream Id
Yes
0x08000000
Comment: See [HTTP_LOG_FIELD_ Constants](https://docs.microsoft.com/en-us/windows/win32/http/http-log-field--constants) from http.h for field descriptions.
Answer: This list from Microsoft is a bit of outdated, as it does not include the recently introduced "streamid" field present in Windows Server 2016, but it definitely can help you specify the fields you need.
https://docs.microsoft.com/en-us/windows/win32/http/error-logging-in-windows-server-2003-sp1
To quickly sum all the Hex values, just type them in Google as is (in this example I choosed to include all fields, including the new streamid fields available since Windows Server 2016 and above) :
0x00000001 + 0x00000002 + 0x00000004 + 0x00000020 + 0x00000040 + 0x00000080 + 0x00000400 + 0x00001000 + 0x00002000 + 0x00004000 + 0x00008000 + 0x00010000 + 0x00020000 + 0x00040000 + 0x00080000 + 0x00100000 + 0x00400000 + 0x00800000 + 0x01000000 + 0x02000000 + 0x04000000 + 0x08000000
That will return 0xFDFF4E7 !
Just create then execute a new .REG file with this content :
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters]

; WIN 2016-2019-2022
; LOG THE FOLLOWING #Fields: date time s-computername c-ip c-port s-ip s-port cs-version cs-method cs-uri cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-bytes cs-bytes time-taken s-siteid s-reason s-queuename streamid
"ErrorLoggingFields"=dword:0fdff4e7

Answer: Here is a workaround:

Create a header file using the columns of your HTTPErr log file in the same order and save it as - header.txt

Use the following format for your SQL query
LogParser.exe "select sc-status, s-reason, s-queuename, count(* ) from C:\temp\HTTPLogs*.log group by sc-status, s-reason, s-queuename order by count(*) desc" -i:TSV -iseparator:space -iHeaderFile C:\temp\HTTPLogs\header.txt

Change format of IIS HTTP Error logging


Find the Fourier series expansion of a function.

Question: A periodic function is defined by
$$ f(t) = \begin{cases}
      t^2 & 0 \leq t \lt 2 \\
     t+4 & 2\leq t\lt 4 \\
      8 & 4\leq t
   \end{cases}
$$
and $f(t) = f(t+4).$
How would I find the Fourier series expansion?
Comment: $f(x) = f(x+4)$ means $f(x) = \sum_{n=-\infty}^\infty c_n e^{2i \pi n x/4}$ where $c_n = ?$ (and it doesn't always converge, in general it is only a formal series, that you have to prove being convergent to $f(x)$)
Comment: By using the formula, maybe ?
Comment: Note that the definition is incoherent. For example, $f(5)=8$, but $f(1+4)=f(1)=1$.
Answer: Hint:
By parts,
$$\int t^2\sin t\,dt=-t^2\cos t+2\int t\cos t\,dt,$$
$$\int t\cos t\,dt=t\sin t-\int\sin t\,dt,$$ and similarly for the cosine.
Comment: Stupid downvote.
Comment: I'll upvote it  because I think it's just the right response to such questions.  "Here, let me announce to the world that I haven't been to lecture all semester."
Comment: @B.Goddard: don't misunderstand my post. This is a true hint, that is sufficient to carry out the whole computation.


PHP file write permission

Question: I have two files, one php file and one log file. The permission has been changed to the following:
-rwxr-x--- 1 www-data www-data  294 2012-06-25 10:17 function.php

-rwxr-x--- 1 www-data www-data    0 2012-06-25 09:53 log.txt

The permission is set to 750.
when I call function.php, I receive the following error message
fopen(log.txt): failed to open stream: Permission denied

This is the line :
$fp = fopen("log.txt","a");

I am very confused. I have php and the file to be written both under www-data now, so why would there be any permission problem?
Please help
Comment: System log says...?
Answer: If you aren't on Windows, you can check if your process is really own by www-data by
$processUser = posix_getpwuid(posix_geteuid());
print $processUser['name'];

Check the directory too ! Are you sure that you are in the right dir ?
echo getcwd();

PHP file write permission


submenu bootstrap

Question: Se alguém poder me ajudar estou tentando criar um sub-menu de preferência que abra para a direita dentro de administrativo abre-se acesso, funcionários e painel de controle dentro de acesso teria dois sub menus cadastrar acesso e listar acesso, segue o código.

    <button type="button" class="btn btn-primary">Administrativo</button>
    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"></button>

Acesso

Cadastrar Acesso

Listar Acesso

Funcionários

Painel de Controle

Answer: Encontrei a solução conforme sua ajuda paulo, encontrei o código abaixo e fiz as alterações para me atender.

$(document).ready(function(){
  $('.dropdown-submenu a.test').on("click", function(e){
    $(this).next('ul').toggle();
    e.stopPropagation();
    e.preventDefault();
  });
});
.dropdown-submenu {
  position: relative;
}

.dropdown-submenu .dropdown-menu {
  top: 0;
  left: 100%;
  margin-top: -1px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Multi-Level Dropdowns

In this example, we have created a .dropdown-submenu class for multi-level dropdowns (see style section above).

Note that we have added jQuery to open the multi-level dropdown on click (see script section below).

    <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorials

    </button>

HTML

CSS

        New dropdown

2nd level dropdown

2nd level dropdown

            Another dropdown

3rd level dropdown

3rd level dropdown

Answer: Se quiser deixar mais interessante, use a função animate da biblioteca Jquery
Segue o código:
<!DOCTYPE html>

    <title>

    </title>

opção 1

opção 2

opção 3

Comment: obrigado pela ajuda paulo, mas queria fazer algo mais simples mesmo so nao entendi pq nao esta funcionando o submenu
Comment: Raramente é o código 'alvo'!
Geralmente é alguma alteração acidental em outra parte do projeto.
Answer: Raramente é o código 'alvo'!
Geralmente é alguma alteração acidental em outra parte do projeto. Então só com esse código que passou provavelmente não vamos descobrir.
Você pode forçar o menu a abrir com javascript, ou pode debugar até encontrar a alteração. Eu não faço nenhuma das duas coisas. Eu pego o exemplo oficial (do menu drop down abrindo) e vou customizando até encontrar o problema, comparando com meu código problemático.
Trabalho espartano! Copiar, Colar, voltar, atualizar, etc. Use o sublime text para editar o código.
Comment: vou fazer isso.

submenu bootstrap


How to solve this system of 100 differential equations?

Question: $x'_i = x_{i-1} + x_{i+1} - 2x_i$ for $1 \le i \le 100$ given $x_{0}=x_{101}=0$
I've tried creating a matrix and dabbled with eigenvalues but have no idea what I'm doing with them.
So because it's a toeplitz matrix, i've gathered that I should have something like 1+ $cos(\frac{k*pi}{101}$)? is that the correct way to proceed?
Comment: This gives you a so-called _tridiagonal_ matrix that is also Toeplitz. This means there is a closed form for the eigenvalues, see [this wikipedia paragraph](https://en.wikipedia.org/wiki/Tridiagonal_matrix#Eigenvalues).
Comment: I just edited it! sorry about that
Comment: Is this to do with numerics? Such as a finite difference scheme applied to an ODE or PDE?
Comment: What exactly do you want with these equations? An explicit expression for all components? Or a solution in terms of matrix exponential suffices? Do you have initial values for $x_i(t)$?
Comment: Just a tip - If you don't know how to do it with $100$ simultaneous equations, try an easier case (do it only for $2$ equations).  This strategy can be hugely useful in math.
Comment: @Mattos it looks like a numerical way to solve $\partial_t y = \Delta y$.
Comment: I'm new to this formatting sorry. I tried with just two, got $x_1 = x'_2 - x'_1$ but I'm not sure how useful that is. I believe this is a ODE @mattos
Comment: @TZakrevskiy That is what I thought originally, a second order central difference, except the RHS has no $(\Delta x)^{2}$ term in the denominator.
Comment: Related: http://math.stackexchange.com/q/2057100/5531 and http://math.stackexchange.com/q/2055812/5531
Comment: Not interested in the asymptotic behavior, but more about the method. So I take it creating a triagonal matrix is the way to go at it?
Comment: @Mattos if you know how to solve $x' = Ax$, you can solve $x'=cAx$ for constant number $c$, just rescale your time variable. Maybe they omitted $(\Delta x)^2$ for simplicity.
Comment: as for the related links posted above, if the solution was 1+cos(k*pi/101) wouldn't the asymptotes be at y =2 and y = 0 for all x? or k in this case.
Comment: Hint: the eigenmodes has the form $x_k \propto \sin\left(\frac{\pi mk}{101}\right) \exp(\omega t)$ where $m \in \mathbb{Z}$.
Comment: @achillehui how does that compare to the closed form a + 2sqrt(bc)cos(kpi/n) ? I haven't seen that form anywhere, trying to find a link about it.
Comment: No idea about your expression, but $\omega$ for the $m^{th}$ mode in above ansatz is $-2(1 - \cos\frac{\pi m}{101})$.
Comment: don't i just find the eigenvalues and then solve the matrix using the eigenvalue and calculating the determinant?
Comment: okay, I figure out what your closed form $a + 2\sqrt{bc}\cos(k\pi/n)$ refers to. If you substitute $(a,b,c,k,n) by (-2,1,1,m,101)$ in this closed form, you get the $\omega$ I mentioned above.
Comment: Is there a way to use matlab or any other scripting language to find an easier way to solve for the solution?

Just to double check
Answer: Compiling the hints of achille hui: Get your solution in form of a sine series,
$$
x_k(t)=\sum_{m=1}^{100}a_m(t)\sin\left(\pi·m·\frac{k}{101}\right)
$$
Then
\begin{align}
\dot x_k(t)
&=\sum_{m=1}^{100}\dot a_m(t)\sin\left(\pi·m·\frac{k}{101}\right)
\\
&=\sum_{m=1}^{100}a_m(t)·2\left(\cos\left(\frac{\pi·m}{101}\right)-1\right)·\sin\left(\pi·m·\frac{k}{101}\right)
\end{align}
so that
$$
\dot a_m(t)=-4\sin^2\left(\frac{\pi·m}{2·101}\right)·a_m(t)
$$
is a decoupled system.
You get the coefficients $a_m(0)$ for the initial state either by a sine transformation formula or by the Fourier transform after you extend the points by $x_{-k}(0)=-x_k(0)$ to the index set $[-101, 100]$ to a periodic sequence with period $202$.


Registering a new user overwrites current user session - why?

Question: I've come across an issue when registering new users with my app. The behaviour looks to be by design, but I don't understand why.
My problem is as follows (and I know it's a bit of an edge case):

User browses to my site's login page in two separate tabs in the same browser.
In the first tab, the user logs in and is correctly redirected to my home page.
In the second tab, the user follows my signup logic (which doesn't require any kind of page refresh, it's all done with client side code that culminates in a jQuery AJAX POST to the built in ServiceStack RegistrationService's /register endpoint)

Instead of creating a new user, the second user's details overwrite that of the logged in user's UserAuth record, and the first user can no longer log in.
Looking at the code in ServiceStack.ServiceInterface.Auth.RegistrationService, this behaviour appears to be 100% intentional:
<code>var session = this.GetSession();
var newUserAuth = ToUserAuth(request);
var existingUser = UserAuthRepo.GetUserAuth(session, null);

var registerNewUser = existingUser == null;
var user = registerNewUser
            ? this.UserAuthRepo.CreateUserAuth(newUserAuth, request.Password)
            : this.UserAuthRepo.UpdateUserAuth(existingUser, newUserAuth, request.Password);
</code>
Once the first user is logged in, the session cookie for that user gets sent with the registration request, causing the existingUser variable in the code above to be populated with the UserAuth for that user, which is then updated with the registering user details.
Can anyone explain why the code's been written in this way? And is there any way around it without replacing the RegistrationService with my own implementation?
Comment: That is pretty weird. Now that I think about it, most sites do require you to sign out before you can register an account though. Maybe that could be a workaround for you?
Comment: Not really - if you stay in a single tab, you would have to log out before you can get back to the registration screen, but if the user has the site open in multiple tabs it becomes hard to enforce that on the client side. Ideally I'd be preventing it server side, but this would involve replacing the built in ServiceStack registration pieces with my own and I wanted to understand the reasoning behind the existing code first.
Answer: This is the feature that lets you to auto-merge different Auth Providers into the same account in ServiceStack.
Comment: There's some hooks in RegisterService like a static ValidateFn where you can run custom logic at the start of the Registration request and a RegistrationValidator you can override, but don't be afraid of customizing a local copy of [RegistrationService](https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.ServiceInterface/Auth/RegistrationService.cs) and customizing it to suit your needs - it's a far better option than trying to getting the default impl to support all use-cases.
Comment: Thanks. We see that if you register multiple times with different OAuth providers that have the same email addresses, the accounts get merged and this is definitely the behaviour we need. But the auto-merging of new registrations with a currently logged in user is causing us problems - is there any way of preventing this, short of creating our own registration service?
Comment: @mythz, I'm going to end up creating my own copy of RegistrationService as you suggested because for my application, I need to restrict account creation to admins and disallow it if not logged in. But wouldn't it be more RESTful to update the existing user on a PUT and create a new user on a POST? I was shocked to discover that this wasn't the default impl.
Comment: @MattWelch Shocked? You can use either and this supports both, `PUT` is for updating a resource (like a document) at the specified url which isn't what happens nor is it 100% idempotent so `POST` is preferred, which also happens to be more practical since it's supported in HTML Forms. You can also add Request Filters for what you want otherwise using your own service does offer greater control.
Comment: Ahh I see. I guess I was thinking of the user record as a 'resource,' and `POSTing` was definitely updating the logged-in user. It appeared idempotent at first glance, aside from the LastModifiedDate. And perhaps in my somewhat simple use case, it is. In any event, I sheepishly realized I can make it work easily without creating my own service anyway if I just make the `POST` call from the client not pass credentials when I want to create a new user rather than update the logged in user. Thanks for the explanation!


Error - ESLint: 7.32.0 ESLint couldn't find the config "standard" to extend from

Question: We have a CircleCI Pipeline. We have a older version of eslint i.e. 5.10.0 which was around three years ago installed and now client wants to upgrade node version to 16 and upgrade related packages.
I have modified package.json file and changes eslint version from "eslint": "^5.10.0" to "eslint": "^7.10.0".
Now, while pushing changes on branch CircleCI test execution fails with the below error.:

Oops! Something went wrong! :(
ESLint: 7.32.0
ESLint couldn't find the config "standard" to extend from. Please check that the name of the config is correct.
The config "standard" was referenced from the config file in "/home/xxx/xxx/.eslintrc.yml".

I have googled for this issue but did not find the proper solution for this.
I have tried to

Removed .eslintrc.yml file by guessing that it can be created automatically.
Try to run the command yarn run eslint --init inside package.json under script tag
"scripts": {
"test": "yarn run eslint --init && yarn lint && yarn flow && yarn jest",
}
But here, CircleCI pipeline is used so eslint --init command will ask question
How would you like to use ESLint?
We don't have any provision in CircleCI during automated file and test execution to provide any answer.
Answer: I had a similar case, where this error was due to my eslint version being too new compared to the one required by standard.
Here are some steps you can try to verify whether that's the case for you as well:

Locally in your project, run npm init @eslint/config (will ask you some questions and generate a new .eslint.{js|yml|json} out of it)
When asked "Which style guide do you want to follow?" reply standard

at this point, you should see something on the line of
The style guide "standard" requires eslint@^7.12.1. You are currently using eslint@{version}
Do you want to downgrade?

choosing "No" will warn you as follow and cause the error you mentioned when trying to execute linting.
Note: it might not work since ESLint's version is mismatched with the standard config

In my case the eslint version was differing by major (8.11.0) which makes it more obvious, but it looks very similar to what you have too.
If by this point you figured that's indeed the issue, here are some alternatives that might help:

Downgrade eslint (easy one but won't work in the long run if you like your dependencies to be up-to-date)
Switch to another style guide which doesn't have this limitation with eslint version (eg. airbnb or google's are suggested by the config setup)
Switch to using standard directly instead of going through eslint

I am no expert in js world, so please feel free to point out anything I missed
Answer: in my case, I fixed it by installing eslint-config-standard
npm i eslint-config-standard