css styling of points in figure

Question: I created an nvd3 type graph with the rCharts package. I saved it in a standalone html and am importing it into an rmarkdown document with .

I looked at the html source in Chrome and Firefox via the 'inspect element' feature and found that the following edits to the css:
.nvd3.nv-line .nvd3.nv-scatter .nv-groups .nv-point {
    stroke-width: 10px;
    fill-opacity: 1;
    stroke-opacity: 1;
}

gives:

which is the effect I want to obtain. However, if I insert the above code into the css, it is not 'picked up'. Other stylings are picked up, so the css is being read, but the above seems to be discarded. Any ideas?
The html figure is here: https://gist.github.com/anonymous/b187e77d795e5bf96f51
EDIT Cracked this one thanks to jbaums and a hint by sal niro. Here's the workflow to transform an rCharts nPlot with 'lineChart' into a combination of 'lineChart' and 'scatterChart'. This is the relevant part of your rmarkdown code:
 ```{r 'Figure'}
require(rCharts)
load("data/df.Rda")
# round data for rChart tooltip display
df$value <- round(df$value, 2)
n <- nPlot(value ~ Year, group = 'variable', data = df, type = 'lineChart')
n$yAxis(axisLabel = 'Labor and capital income (% national income)')
n$chart(margin = list(left = 100)) # margin makes room for label
n$yAxis(tickFormat = "#! function(d) {return Math.round(d*100*100)/100 + '%'} !#")
n$xAxis(axisLabel = 'Year')
n$chart(useInteractiveGuideline=TRUE)
n$chart(color = colorPalette)
n$addParams(height = 500, width = 800)
n$setTemplate(afterScript = '<style>
  .nv-point {
    stroke-opacity: 1!important;
    stroke-width: 6px!important;
    fill-opacity: 1!important;
  }
</style>'
)
n$save('figures/Figure.html', standalone = TRUE)
```

Comment: you likely need to do this through the JS through an `append().attr()` function
Comment: @salniro, Oh I have no idea what that involves! any hint appreciated, thanks.
Comment: I had the same gotcha with D3. Needs to be done when adding the `svg` element in the JS hope you find it!
Comment: Thanks, I can see the svg element when I inspect the code, so I'll see if that gets me anywhere. Also, I'm reading this: http://stackoverflow.com/questions/710275/how-to-add-update-an-attribute-to-an-html-element-using-javascript, but I'm none the wiser.
Answer: If you specify the rules as !important, then they won't be overruled later (though support for !important is limited in some old versions of IE).
Add the following between the  tags of your html file:
.nv-point {
  stroke-opacity: 1 !important;
  stroke-width: 10px;
  fill-opacity: 1 !important;
}

Rendered in Chrome 39.0.2171.95 m:

And in Firefox 34.0.5 and IE 11:
Comment: haha I always thought that was just a user comment when I saw it
Comment: @jbaums, thanks! Indeed, that works (took me a little while to test I could only make it to work within the html inside between ``
Answer: How to highlight a single point
I was working on a solution on how to highlight single points within the line and wanted to share it, since I did not found something similar yet:
var highlightSinglePoint = function(point){
    var selector = 'nv-point-'+point;
    var x = document.getElementsByClassName(selector);
    x["0"].style["fillOpacity"] = "1";
    x["0"].style["strokeWidth"] = "5px";
    x["0"].style["strokeOpacity"] = "1";
}

You might also want to reset these css styles on your lastly highlighted point before highlighting another one.
Note: Selecting 'nv-point-XYZ' will select point XYZ of all your d3 linecharts. So if you have multiple charts in your application, then dont forget to adapt the selecter with a HTML id of your chart or whatsoever.

css styling of points in figure


What does this mean (the treble clef part) and how to play it?

Question:
This is the accompaniment piece for a clarinet solo and I do not know how to play this measure.
Answer: It looks like a tremolo. It is played as a oscillation between the top two notes (I'm guessing a A and a D) and the lower note (I'm guessing an F). The dotted half-note (written on each stem) indicates either 3 quarter-note beats or 6 eighth-note beats (or the equivalent); the 6 eighth notes in the other staff probably mean the latter. The three lines connecting the upper notes mean to (approximately) play the oscillation as thirty-second notes. On a keyboard (which this looks like it's from) this gives a shimmering effect to the chords. It's a bit like a trill but with larger intervals and more notes.
Comment: Good answer, but the time is almost certainly 6/8, which means two beats of dotted minims/half-notes.
Answer: It's a tremolo, which for a pianist means to alternate very rapidly between the two notes/chords.  Here's a video that shows you how to do it.
Answer: Ok, I could not leave it.
those answers are usually called community wiki aren't they?

thanks to @BrianChandler
and @AlexanderWoo
Comment: This is just not what is indicated: the tremolo should go between the two notes/chords indicated by the notes with a duration of the bar: i.e. DA - F - DA - F and so on.
Comment: No - this is wrong - the A and D are played simultaneously, alternating with the F being played by itself.
Comment: As of this comment, what is notated here is 32nd notes, not tremolo.
Comment: @ToddWilcox, yes, but this is how it looks like when you unfold the example of the OP.


User has excessive rights to W2k8r2 server even when she is a normal user

Question: Really wierd issue this one.  I have a user whose PC I have just joined into a domain which is simply a single Windows 2008 R2 server.
All users is map to a SHARE that contains their home folders so each user should only see his/her own folder.  But for this user after she logon to the domain from her PC, she is able to access all the other users home folders with full permissions!
I have checked her grouping and share+ntfs permission - all seem correct; effective permission on her account show everything is in order and that she does not have access to any folders except her own. Other users are not having this issue.
Here comes the wierd part:

If she use another PC, her access to other folders on that same SHARE are correctly
restricted.
If another user logon from her PC, that user access is also correct.
But if she logon from her own PC, she get full rights to the server!

How can this be happening?
Comment: I think this one might be better for Serverfault
Comment: I'm not a experience Windows guy so any facepalm answer will still be welcomed.
Comment: What rights does she have locally on that machine? Has she been assigned any extended rights on the machine under local group policy\computer configuration\security settings that may be impacting on things?
Comment: Weird problem. So weird that it sounds like there's a facepalm kind of answer to it.
Comment: is she an admin of her own PC?
Comment: Yes she is local admin.  The issue is not access to local drives.  She is map to a windows server share, and on her PC and only her PC, she is able to access all the folders in that share.
Comment: Just to add that we never found out why this was happening.  What we did was to delete those user accounts that got this unexplained elevated admin rights and recreated the users again.  After this, the rights appear correctly as expected.
Answer: If the homefolders are stored on the local disk, it might be that you have set her permissions to local administrator.
Comment: All users home folders are on the w2k8r2 server and accessible by a share.  Its this share thats giving her excessive full access but all the permission properties i've checked looks ok.
Comment: You say that the share is on a server. And that her computer is a server. Are they in fact the same server?
Comment: Her computer is a normal Windows 7 PC.  Server is Windows 2008R2 with folders shared out.  If she logon from her PC to the domain, she get full access to the servers' share when she should not.
Answer: You have to run some basic tools to check the rights.

Test Effective File/Folder permissions. That is both share and ntfs.
Run RSOP for that user to evaluate group policies. Also check mappings and verify no permissions from elevated groups (if the user was in several groups and recently demoted) are not overlapping.
Check effective permissions for each group that the user is a member of.
Try resetting user account. Check logon scripts as well.
Comment: Simply disable, reset the password and re enable the profile. If the user is using a roaming profile, please check the settings as well. Re map all the mapped folders and printers. Apply a deny permission for the other shares which the user has exclusive access and check whether it propagates to this specific share (overlapping).
Comment: I have reset the user account and computer account but it is still having full admin rights to the server's shares.  I have also run gpresult /v on the pc but not sure what i should look out for.  Any further hints?
Comment: Run the command after login as that specific user on Windows 7. When running the gpresult, you should also use /r option. Or else, if you wish to perform remotely, please use /user [\] parameters. That should reveal any hidden configuration. You could also use auditing to understand the access behavior. Enable auditing for the specific share.
Comment: Thanks I will read up on RSOP.  How do I reset a windows user account?  BTW I have already check the basic obvious stuff like share/ntfs permission, group membership.
Comment: Additionally, reset the computer account and check. This is not necessary but I am suspecting a different possibility. Thank you!
Answer: This can occur when the Windows Fast Logon Optimization feature causes Windows Explorer to start before the logon scripts run. Having the Group Policy setting of 'Run Logon Scripts Synchronously' enabled and the setting 'Always wait for the network at computer startup and logon' settings enabled should fix this issue as described in this Microsoft Support Article.
More information on managing settings with Group Policy can be found on the Manage and Operate Windows 7 page of the Springboard Series on TechNet.
Hope this helps
Comment: I have run gpresult /v on the pc, what should i look for to figure out how the user is getting admin rights?
Comment: Could you expand on that? I can't envisage a situation where logon scripts being bypassed would affect a user's security group membership or effective permissions on a filesystem.
Comment: It appears that I may have misunderstood the question. I had interpreted this question as being an issue where a user is mapped to \\server\share\username, but the mapping actually ends up being \\server\share (one level up). My answer was not referencing the permission issue directly.
Comment: However, with that said, I agree with Lasith. But, the [RSOP page](http://technet.microsoft.com/en-us/library/cc772175.aspx) on TechNet shows that RSOP doesn't include all settings for any OS after Vista SP1, and that you should use Group Policy Results or Group Policy Modeling options in the [Group Policy Management Console](http://technet.microsoft.com/en-us/library/cc771009.aspx), or use the [GPResult](http://technet.microsoft.com/en-us/library/cc733160(v=ws.10).aspx) command line tool.


How to NOT turn element read only when waiting for '#ajax' callback in Drupal 7 forms?

Question: I need a simple '#type' => 'textfield' field. When a user types in it, I want to update another section of my form. Just a more elaborate version of built-in autocomplete field, really. So I added:
'#ajax' => array(
  'callback' => 'mymodule_tag',
  'wrapper' => 'edit-tags',
  'method' => 'replace',
  'effect' => 'fade',
  'event' => 'input',
),

The only problem is - it turns my field disabled when waiting for the server's reaction. This is unacceptable: User's input should never be blocked, that's a priority. I bet the solution is simple, but googling for it gives me a lot of results about how to disable field, and none about keeping it enabled. Too much noise for my search skills. Any suggestions?
Answer: I'm not sure I agree with your premise (interesting question, nonetheless). If performing a second operation while the first is already running would cause a problem client/server side, then that operation should definitely be blocked in my opinion.
If the only issue you have is that the blocking is done by way of disabling the text field, consider that it's just a matter of good UX. If the field wasn't disabled, but the functionality was, then there's no feedback to the user, who is left wondering why nothing's happening even though they're typing into a text field that has some rich functionality a few seconds earlier.
That said, if you want to override the behaviour of Drupal's AJAX have a look in the /misc/ajax.js file. You'll need to re-implement at least:

Drupal.ajax.prototype.beforeSend
Drupal.ajax.prototype.success
Drupal.ajax.prototype.error

Those functions set/remove the disabled attribute on the element. It should be reasonably straight forward to re-assign those functions in a custom JS file, and you can just remove lines like this:
$(this.element).addClass('progress-disabled').attr('disabled', true);

Or tweak it to something more palatable for your use case.
Comment: @Mołot I would class that as bad UX - The "should be enough" icon doesn't cut it for me, you're making the assumption that your users will have exactly the same thought process as you (believe me, that's almost never the case!) and that they'll automatically know that the rotating icon means they can't use the textfield for the same purpose until the icon is gone. I'd imagine that's one of the reasons the functionality you're looking for was never implemented - it's not seen as the right way to do things. Either way, though, at least you've got a way forward if it matters enough :)
Comment: Operations are read-only and cacheable. It's just a fancy selective autocomplete, that's all. So there is no problem with race conditions and alike. And I don't want to override behaviour for every field on my site. I just need it on one field.
I hoped there is something like '#nonblocking' parameter for '#ajax' table I'm simply unable to find. Looking at those files, I guess that's not the case.
Comment: For blocking - there is a rotating ball or other icon indicating ajax at work. That should be enough for most users to see that they're supposed to wait for their results.
Comment: But they CAN use the textfield. Just like they CAN write in regular autocomplete form element for tags, even if ajax is waiting for autocomplete suggestions to return from a server. My case is just a bit more elaborate autocomplete, but with the same UX basis. So, it actually WAS implemented, just in a way that makes it hard to tailor to a bit more advanced needs.
Comment: I don't think we're going to agree, I'm looking at it from a different perspective. I sympathise though, I've been at odds with the 'accepted' way of doing things before and had to work hard to get around what I consider bad-practice, even though the majority (or, the core developers at least) disagree.
Comment: Well, I can't see a reason why autocomplete works the way it does and it's OK, but when I need to build something that works the same way, just puts it's results in a div I choose instead, and with more elaborate suggestions, it's suddenly a bad practice.
Comment: You're just going to have accept that you're coding against a framework, and that you might not always agree with the methods/implementations/decisions of that framework (I know I don't!). Something that may not work for your use case may work perfectly well for 99.99% of other cases. Or it might not, and you might be describing what many would see as a bug. Who's to say. The developers have been careful to make sure all behaviour like this can be overridden if it's not to your liking, though, so I think the problem, if any, is a tiny one


Why Student's t-distribution has fatter tails than normal distribution?

Question: Student's t-distribution that arise:

when estimating the mean of a normally-distributed population
when the sample size is small
and the population's standard deviation is unknown

I need to clarify the Hypothesis H and Question Q:
H: In general you can control the tails of normal distribution with standard deviation, the bigger it is the fatter the tails so I can make the tails as fat as I like.
Q: Is this comparison based on the normal distribution used to produce the t-distribution?
It looks to me the answer is yes, for the previous question but maybe I am missing something important.

In general, and I understood this for the first time thanks to @whuber "a fat-tailed distribution" is a probability distribution that exhibits a large skewness or kurtosis, relative to that of either a normal distribution or an exponential distribution according to Wikipedia
So my hypothesis H looks like is wrong at the very start, because you cannot alter the Normal distribution "fat tail" state with the standard deviation parameter.
It is pretty unclear why both the normal distribution or an exponential distribution are considered in here because their third and forth moment formula differs. In case of Exponentiation distribution 3rd and 4th moments are: 2 and 6, and in case of Normal distribution those moments are zero. So I wonder why Wikipedia has this definition of being "fat".

In my original idea of being on tail I would consider the area [-inf, $\mu -3\sigma]$ and $[\mu +3\sigma, \inf)$ and if some distribution has "fatter tail" would be to have large area under the curve in that tail area.
Comment: I cannot understand this question because I don't know what this "standard deviation" is that you might be varying to "control the tails."  A Normal distribution is a Normal distribution, period.  Changing its parameters does not change the "fatness" of its tails in any meaningful or conventional sense.  What "comparison" are you carrying out, then?
Comment: OK, I see what you meant. Thanks.
Comment: I altered the question, hope this helps a little bit.
Comment: Many threads here on CV discuss "fat," "heavy," or "long" tailed distributions.  See [this search](https://stats.stackexchange.com/search?tab=votes&q=heav*%20tail%20distribution%20defin*) for links to some of the most relevant to the concept you express at the end.  The second paragraph of my post at https://stats.stackexchange.com/a/86503/919 gives one simple intuitive definition.  Please note that moments, like skewness or kurtosis, are not good for characterizing tail behavior.
Comment: @whuber, not bad paragraph, but the term "eventually F has more probability at large values than G" is unclear as we don't know what are these large values. It may be true for some large value but for some **larger** value may not be true. The problem on my side is that your answer posed abut 5 more questions (which is good) and I will not hesitate promote you because of that. -- In here it would be helpful to confirm to define the tails first. I presented what is  tail (inside the question). To create another question based on your answer would be my approach. :) Thanks.
Comment: I agree the English may be unclear--but the definition I gave is mathematical, rigorous, and absolutely clear.
Comment: https://stats.stackexchange.com/questions/511206/question-based-on-the-whuber-detailed-answer-on-fat-tailed-term
Answer: Your "title" question seems more clear to me than your detailed question. So I ll try to answer the former.
Why is t-distribution fatter? because there is more uncertainty. Since we do not know the standard errors, there is more uncertainty of the t-statistic. However, the larger the sample is, the more accurate the Standard deviation estimate will be, thus t-distribution will converge with the normal distribution.
Now, you are partially correct. In a normal distribution, the larger the variance, the farther the tails will spread. However, a normal distribution has a very nice "ratio" of dispersion around the tails, and concentration around the means. In other words, once you standardized a variable, (so that it has a mean zero and standard deviation 1), if that variable follows a normal distribution, it will always look the same.
The t distribution "ratio" is larger than the one for normal distribution. So even if you standardize the variable, the distribution will depend on the degrees of freedom of the distribution. lower degrees of freedom, more uncertainty, fatter tails. Higher degrees of freedom, less uncertainty, t-distribution will look more and more like a normal distribution.
HTH
F
Comment: But fatness of tails refers to extremity of potentially observable data.  Larger variance does not imply fatter tails: You will get points that are farther from the mean, yes, but they are not necessarily extreme.
Comment: True, I should say, the larger the variance, the longer the tails. That is why I tried to keep the idea of "ratio" between dispersion and concentration.  I corrected this in my answer


Como totalizar os dias de acordo com um período?

Question: Como totalizar os dias de acordo com um período?
Exemplo:
+--------------+--------------+--------+----------+
| data_ini     | data_fim     | codfun | qtd_dias |
+--------------+--------------+--------+----------+
| '2014-01-15' | '2014-01-31' | 1      | 16       |
| '2014-02-01' | '2014-02-28' | 1      | 27       |
| '2014-03-01' | '2014-03-22' | 1      | 21       |
| '2014-03-10' | '2014-03-31' | 2      | 21       |
| '2014-04-01' | '2014-04-30' | 2      | 29       |
| '2014-05-01' | '2014-05-12' | 2      | 11       |
| '2014-04-08' | '2014-04-30' | 3      | 22       |
| '2014-05-01' | '2014-05-31' | 3      | 30       |
| '2014-05-01' | '2014-06-19' | 3      | 49       |
+--------------+--------------+--------+----------+

Preciso totalizar a coluna qtd_dias por codfun e trazer o período inicial e final (data mais antiga em data_ini e data mais recente em data_fim), por exemplo:
+--------+--------------+--------------+----------------+
| codfun | data_ini     | data_fim     | qtd_dias_total |
+--------+--------------+--------------+----------------+
| 1      | '2014-01-15' | '2014-03-22' | 66             |
| 2      | '2014-03-10' | '2014-05-12' | 63             |
| 3      | '2014-04-08' | '2014-06-19' | 72             |
+--------+--------------+--------------+----------------+

Comment: Amigo @mcardoso, dava pra dar mais alguma informação sobre a lógica de agrupamento, ou algum preâmbulo(sito)? Eu não percebi muito bem.
Comment: A primeira tabela está idêntica como está no banco de dados e a segunda (que é o resultado), seria a ramificação da primeira, ou seja, deve-se colocar a data de início e fim mês a mês, de acordo com o período da primeira tabela, resultado na nesta segunda.
Comment: Suas somas nos dados representativos estão errados, seria intencional? A solução do @luigibertaco funciona corretamente no MySQL.
Comment: A Reestruturação da pergunta feita pelos adm do stackoverflow está errada! é o contrário mesmo! preciso do detalhamento e não do agrupamento.
Answer: Acredito que no seu caso seria algo do tipo:
select codfun, min(data_ini), max(data_fim), sum(qtd_dias) from TABELA group by codfun;

não tenho certeza de como isto vai se comportar no mysql, mas acredito que não tenha diferença com outros bancos.


Quiz Module persistance implementation details

Question: In which part of the code is a new quiz stored in the database? What are the functions responsible for storing a new quiz in the database upon the submission of the form for creating a new quiz?
I'm trying to accomplish two things:

Timer per question
Dynamic question selection strategy

Quiz Module Version: 7.x-5.3
Answer: You need to be familiar with Drupal concepts like Nodes and Entities because they are used to model a Quiz.
The logic to keep the pieces synchronized is implemented via Hooks, like _hook_insert_ and _hook_update_, located on the quiz.module file.
Quiz 2.0 Architecture Information

A Quiz is a Drupal node, and thus the node table contains a row for
  each Quiz. Similarly, a Question is also a Drupal node, so it too has
  an entry in the node table. Additional properties for Quizzes can be
  found in the rows of the quiz_node_properties table. Similarly, all
  question-types have a table called quiz_node_question_properties to
  store additional data. Each question-type also makes it's own set of
  tables to hold answers and user feedback. That means the
  multichoice.module question-type gets a quiz_multichoice_answers and a
  quiz_multichoice_user_answers.

From Community Documentation: Chapter 3 ~ Under The Hood

hook_insert
<code>/**
 * Implements hook_insert().
 */
function quiz_insert($node) {
  // Need to set max_score if this is a cloned node.
  $max_score = 0;

  // Copy all the questions belonging to the quiz if this is a new translation.
  if ($node->is_new && isset($node->translation_source)) {
    quiz_copy_questions($node);
  }

  // Add references to all the questions belonging to the quiz if this is a
  // cloned quiz (node_clone compatibility).
  if ($node->is_new && isset($node->clone_from_original_nid)) {
    $old_quiz = node_load($node->clone_from_original_nid);

    $max_score = $old_quiz->max_score;

    $questions = quiz_get_questions($old_quiz->nid, $old_quiz->vid);

    quiz_set_questions($node, $questions);
  }

  _quiz_common_presave_actions($node);

  // If the quiz is saved as not randomized we have to make sure that questions
  // belonging to the quiz are saved as not random.
  _quiz_check_num_random($node);
  _quiz_check_num_always($node);

  quiz_update_defaults($node);
  _quiz_insert_resultoptions($node);
}
</code>
hook_update
<code>/**
 * Implements hook_update().
 */
function quiz_update($node) {
  // Quiz node vid (revision) was updated.
  if (isset($node->revision) && $node->revision) {
    // Create new quiz-question relation entries in the quiz_node_relationship
    // table.
    quiz_update_quiz_question_relationship($node->old_vid, $node->vid, $node->nid);
    drupal_set_message(t('Some of the updated settings may not apply to quiz being taken already. To see all changes in action you need to start again.'), 'warning');
  }

  // Update an existing row in the quiz_node_properties table.
  _quiz_common_presave_actions($node);

  quiz_update_defaults($node);
  _quiz_update_resultoptions($node);

  _quiz_check_num_random($node);
  _quiz_check_num_always($node);
  quiz_update_max_score_properties(array($node->vid));
}
</code>


Solution of a specific PDE

Question: I'm looking for a solution of the following PDE problem:
$$\begin{cases}
-\frac{\partial^2u}{\partial x^2}-2\frac{\partial^2u}{\partial y^2}=f&\text{on}~U,\\
u=0&\text{on}~\partial U
\end{cases}$$
for $U=\left\{(x,y)\in\mathbb{R}^2|\,x,y\geq0\right\}$ .
The solution should be represented as an integral of $f$ integrated against a kernel.
I tried so far to extend the Poisson kernel but it is somehow not working. I'm very glad for your help. Thank you so much.
Anastasia
Comment: This might help: http://math.stackexchange.com/questions/426972/a-differential-operator
Comment: We're not doing your homework! What have you done so far?
Answer: Hint: Make a transformation $(x, y) \mapsto (x, z)$ such that $2\frac{\partial^2}{\partial y^2} = \frac{\partial^2}{\partial z^2}$.
Answer: $-\dfrac{\partial^2u}{\partial x^2}-2\dfrac{\partial^2u}{\partial y^2}=f(x,y)$
$\dfrac{\partial^2u}{\partial x^2}+2\dfrac{\partial^2u}{\partial y^2}=-f(x,y)$
Let $\begin{cases}p=y+\sqrt{2}ix\\q=y-\sqrt{2}ix\end{cases}$ ,
Then $\dfrac{\partial u}{\partial x}=\dfrac{\partial u}{\partial p}\dfrac{\partial p}{\partial x}+\dfrac{\partial u}{\partial q}\dfrac{\partial q}{\partial x}=\sqrt{2}i\dfrac{\partial u}{\partial p}-\sqrt{2}i\dfrac{\partial u}{\partial q}$
$\dfrac{\partial^2u}{\partial x^2}=\dfrac{\partial}{\partial x}\left(\sqrt{2}i\dfrac{\partial u}{\partial p}-\sqrt{2}i\dfrac{\partial u}{\partial q}\right)=\dfrac{\partial}{\partial p}\left(\sqrt{2}i\dfrac{\partial u}{\partial p}-\sqrt{2}i\dfrac{\partial u}{\partial q}\right)\dfrac{\partial p}{\partial x}+\dfrac{\partial}{\partial q}\left(\sqrt{2}i\dfrac{\partial u}{\partial p}-\sqrt{2}i\dfrac{\partial u}{\partial q}\right)\dfrac{\partial q}{\partial x}=-2\dfrac{\partial^2u}{\partial p^2}+2\dfrac{\partial^2u}{\partial pq}+2\dfrac{\partial^2u}{\partial pq}-2\dfrac{\partial^2u}{\partial q^2}=-2\dfrac{\partial^2u}{\partial p^2}+4\dfrac{\partial^2u}{\partial pq}-2\dfrac{\partial^2u}{\partial q^2}$
$\dfrac{\partial u}{\partial y}=\dfrac{\partial u}{\partial p}\dfrac{\partial p}{\partial y}+\dfrac{\partial u}{\partial q}\dfrac{\partial q}{\partial y}=\dfrac{\partial u}{\partial p}+\dfrac{\partial u}{\partial q}$
$\dfrac{\partial^2u}{\partial y^2}=\dfrac{\partial}{\partial y}\left(\dfrac{\partial u}{\partial p}+\dfrac{\partial u}{\partial q}\right)=\dfrac{\partial}{\partial p}\left(\dfrac{\partial u}{\partial p}+\dfrac{\partial u}{\partial q}\right)\dfrac{\partial p}{\partial y}+\dfrac{\partial}{\partial q}\left(\dfrac{\partial u}{\partial p}+\dfrac{\partial u}{\partial q}\right)\dfrac{\partial q}{\partial y}=\dfrac{\partial^2u}{\partial p^2}+\dfrac{\partial^2u}{\partial pq}+\dfrac{\partial^2u}{\partial pq}+\dfrac{\partial^2u}{\partial q^2}=\dfrac{\partial^2u}{\partial p^2}+2\dfrac{\partial^2u}{\partial pq}+\dfrac{\partial^2u}{\partial q^2}$
$\therefore-2\dfrac{\partial^2u}{\partial p^2}+4\dfrac{\partial^2u}{\partial pq}-2\dfrac{\partial^2u}{\partial q^2}+2\biggl(\dfrac{\partial^2u}{\partial p^2}+2\dfrac{\partial^2u}{\partial pq}+\dfrac{\partial^2u}{\partial q^2}\biggr)=-f\biggl(\dfrac{i(q-p)}{2\sqrt{2}},\dfrac{p+q}{2}\biggr)$
$8\dfrac{\partial^2u}{\partial pq}=-f\biggl(\dfrac{i(q-p)}{2\sqrt{2}},\dfrac{p+q}{2}\biggr)$
$\dfrac{\partial^2u}{\partial pq}=-\dfrac{1}{8}f\biggl(\dfrac{i(q-p)}{2\sqrt{2}},\dfrac{p+q}{2}\biggr)$
$u(p,q)=F(p)+G(q)-\dfrac{1}{8}\int_b^q\int_a^pf\biggl(\dfrac{i(t-s)}{2\sqrt{2}},\dfrac{s+t}{2}\biggr)ds~dt$
$u(x,y)=F(y+\sqrt{2}ix)+G(y-\sqrt{2}ix)-\dfrac{1}{8}\int_b^{y-\sqrt{2}ix}\int_a^{y+\sqrt{2}ix}f\biggl(\dfrac{i(t-s)}{2\sqrt{2}},\dfrac{s+t}{2}\biggr)ds~dt$

Solution of a specific PDE


Condition for the generators through any one of the ends of an equi-conjugate diameter of the principal elliptic section of the hyperboloid

Question:
Question: Show that the generators through any one of  the ends of an equi-conjugate diameter of the principal elliptic section of the hyperboloid $\frac{x^2}{a^2}+\frac{y^2}{b^2}-\frac{z^2}{c^2} = 1$ are inclined to each other at an angle of $60 ^\circ$ if $a^2+b^2=6c^2$.

Solution: I took the point on the diameter as $(a\cos\theta,b\sin\theta,0)$ . So the two generators through this point are
$$\begin{align}
\frac{x-a\cos\theta}{a\sin\theta}=\frac{y-b\sin\theta}{-b\cos\theta}=\frac{z}{\pm c}
\end{align}$$
So the direction ratios of two generators are $(a\sin\theta,-b\cos\theta,c)$ and $(a\sin\theta, -b\cos\theta,-c)$ respectively.
$$\begin{align}
\cos\theta &=\frac{l_1l_2+m_1m_2+n_1n_2}{\sqrt{{l_1}^2+{m_1}^2+{n_1}^2}\sqrt{{l_2}^2+{m_2}^2+{n_3}^2}} \\
\implies \cos\theta &=\frac{a^2\sin^2\theta+b^2\cos^2\theta-c^2}{a^2\sin^2\theta+b^2\cos^2\theta+c^2}
\end{align}$$
Putting $\theta = 60^\circ$ and solving I got $3a^2+b^2 = 12c^2$
I am wondering whether the question is wrong or I missed anything or my approach itself is wrong. Appreciate any hint.
Answer: $\alpha = 60^\circ$ is the angle between two generators not the parameter of end points of conjugal diameters.
$$\begin{align}
\cos\alpha &=\frac{l_1l_2+m_1m_2+n_1n_2}{\sqrt{{l_1}^2+{m_1}^2+{n_1}^2}\sqrt{{l_2}^2+{m_2}^2+{n_3}^2}} \\
\implies \cos\alpha &=\frac{a^2\sin^2\theta+b^2\cos^2\theta-c^2}{a^2\sin^2\theta+b^2\cos^2\theta+c^2}
\end{align}$$
Putting $\alpha = 60^\circ$ and $\theta = 45^\circ (\because $ equi-conjugal diameters means equal length of conjugal diameters i.e. $\sqrt {a^2cos^2\theta+b^2sin^2\theta} = \sqrt {a^2sin^2\theta+b^2cos^2\theta}$ which is possible for $\theta = 45^\circ$)
Putting values of $\theta$ and $\alpha$ you get the answer $a^2+b^2 = 6c^2$


ASP.NET MVC: Default model binder not working on Safari (but does work for Firefox)

Question: Very strange issue... I have something like this in my Controller:
public ActionResult Initialize(IEnumerable<MyModel> Requests)
{
...

}

I generate form elements in my submitting View that look like this:
Requests[90ed54f6-4650-44c7-8cc2-c4d225a9a334].Name
Requests[90ed54f6-4650-44c7-8cc2-c4d225a9a334].Address
Requests[db67e8e5-94f8-4b35-b69c-65184980f2a1].Name
Requests[db67e8e5-94f8-4b35-b69c-65184980f2a1].Address

On Firefox, when I submit this with multiple elements, the binder works and I get a collection of objects. On Safari, the exact same data always generates only 1 object in the collection.
Weirdly, in the debugger if I look at Requests.Params.AllKeys[] I see the values -- they're being submitted, just somehow not binding. I use Firebug on Firefox but don't have an equivalent tool for Safari. Since I see the values in the Request.Params, I assume that it's not an issue with the form values being passed in -- just something about they way they're being bound to the ViewModel...
The binder is kind of black magic to me -- I'm not sure where this lives and if I can step through this to see what it's doing.
Any ideas what this might be or how I might chase this down?
Edit: This works correctly in IE as well -- just Safari is acting weird.
Edit 2: I lied... Safari does not post the index values as I would expect:
Requests.index = {GUID}
Requests[90ed54f6-4650-44c7-8cc2-c4d225a9a334].Name
Requests[90ed54f6-4650-44c7-8cc2-c4d225a9a334].Address
Requests.index = {GUID}
Requests[db67e8e5-94f8-4b35-b69c-65184980f2a1].Name
Requests[db67e8e5-94f8-4b35-b69c-65184980f2a1].Address

Both Firefox and Internet Explorer post both Requests.index values as comma separated values, but Safari only posts the first. I'm not sure what "correct" is for this case, but this is something I can sink my teeth into.
Comment: Here is a good guide to stepping through the mvc source code:  http://weblogs.asp.net/gunnarpeipman/archive/2010/07/04/stepping-into-asp-net-mvc-source-code-with-visual-studio-debugger.aspx
Comment: @ericvg -- Thanks -- that helped me see what was happening.
Answer: I assume that the "index" is a GUID that functions as the request's id.  I would assume that you would actually generate something like:
 <input type="hidden" name="Requests[0].ID" value="90ed54f6-4650-44c7-8cc2-c4d225a9a334" />
 <input type="text" name="Requests[0].Name" />
 <input type="text" name="Requests[0].Address" />

Of course, your MyModel class will need to have the ID property to hold the Guid.
My suspicion is that it has something to do with how the query parameters are encoded, but honestly I have never set up collections the way you are and it's not clear to me how the model binder should interpret the parameter index -- perhaps it's mapping them all onto 0 -- if it's not numeric.
Comment: They're guid based indexes on the form objects ... the values are literally (Requests[90ed54f6-4650-44c7-8cc2-c4d225a9a334].Name).  Encoding sounds like it might be right -- could explain why Safari behaves differently. Thanks
Comment: @Andrew - Try setting up your indexes like: Request[ *GUID* ].index = *GUID*. I still think it would be better to use numeric indices absent any other compelling reason not to. After all, you're simply getting back an enumerated list. Unless you store the GUID as part of the object (as I've shown), it doesn't make the results any more unique than simply using an monotonically increasing integer value.
Comment: On the input side, I'm allowing arbitrary adding/removing of rows of data which makes it difficult to do with concurrent indexes. So for example, a user can input 0,1,2,3 and then delete row 2 before submitting the form. The GUIDs help with that. I'll try what you suggest though.
Comment: @Andrew - it should still be ok.  You might, however, get gaps that correspond to the missing indices.  Doing something like: `var actualRequests = requests.Where( r => r != null )` would solve that.
Answer: Compare actual values POST'd by each browser:
public ActionResult Initialize(FormCollection collection)
{
  //... dump the collection's NameValueCollection ...
}

And compare actual HTML rendering of the form between browsers, just to be sure.
Answer: So the final solution to this had to do with improperly placed <input> tags. Specifically, I was placing a hidden <input> after a
 and before a . On Firefox and IE it's very forgiving and this was working. On Safari for some reason, it would not consider the 2nd-Nth elements to be valid form inputs. Putting the <input> elements inside of the  worked for all browsers.
Thanks for your help guys.


Android Studio Quickboot/Snapshot not supported error?

Question: I am Facing this error recently. Everything was fine i was learning android studio and suddenly out of nowhere this hit me up.
****Emulator: Warning: Quick Boot / Snapshots not supported on this machine. A CPU with EPT + UG features is currently needed. We will address this in a future release.****
This error made me to delete my virtual device and create a new one. Then it became too slow to start and run the applications. I am running an i5 - 4570 with 8 gigs of ram and a NVIDIA GT 610. I have installed HAXM and virtualization is enabled.Please help me through this.
Kudos.
Answer: This error means that your CPU do not have right configuration the INTEL VTX technology in your PC.
Android recommend this steps:
https://developer.android.com/studio/run/device
Is more reliable in some cases use a physical device via USB instead of emulator.
Comment: But it was working fine before. Mine is an i5-4570 and it supports VT-x.


C++ smart linear container

Question: Let me explain my problem together with the background, so it would be easier to understand why I'm asking for this specific type of thing. I'm developing an instant messenger. Most of the architecture is outlined by my teacher, however implementation detail may vary. There is an "Engine" class, EventManager, which registers clients. To identify them and to easily remove them, I use a map (with client-id's) or a set with pointers. So far, so good. But then this EventManager uses poll() (or select(), but that's nowhere as comfortable to use as poll(), as you have to rebuild the array each time, which is slow and not-so-nice, I guess, and I can restrict myself to UNIX environment, if you ask) in its main loop. Which needs an array of struct pollfd. Now every time a new client comes or goes, this array needs to be rebuilt. Either I use a dynamic array by hand and allocate memory every time (baaaaaad), or I use a vector, which would handle new client's struct pollfd insertion pretty well at the end of the container, or a deque, which would insert and remove anywhere pretty well. Now my two questions are:

If I choose vector, will it automatically shrink and move elements in the middle of itself instead of full reallocation? and
That would anyway copy a lot, if it's in the beginning, so I'd like to use deque. Does that have an array interface (like you would do with vector - &myVector[0]) or is it strictly non-contiguous?
Comment: no, there is nothing wrong with homework questions here. The tag is just used to indicate that rather than providing complete working code, we should emphasize the actual *explanations*, so that the person asking the question will actually *learn* something, rather than just solving the immediate problem. The tag is also commonly used for questions about textbook exercises and such, which aren't strictly homework, but where the same applies (that you're looking for understanding, rather than just the code)
Comment: Ah, yes, threads are forbidden ;)
Comment: This is NOT homework! Please be respectful, we all started somewhere! This is a course project of middle size, not a lab for two classes!
Comment: Oh well, thank you, the guy who edited my post. Now people have seen the word "homework" and are running away from this question...... and mod me to death if I'm not right.
Comment: Oh well, my apologies then. I've seen a couple examples here when people said "Don't make us do your homework for you" and such, so I'm pretty much afraid of this "homework" tag or "homeworkish" attitude towards a question.
Answer:
If you remove something from the middle of a vector it will move all the following elements one position towards the beginning. It will not reallocate. You don't have to consider reallocations at all because they are amortized to give O(1) time per insertion.
deque is not much better than vector. Removing from the beginning or end is efficient. Not from the middle. If you remove from anywhere, then it will hopefully be twice as fast a vector, but not faster. Since it's a more complicated structure it'll probably be even slower. deque doesn't guarantee continuous storage, so although indexing is allowed and done in O(1) time, you still can't reliably convert it to a pointer.

Anyway it smells like premature optimization. Use vector. Since the order of clients is not significant, you can speed up the erasure of clients by swapping the element that you want to remove with the last element in the vector and calling pop_back() after that.
Comment: Thanks! But std::set is not an array in any way, unfortunately. so I'll resort to vector, then. The main problem here is an array (pointer) interface...
Comment: @Semen Semenych: Sorry, I missed the point at the beginning, fixed already. Then your only choice is vector.
Comment: The last part about pop_back() seems ingenious to me. That's what I'll do, really.

C++ smart linear container


Automatically copying new files to another folder (CentOS 6.3)?

Question: Is there a command I can enter via SSH (CentOS 6.3) that will monitor a certain directory, and if any new files/folders are created in in, copy those files to another folder at all?
I have looked at various sync programes, and rather than mirror the folder I need to keep a copy of any new files/folders even if they are deleted from the original directory.
I am hoping the cp command can be used somehow, but I couldn't work out how to do it myself.
Thanks for any help, and please let me know if you need further information to help or there is a better way to achieve my needs.
Answer: Rsync would do it, it doesn't have to delete files from the destination if they are deleted from the source.
Do you need it to run periodically or monitor constantly for changes? If the latter you might want to look into something using inotify or FAM.
Comment: Hi Jonathan,thanks for the quick reply and sorry for the delay in getting back to you.  I would want it to monitor changes constantly if possible and will see what I can find in regards to inotify of FAM.  If you have any further information you could help with in regards to these (such as setting them up etc. - I'm new to Linux) it would be appreciated.  Thank you.
Comment: Just to add, I now I inotify-tools installed (inotify-tools.x86_64 0:3.14-1.el6) - I'm learning!


Mixing log4j 1.x and log4j 2 with third party libraries dependending on log4j 1.x

Question: I'm maintaining a Maven project that uses log4j 1.x with a large codebase. Not only is log4j 1.x used in existing code, it is also used by some third party libraries on which the project depends.
I want to start using log4j 2 now, but I wonder if it is worth the hassle.
I know it is possible to mix the two (cf. Mixing log4j 1.x and log4j 2) but what about the third party libraries that depend on log4j 1.x, I'm afraid there will be conflicts.
So should I rather stick to log4j 1.x or risk a dependency hell by upgrading to log4j 2?
Comment: Only you can weigh the pro's of log4j 2 vs the con's of *"dependency hell"*. We may all have opinions about that, but we don't know you project and requirements. Voting to close as "primarily opinion-based".
Comment: It is a matter of fact, that if you read the answer to the question you linked, and the documentation of the Log4j 1 to Log4j 2 bridge, you'd already know that the bridge will redirect all Log4j 1 calls to the Log4j 2 implementation, because that is what a bridge does. As long as you *exclude* any actual Log4j 1 implementation, there will be no conflict. Whether the *"dependency hell"* of excluding Log4j 1 is worth the features of Log4j 2, is for you to decide, as already stated, and is entirely opinion-based.
Comment: @Andreas Objectively speaking: is it possible for my project to depend on log4j 2 and third party libraries on log4j 1.x without giving a conflict? This is not a matter of opinion but of fact, no?
Answer: I've done so myself. I don't think there will be any issue.
Even the project I did for had third party libraries.
You can use log4j-1.2-api-2.x.jar simply.
Remove your older log4j-1.2.x.jar and replace with below three jars:

log4j-1.2-api-2.x - will handle third party libraries depending on older log4j version.
log4j-api-2.x.jar
log4j-core-2.x.jar

Moreover, for your own code, you can follow migration steps to start using log4j2 api and third party libraries will continue using bridge between older and newer version that is log4j-1.2-api-2.x.jar (aka log4j 1.x bridge)
Below is the official documentation:
Migrate from log4j-1.x to log4j-2
Answer: It seems that perhaps the naming has changed since @Nitin answered the question. According to the log4j site, the Maven dependency is:
<code><dependencies>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-1.2-api</artifactId>
    <version>2.2</version>
  </dependency>
</dependencies>
</code>


O que é FastExpando/FastExpandoObject?

Question: Estava lendo a respeito do Dapper e me deparei com uma característica dele chamada FastExpando ou FastExpandoObject, eu não compreendi muito bem e fiquei com algumas duvidas em relação a esta característica.
Dúvidas

O que é FastExpando/FastExpandoObject?
Qual é a relação que o FastExpando/FastExpandoObject tem com o Dapper?
Answer: Primeiro, na framework .NET existe a classe ExpandoObject, que permite a expansão de um objeto em tempo de execução.

http://msdn.microsoft.com/pt-br/library/system.dynamic.expandoobject(v=vs.110).aspx

ExpandoObject tem vários usos, um deles é no acesso a Banco de Dados, armazenando os resultados de uma consulta. A habilidade de alterar o objeto mostra-se muito útil nessa tarefa.
Dapper, em sua própria definição, é um framework simples para manipular objetos em .NET, que tem como objetivo oferecer uma melhor performance.

http://github.com/StackExchange/dapper-dot-net

Agora, sobre FastExpandoObject, eu não o encontrei na definição original  do Dapper (link acima).
Encontrei-o em um repositório do GitHub:

http://github.com/MiniProfiler/dotnet/tree/master/StackExchange.Profiling/Helpers

onde é declarado como:
private class FastExpando : System.Dynamic.DynamicObject, IDictionary<string, object>

No SqlMapper.cs desse repositório, existe uma referência a uma página antiga:

http://code.google.com/archive/p/dapper-dot-net/

E essa página possui um pacote antigo do Dapper, mas o mesmo também não possui nenhuma definição do FastExpando:

http://code.google.com/archive/p/dapper-dot-net/source/default/source

Concluindo, como a pergunta original que te deixou com dúvida é de 2012, eu imagino que FastExpandoObject não seja mais utilizado. E, julgando pelo nome, tinha como propósito ser mais rápido que o ExpandoObject.
Pesquisando sobre ExpandoObject, eu encontrei uma outra classe chamada BetterExpando, que em sua definição é "melhor que expando".

http://gist.github.com/lukevenediger/6327599

E provavelmente devem existir outras classes...
Answer: ExpandoObject são objetos dinâmicos, ou seja, objetos que voce pode adicionar ou remover propriedades em tempo de execução.
dynamic meuCache;
meuCache.QualquerCoisa = "Qualquer coisa mesmo";
meuCache.OutraCoisa = new { FaladoSerio = true };
meuCache.MaisUmaCoisa = Enum.Empty<string>();

Hoje, o objeto dinamico mais popular do .NET Framework é o ViewBag, do ASP.NET MVC.
No caso do Dapper, ele utiliza objetos dinamicos para deserializar informações que virão de uma fonte onde seu formato é desconhecido.
Podemos ver sua aplicação no Dapper em sua classe GridReader, método .Read(bool)

class GridReader: The grid reader provides interfaces for reading multiple result sets from a Dapper query
IEnumerable < dynamic> GridReader.Read(bool): Read the next grid of results, returned as a dynamic object

Retornar listas é sempre melhor do que retornar tabelas.

O que é FastExpando/FastExpandoObject?


JQuery Slide Toggle Close and Open Issue

Question: First of all , please bear with me about my bad english :(
I am listing data in a table using for-each loop and above HTML will generate if use to slideToggle then it open fine.
but if another row open then last one still open , i want to open a new one but close previous.
function view_history_details  (  ) {

    $('#view-details').slideToggle();
}

    some text

    some text

    some text

Answer: You can redesign the solution as below using jQuery event handlers.
We adds a class to the anchor elements which triggers the action, then use that class to register the click handlers. Inside the handler we toggles the next view-details row and hides all other view-details elements

jQuery(function($) {
  $('.toggle').click(function(e) {
    console.log(this)
    e.preventDefault();
    var $cur = $(this).closest('tr').next('.view-details').stop().toggle();
    $('.view-details').not($cur).stop().hide();
  })
})
.toggle {}

      togggle

    some text

      togggle

    some text

      togggle

    some text

Answer: You need to pass particular control to your function so as to slideToggle only that control's view-details element as below:
function view_history_details  (ctrl) {
    $('.view-details').slideUp();
    $(ctrl).closest('tr').next('.view-details').slideToggle();
}

and when calling function from td write it as below and pass this

Repeat for all tds where view_history_details function call exists.
DEMO

function view_history_details  (ctrl) {
    $('.view-details').slideUp('fast');
    $(ctrl).closest('tr').next('.view-details').slideToggle('slow');
}

      View Details

    some text

      View Details

    some text

      View Details

    some text


Enviar dados para outra tab através do "ion-option-button"?

Question: Como posso enviar os dados de uma tab para outra tab ao clicar no componente "ion-option-button"?
Essa tab destino terá um formulário, a intenção é editar os dados contidos em um "".
Dados para exibição consegui fazer através do:
<code>`<ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap" href="#/tab/chats/{{chat.id}}">`
</code>
Comment: você pode fazer isso por get, passando os dados no parâmetro da url, e recuperando o conteúdo, ou então via manipulado cookies, mas qual teria de se montar uma rotina pra gravar e recuperar este cookie
Answer: Já fiz isso antes passando parâmetros nas URLs, mas a experiência me mostrou que é melhor montar uma factory e gravar os dados lá. Fica mais organizado e centralizado. Mas também depende da natureza dos seus dados e tal.


A Regex to match text that starts with a space and ends with a know value

Question: I'm trying to match a string on a multiline text using Regex, the string looks something similar to this:
space-separated-values 1/2/tmp/known_text\n
I'm trying to match 1/2/tmp/ i.e everything that comes after the last whitespace up until the known_text value I have, everything in between is unknown to me.
I've tried a lot on https://regex101.com/ but couldn't get to figure it out, could anyone help me doing that please!
Comment: Is there no space after known text? Or could there be some more space?
Comment: there's a line and after the know text
Comment: Provide some proper example strings
Comment: k d kn tmp/myfolder1/1.png
s a mm tmp/myfolder1/1.png
Comment: Which programming language you are using?
Comment: I'm using Elixir
Answer: If I understand you correctly, you want to find a space, then no spaces until knownvalue:
\s[^\s]*knownvalue\n

I have a fiddle here: https://regex101.com/r/qRj0Qi/2.
Comment: it's exactly what I was aiming for, except I removed the `\s` at the begging
thanx a lot!


How to get the derivation for mean-field approximation?

Question: In page 487/1266 of [probabilistic graphic model: principal and technique] book, the authors give the following Lagrange equation:
$$L_i[Q]=\sum_{\phi \in \Phi} \mathbf{E}_{\mathbf{U}_\phi \sim Q}[\ln \phi] + \mathbf{H}_Q (X_i) + \lambda (\sum_{x_i} Q(x_i) - 1)$$
And in page 42/86 of [http://web.eng.tau.ac.il/deep_learn/wp-content/uploads/2017/01/Semantic-Segmentation.pdf], the authors derived the following Lagrange equation for solving a maximum problem for KL divergence using mean-field approximation:
$$\mathbf{D}(Q\|P) = \sum_{\mathbf{x}} Q(\mathbf{x}) \log \frac{Q(\mathbf{x})}{P(\mathbf{x})}=\mathbf{E}_{U\sim Q}[E(\mathbf{U})]+\sum \mathbf{E}_{U_i \sim Q_i }[\log Q_i(U_i)]+\log Z + \lambda (\sum_{x_i} Q(x_i) - 1)$$
Then take the derivation with respect to $Q(x_i)$.
How to get the derivation with respect to $Q(x_i)$. I'm not sure if my understanding is right. Suppose we have $N$ pixels and the label is from $L$ classes. The random variable is $X=(X_1,X_2,\cdots,X_N)$, where $X_i \in {\{0,1\}}^{L}$, i.e., for each pixel, the possible label is from $0,1,2,\cdots,L-1$. The energy is defined:
$$P(\mathbf X) = \frac{1}{Z(\mathbf X)} \exp \{{-E(\mathbf X)}\}$$
$$E(\mathbf X) = \sum_i \phi_u (x_i) + \sum_i \sum_{j\neq i} \phi_p (x_i,x_j)$$.
What does it mean for $Q(\mathbf X)$? How to get the derivation for $Q(x_i)$?
Answer: This derivation is a bit tricky. My experience is to use the approach in Bishop's Machine Learning and Pattern Recognition as a starting point. I've tried to derive it here: https://github.com/idnavid/misc/blob/master/variationalbayes_doc1.ipynb
Comment: Hi, @idnavid, thanks a lot for your kind comment and sharing!!


PatternFill entire row openpyxl

Question: I have an excel file that I have brought in as a df. I would like to highlight entire rows based off of names. So far, I am able to highlight only one column, but I would like the highlight applied to all columns. This is what I have so far, it runs through each name and applies a highlight color to it, after the name is no longer found, it moves on to the next name and applies the second highlight color, etc.
alist= df['NAME'].unique()
colorlist = ['efde6b','f4848d','bdbcff','75b56a','fcd7bd','f4b7c7','f79b74','a7d4f2']
count = 0
for a in alist:
    color = colorlist[count]
    color = str(color)
    for row in ws.iter_rows(1):
        for cell in row:
            if cell.value == a:
                cell.fill = PatternFill(start_color=color,
                                            end_color=color,
                                            fill_type='solid')
     count = count + 1

Comment: What's the question?
Answer: alist = test['NAME'].unique()
colorlist = ['efde6b','f4848d','bdbcff','75b56a','fcd7bd','f4b7c7','f79b74','a7d4f2']
count = 0
for a in alist:
    color = colorlist[count]
    color = str(color)
    for row in ws.iter_rows(1):
        for c in row:
            if c.value == a:
                row = c.row
                col = 1
                # print(row, col)
                while col < 9:
                    ws.cell(row=row, column=col).fill = PatternFill(start_color=color,
                                                    end_color=color,
                                                    fill_type='solid')
                    col = col + 1

Comment: This doesn't provide any kind of explanation and doesn't look much different.

PatternFill entire row openpyxl


My server room has flooded

Question: We recently went through a hurricane and our server room became flooded.  Hooray for insurance.  Anyway, I need to save as much data off one of the hard drives as possible.  Yes, it was submerged for the better part of two days.
Do I need to open the drive and make sure it's flood-water free?  Should I remove the board on bottom and dry out the foam?  What all do I need.
Any suggestions would be helpful.
Thanks in advance!
Comment: DIY would be cool if: A.) The data you want to recover has no value and the experience would be a learning one. B.) You get paid for your time regardless of recovery success., or C.) You *already* work for a data recovery shop. Either way +1 for your question. Hope I never have to deal with that.
Comment: At the very least, there some *really* strong magnets inside a disk enclosure. Sticking these on the fridge at work is highly recommended.
Comment: I was hoping for a little more DIY approach, but everyone seems to think a specialist is the way to go.

Thanks for all the answers.
Comment: @jscott: It's more of a money kind of thing, but it will be a learning experience if I decide not to send it off.
Answer: http://www.storagesearch.com/disklabs-art3-floods.html

Do NOT attempt to recover the data
  yourself. This will do more damage to
  your data and makes it more difficult
  to recover when it eventually gets to
  a data recovery specialist.
When hard disk drives get wet, the
  'heads' can get stuck to the platters.
  When the hard drive is powered up in
  this state the disk tries to spin up
  and the heads literally get ripped off
  causing damage to the platters - the
  place where all the data is stored. 2
  - Do NOT DRY the hard disk drive out. Although this may seem paradoxical -
  this will nearly always destroy the
  platter of the hard disk thus making
  your data irretrievable.
When hard disk drives get wet then dry
  out, there is nearly always a residue
  of contaminant left on the platters
  and heads. Any residue (including a
  piece of dust), causes physical
  degradation of the hard disk's
  platters and loses more data. 3 - DO
  keep the hard disk WET. Ideally, keep
  the hard disk drive in a sealed
  container to keep the hard disk drive
  wet. This stops the hard disk drive
  corroding and allows the technical
  staff at the recovery company to clean
  and dry the platters correctly with
  minimum damage to the platter
  surfaces.
Normally, Disklabs Data Recovery
  charges a premium for water damaged
  hard disk drives, however, this
  additional charge for the cleaning and
  drying out of the hard disk drive has
  been waivered for the victims of the
  latest flooding events.
Comment: http://superuser.com/questions/100332/water-damaged-parts-is-there-any-chance-of-recovery/100345#100345 quotes similar advice from a different data recovery company.
Comment: I don't know what to say about residue. Don't all drives have a filter that stops dust from entering the case?
Comment: @Cristian I'm guessing those filters don't keep out stuff below a certain size in microns. Once dissolved in water, lot of that crap could get in. As the water evaporates, the dissolved solids would be left behind.
Answer: If you need as much as possible, take it to a specialist.
The inside needs to be free of water and debris (even dust). It might need to be opened in order to dry out the platters. If that's the case, you shouldn't be doing it. Drives need to be opened inside a cleanroom. Dust on the platters is very bad news.
If you don't have the budget for a real data recovery solution, that's fine. Understand that anything you do may limit or destroy the chances of a professional being able to get data off of the drive. If you're willing to take that chance then go ahead and replace the circuit board with a new one off a drive of the same make and model. While you're replacing it, make sure everything is dried off. Say a little prayer, plug it in, and see what it comes up with.
Answer: Putting the hard drive in an airtight container with uncooked rice should help to absorb the moisture.
Edit: further enlightenment suggest this could be risky because of the residue left by contaminants in the water. Therefore, there are a few options:

hand the drive over to a specialist
wash it with clean water before dying it
dry the drive as it is
Answer: On top of the preservation-advice by Josh, do keep in mind data recovery companies will usually charge per file/byte and time spent.
If you can clearly map out what files you absolutely need and how the disks were structured (raid, filesystems, ..) you can keep the costs down.
Squeeze everything you can out of your backups and see what data can be easily reconstructed.
Consult with the business people to see how much what specific data is worth, they may have a very different perspective than us technical people. (also: get any "don't need this data" in writing!)

My server room has flooded


Making UI communicate with logic

Question: I have begun playing around with Shoes.rb and I have an hard time making the UI working with some logics. For instance I'd like to send a message to an object when a button is clicked so I have the following code:
    Shoes.app do
      button "Run" do
        @label.replace Calculator.add(1,1)
      end
      @label = para "Result will show up here"
   end

I have also my Calculator class
class Calculator
  def self.add(x,y)
    x+y
  end
end

How can I make it work?
I have tried to add the class under the Shoes block (adding also it into a module) and having the class in a separate required file but nothing works.
Thanks.
Comment: What error do you get?
Answer: Put Calculator definition before the Shoes.app block:
class Calculator
  def self.add(x,y)
    x+y
  end
end

Shoes.app do
  button "Run" do
    @label.replace Calculator.add(1,1)
  end
  @label = para "Result will show up here"
end

Otherwise, code in the Shoes.app block can't access the Calculator class.
Comment: Thanks, actually I was able also to require external file, I had a typo before.

Making UI communicate with logic


How to make Monit "check process" conditional?

Question: I have a monit script that does something like this:
check process sidekiq_1 with pidfile /tmp/pids/sidekiq_1.pid
 start program = "/bin/bash -l -c 'bundle exec sidekiq start" as uid jim and gid jim with timeout 250 seconds
 stop program = "/bin/bash -l -c 'bundle exec sidekiq stop" as uid jim and gid jim with timeout 120 seconds
 if cpu usage > 25% for 18 cycles then restart
 if mem > 1500.0 MB for 18 cycles then restart

This is great, however I need to have the check made conditional based on the existence of a trigger file like so:
Only execute the check (start the process), if the file /tmp/do_not_start_sidekiq.txt is NOT present.
In this way i could do a touch /tmp/do_not_start_sidekiq.txt if I wanted to shut down the processes and not have monit starting them again, until I do a rm /tmp/do_not_start_sidekiq.txt
How would I do change this monit script to get that behavior?
Answer: The right way to handle this with monit is to "unmonitor" the process...
An example:
monit unmonitor sidekiq_1

Will not attempt to restart or report issue with the process.
You can restore monitoring of the check with:
monit monitor sidekiq_1

These can also be grouped or kicked off by cron. A good real-life deployment may have applications monitored during business hours and unmonitored during downtime windows, controlled by cron...
################################################################################
# Shutdown Cucumber
################################################################################
01  15 * * 1-5 monit unmonitor `/bin/hostname`
50  23 * * 0-5 monit -g servers stop all
51  23 * * 0-5 monit -g base  stop all
52  23 * * 0-5 monit stop all

Edit:
If you need an unprivileged user to be able to control this behavior, you can leverage /etc/sudoers entries for the monit unmonitor/monitor commands.
Something like:
jim ALL=NOPASSWD: /usr/bin/monit unmonitor sidekiq_1

Would allow that specific command to be run by your unprivileged user, jim.
Comment: @NielsKristian Your other option is to run multiple Monit instances. The "Cucumber" example I gave above is from a firm that runs Monit as a non-root user so their developers can control the application, but they also have another system-level Monit that handles server monitoring. They *may* have customized things to make this work.
Comment: I get it, and i thought of it, however I'm not so sure that it's the case here. Now monit is being run by a privileged user with root access. This is to have monit monitoring all kinds of low level stuff like memcached and so on. These services should the less privileged user `jim` not have access to. The user `jim` is a user that several people in my team have authentication to, that can only execute higher level stuff like, restart the application, stop/start the workers (sidekiq) etc. So determining if monit itself should monitor something or not is not my team members' responsibility.
Comment: @NielsKristian See my edit above.
Comment: Hmm okay thanks, at least that's a solution, however I don't really like having coupling to project specific behavior, through monit, in my `/etc/sudoers` file.


No fields to select

Question: In View 3, the contextual filter page is missing some fields; only content, content revision, content translation, file usage, global, search, and user show up. Is this an installation issue?
Answer: Some Tutorials for Drupal 7 show how to use Contextual Filters using Fields, but fields are called Content in the current versions of Drupal7 / Views 3.

No fields to select


How to create react app as a service/package and import it into 'package.json' of another app

Question:  .
Hi currently i m working in a monorepo application in react.
What i need is to extract some of its 'components' & 'styling' and create separate modules/packages that live outside of the main project, and import them into package.json like normal modules.
initial file structure and future proposal structure:

 myMainproject:

    \src
      \components
        component-styles.scss
        \button
        \label
        \list
        \item
        .......
      \modules
        \calendar
        \header
        \footer
        \support
      .....
      package.json
      ....

 // I extract calendar, footer modules

 calendarService:

     \src
      \components
        component-styles.scss
        \button
        \label
        \list
        \item
        .......
      \modules
        \calendar
      .....
      package.json
      ....

 footerService:

     \src
      \components
        component-styles.scss
        \button
        \label
        \list
        \item
        .......
      \modules
        \footer
      .....
      package.json
      ....

 // Extract style and create a separate service

 styleService
      \src
        \styles
         .....
      package.json
      ....

final 'package.json' of 'myMainproject':

  ......
  "dependencies": {
      "calendarService": ...,
      "footerService": .... ,
      "styleService": ...,
      .....
  }

Do you have any ideas, not only technical but architectural also, or any doc to achieve that ?
Comment: Have you tried using https://github.com/lerna/lerna ?
Comment: not really. i just starting. i m open to suggestions. have you accomplished that with lerna ?
Answer: Try to use Yarn workspaces, docs here
Answer: As per the design, for each of the React Module (Calendar, footer and style) that you want to create you'll also need to add an index.js file to the structure. You can name the file whatever you want. This is the file that will get executed when your module will get required.
You'll just have to export your components from the index.js file. In the package.json file of the separate React modules, you'll have to indicate the JS file that you want to execute when that module is required or imported. You do this by providing the name of the file for the main field in package.json


how can I concatenate these mixtures

Question: I have a matrix. for each row of this matrix I made a Gaussian mixture, how can I concatenate these mixtures.
Comment: I'm trying to understand the question. Are you asking that how you can write down the likelihood of the bigger matrix when each of its rows is characterized by a separate Gaussian mixture model?
Comment: yes that's right
Comment: are the rows independent from each other?
Comment: they are independent but the same type
Answer: under independence assumption, the total likelihood of a matrix $\mathbf{M}$ given that each of its rows defined by a Gaussian mixture model $f_i(X|\vec{\theta_i})$ is equal to:
\begin{equation}
\mathcal{L}(\mathbf{M}) = \prod_{i=1}^{N} f_i(X_i|\vec{\theta_i})
\end{equation}
where $N$ is the number of rows in matrix $\mathbf{M}$, and $X_i$ denotes the i-th row in $\mathbf{M}$. The parameter vector $\vec{\theta_i}$ are supposed to be the mixture ratio parameters, mean and variance of the Gaussian distributions in the i-th distribution.

how can I concatenate these mixtures


Problems with PUT request in react.js application

Question: I am having problems with this PUT request when I only edit one of the fields then press save all the values apart from the edited one become null. I am fairly certain it has something to do with the onChange(), but I am not sure what. I have all the relevant code below. Any ideas?
Admin.js
import React, { useContext, useEffect, useState } from "react";
import "./admin.css";
import ApiContext from "../../context/ApiContext";

const Admin = () => {
    const {
        onChange,
        retrieveHeaderData,
        submitHeaderData,
        updateHeaderData,
        headerData,
    } = useContext(ApiContext);

    useEffect(() => {
        retrieveHeaderData();
    }, []);

    let submitOrUpdateHeaderData = async (e) => {
        e.preventDefault();
        if (!headerData) {
            submitHeaderData();
        } else {
            updateHeaderData();
        }
    };

    return (

Change user details

                    <form onSubmit={submitOrUpdateHeaderData}>
                        <input
                            type="text"
                            name="title"
                            placeholder="Title"
                            value={headerData.title}
                            onChange={(e) => onChange(e)}
                        />
                        <input
                            type="text"
                            name="name"
                            placeholder="Name"
                            value={headerData.name}
                            onChange={(e) => onChange(e)}
                        />
                        <input
                            type="text"
                            name="linkedIn"
                            placeholder="LinkedIn"
                            value={headerData.linkedIn}
                            onChange={(e) => onChange(e)}
                        />
                        <input
                            type="text"
                            name="github"
                            placeholder="Github"
                            value={headerData.github}
                            onChange={(e) => onChange(e)}
                        />
                        <button className="btn btn-primary" type="submit">
                            Save details
                        </button>
                    </form>

    );
};

export default Admin;

ApiContext.js
import { createContext, useState } from "react";

const ApiContext = createContext();

export default ApiContext;

export const ApiProvider = ({ children }) => {
    const [headerData, setHeaderData] = useState({});

    const onChange = (e) => {
        setHeaderData((headerData) => ({
            ...headerData,
            [e.target.name]: e.target.value,
        }));
    };

    let retrieveHeaderData = async () => {
        let response = await fetch("/api/retrieve/header-data", {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            },
        });
        let data = await response.json();
        if (response.status === 200) {
            setHeaderData(data[0]);
        }
    }

    let submitHeaderData = async (e) => {
        e.preventDefault();
        let response = await fetch("/api/submit/header-data", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                title: headerData.title,
                name: headerData.name,
                linkedIn: headerData.linkedIn,
                github: headerData.github,
            }),
        });
        let data = await response.json();
        if (response.ok) {
            setHeaderData(data);
            console.log(data);
        }
    };

    let updateHeaderData = async () => {
        let response = await fetch("/api/update/header-data", {
            method: "PUT",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                title: headerData.title,
                name: headerData.name,
                linkedIn: headerData.linkedIn,
                github: headerData.github,
            }),
        });
        let data = await response.json();
        if (response.ok) {
            setHeaderData(data);
            console.log(data);
        }
    }

    let contextData = {
        headerData: headerData,
        onChange: onChange,
        submitHeaderData: submitHeaderData,
        updateHeaderData: updateHeaderData,
        retrieveHeaderData: retrieveHeaderData
    };

    return (
        <ApiContext.Provider value={contextData}>
            {children}
        </ApiContext.Provider>
    );
}

server.js (the PUT request in question)
app.put("/api/update/header-data", async (req, res) => {
    let data = req.body;

    let updateHeaderQuery =
        "UPDATE header SET name = ?, title = ?, linkedIn = ?, github = ?";

    try {
        await database.query(updateHeaderQuery, [
            data.name,
            data.title,
            data.linkedIn,
            data.github,
        ]);
        console.log("Header Data Updated Successfully !");
        return res.json({
            status: "ok",
            message: "Updated data into header table",
        });
    } catch (e) {
        console.error(e);
        res.sendStatus("400").json({
            status: "error",
            message: "Error updating data into header table",
        });
    }
});

Answer: Turns out that it was an issue with the onChange function. Here is what I changed it to.
const onChange = (e) => {
        setHeaderData((prevData) => ({
            ...prevData,
            [e.target.name]: e.target.value,
        }));
    };

Comment: What was the change you made to `onChange` ?
Comment: The previous onChange had `headerData` not `prevData`. It was just a stupid mistake which I should've noticed immediately


SharePoint 2016 FBA on-prem DUO .NET WebSDK

Question: We've configured SharePoint 2016 FBA with the DUO WebSDK and its works well except for one aspect regarding FBA authentication.
login page 1.) authenticate the username and password using FBA-LDAP.
login page 2.) load the duo web iframe
The method that authenticates the username and password on login page 1 is the SPClaimsUtility.AuthenticateFormsUser which persists a cookie to the site.
If the user fails the DUO authentication on login page 2, they still have an authenticated session to the site. We can force a signout and clear session cookies, but I was hoping for a cleaner approach.
Please assist with any ideas.
Thanks!
Answer: We resolved this by validating credentials on the first login page with Membership.ValidateUser which validates against the user store without creating a persisted cookie.  On the second page once the user has successfully passed DUO authentication we used the SPClaimsUtility.AuthenticateFormsUser.  Hope this helps anyone out there!  Have a good one.


How do you build an application in c++ modularly

Question: This is a question more about how to build a c++ application than it is about c++, per se
I'm building an application that was envisioned as a Graphical application, but the specifics of the implementation require a great deal of abstract functionality to facilitate the interface, such as reading lists of objects from files, web resources, etc. I have figured out how to implement this functionality without much difficulty, but I have no good way to test it.  Specifically, I've begun the implementation of the graphical environment, but it is not yet ready to work with the lower-level functionality.
I have also built a good deal of what I want the lower layer to do, but it is as-yet untested.  all of this code resides in a single folder and is stored in a version control system with regular commits.
I'm relatively new to writing anything functional in C++ having only worked on class projects up to this point, but I have written a good number of programs, of various types, in PHP.
If this were a PHP project, it seems it would be simple to test any functionality:

I would simply begin by implementing it interactively
codify it into a small file
write some code that used the functionality
build it into a function
import that function into my larger body of code.

This seems like a really awkward way to do the same with C++.  Have I got it all backwards, how do you solve small isolated problems, in your compiled programs and import them into your projects; is there a workflow that you find helpful.
Answer: Generally speaking, the answer to your question is using classes and unit testing.  Do an internet search for Agile / Extreme Programming.
The idea is this:

Do all the agile story stuff (I'll let you read about this on your own)
You break out your design into classes
Write unit tests that define the "spec" for your class
Write empty placeholder functions.
See the unit tests fail.
Write code until the unit tests succeed.
Go back to step 3 and repeat for the rest of your classes.

If you write code in this manner, you create reusable and robust code.
Honestly, I don't personally believe in TRUE TDD (test driven development) -- I feel it's better to write your unit tests after you've written your code (I feel the impending flame of doom coming from users screaming "AGILE OR DIE!").
EDIT:  If your question is more along the lies of the actual BUILDING of multiple classes, well that's easy.  Generally speaking, each of your classes should be encapsulated in 2 files (source code and header file).  Just include those files (along with files from all other classes you want to use) in a new project.  #include "xxx.h" in the appropriate places where you need to use the classes, write your code that uses those classes, and build.  That's it.
Comment: To answer your comment from below:

If you've already written code (sounds like you're not using Agile/XP methods -- that's fine). Then I would create an interface to use it (which honestly you should have done already). Create a USABLE .h file (many people put stuff in .c that should be in .h, and vice-versa). Then import those files into a new project when you need them.
Comment: Clarification:

SO -- I'm using classes, I'm working with QT, and I have a lot of the code built -- should I just take the code I've written, copy it into a new folder, write a simple interface, and then compile/test? is that the best option.
Answer: I guess this would be the general tactic for any OO project.
First determine the main components and make sure you have a very thorough understanding of what everything is responsible for.
Write out the interface for each component, and check (logically) to see that it fits your problem.
Implement each module.
As far as testing is concerned make tester modules (stubs): for example make a class that will send input to the GUI mimicking the input that would be sent by the actual component. Since you have a clear idea of the interface, how this result was produced would be irrelevant.
Repeat this process for each component in your system and then put them together.
Hope it helps
Answer: I am currently in a similar situation, where I have implemented bits-and-pieces of functionality (file I/O through some API, main parts of the work, etc.). So maybe some of my experiences would be helpful:

If you have some code already, it may help to draw a diagram of what you have. Pen-and-paper, or even better UML can help here (btw, a good UML tool which can import existing classes is Umbrello). Sometimes I do this kind of "design check" after the last commit, and it helped me to spot some subtle problems, especially in the design stages, where I was refactoring classes daily;
If you have written code for the components, I think you can easily formulate some requirements for each one, and from these you can create some tests (e.g. with 'UnitCPPLite'). Currently, I have the test in the main file, with some boilerplate code which triggers the test execution before anything else is done in the application (although this is still not optimal);
Finally, I would add to the recommendation of ComtriS the idea of "include guards" (if you don't use them already), to prevent multiple inclusion of the header files. So, in practice, I typically end-up with something like this:

src/CFoo.h:
<code>// class 'CFoo': header file
#ifndef CFOO_H
#define CFOO_H

#include <only_what_you_need_in_declaration_interface>

class CFoo {
    private:
        // class data
    public:
        // constructors, destructors, getters, setters, etc.
        void doWork();
    };
#endif /* CFOO_H */
</code>
src/CFoo.cpp:
<code>// class 'CFoo': implementation file
#include "CFoo.h"
#include <what_you_need_in_addition_for_internal_workings_of_methods>

// code for other methods...

void CFoo::doWork() {
    // work
}
</code>
Hope it helps.


does rstandard standardize in z?

Question: I'm new to R, so please be gentle.
I was under the impression that rstandard(model) returns the z-scores of the residuals in model. However, when I standardized the residuals myself in z, the result was different. In fact, rstandard(model) had a mean different from 0 and had a standard deviation different from 1. The differences seem to be nonnegligible. What exactly does rstandard(model) do? Or am I doing something wrong here?
> x = rnorm(30, mean = 100, sd = 15)
> y = rnorm(30, mean = 100, sd = 15)
> model = lm(y ~ x)
> z.res = residuals(model)/sd(residuals(model)) #standardizing it myself
> rstandard(model) - z.res #difference between rstandard and what i did
            1             2             3             4             5
-4.422354e-04  1.556269e-04 -4.576832e-03 -1.274350e-03  1.048068e-01
            6             7             8             9            10
-2.333922e-02  1.820134e-02 -3.307542e-03  3.368978e-02 -1.804108e-04
           11            12            13            14            15
-1.100621e-01 -1.343715e-03 -1.300427e-03  1.509862e-03  3.246602e-03
           16            17            18            19            20
 3.734255e-03 -1.821539e-06 -1.153190e-02 -1.713254e-06 -2.185101e-02
           21            22            23            24            25
-2.681935e-02  2.562472e-03 -4.721114e-02 -1.084481e-04 -3.430827e-03
           26            27            28            29            30
 4.149684e-04  7.705807e-04  2.166815e-03  2.537837e-02  4.182761e-04
> mean(z.res)
[1] -9.428041e-18
#as expected of z-scores, mean is 0
> sd(z.res)
[1] 1
#as expected of z-scores standard deviation is 1
> mean(rstandard(model))
[1] -0.001990908
#not really 0
> sd(rstandard(model))
[1] 1.019699
#not really 1

Also, the way I understood Standardized residuals in R's lm output, rstandard is actually studentized residuals. But isn't there already rstudent?
I'm using R version 2.14.1 in Xubuntu 12.04.
Thank you.
Comment: The residuals don't have constant variance, even though the error term does. Points with more extreme 'x'-values have smaller variance. If you want to make them comparable, you don't divide by their *average* standard deviation, but by their individual standard deviation. This is what is going on. On the other hand, `rstudent` computes *externally* studentized residuals, not internally studentized residuals.
Answer: rstandard() produces standardised residuals via normalisation to unit variance using the overall error variance of the residuals/model.
rstudent() produces Studentized residuals in the same way, but it uses a leave-one-out estimate of the error variance.
The key line in rstandard() is
res <- infl$wt.res/(sd * sqrt(1 - infl$hat))

where sd is defined as
sqrt(deviance(model)/df.residual(model))

where model is the object returned by lm. But note this is not the same as sd(resid(model))
Note that the sd is also scaled by the hat values $1 - h_{ii}$ which together explain the discrepancy with your values.
The key line in rstudent() is
res <- res/(infl$sigma * sqrt(1 - infl$hat))

which is almost the same but sd is replaced via the leave-one-out estimate of the error variance (sd) infl$sigma
Answer: The two functions do different things, as I understand it.
residuals(model) gives the response minus the fitted values. (from help for lm)
rstandard(model) is part of leave one out influence diagnostics (from help for rstandard), which says:

This suite of functions can be used to compute some of the regression
  (leave-one-out deletion) diagnostics for linear and generalized linear
  models discussed in Belsley, Kuh and Welsch (1980), Cook and Weisberg
  (1982), etc.

You can examine exactly what rstandard does by looking at the code. For lm, you can do this with
> methods(rstandard)
> getAnywhere(rstandard.lm)

.
Comment: As `rstandard.lm` is exported from the `stats` namespace, you can just type its name at the prompt without needing `getAnywhere()`.

does rstandard standardize in z?


MaxRequestWorkers setting

Question: I have a vps with Ubuntu 14.04.1 LTS and plesk 12.01
Where I have 8 active domains.
Many times I find myself off the http service logs the following error:
<code>server reached MaxRequestWorkers setting, consider raising the MaxRequestWorkers setting

<IfModule mpm_prefork_module>
    StartServers             5
    MinSpareServers       5
    MaxSpareServers      10
    MaxRequestWorkers     150
    MaxConnectionsPerChild   0
</IfModule>

<IfModule mpm_event_module>
    StartServers             2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxRequestWorkers     150
    MaxConnectionsPerChild   0
</IfModule>

<IfModule mpm_worker_module>
    StartServers             2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxRequestWorkers     150
    MaxConnectionsPerChild   0
</IfModule>
</code>
I tried different configurations, but nothing.
Just start the apache service sites go quietly, after 2-3 minutes they all go off. But the cpu and ram are completely free.
In plesk I only active mpm_prefor
How can I fix this?
Answer: Can you please try to increase MaxRequestWorkers value on your server to 250 and monitor your Apache services logs, if you are getting same issues that meas your server is under DDOS attack and due to that you are getting this issues,

MaxRequestWorkers setting


Problemas com :checked css

Question: Estou tentando fazer com que um menu apareça quando o checkbox estiver checado

/* Menu Mobile */
.mobile{
 position: fixed;
 display: block;
}
.mobile input{
 display: none;
}
.mobile label{
 color: yellow;
 font-size: 8vh;
 text-align: center;
 cursor: pointer;
 width: 8vh;
 display: none;
}
.menu-mb{
 background-color: #111;
 display: none;
 margin-top: 9vh;
 width: 75vw;
 height: 100vh;
 position: fixed;
}
.menu-mb ul{
 list-style: none;
}
.menu-mb ul li{
 float: none;
 width: 100%;
}
.menu-mb a{
 text-decoration: none;
 color: white;
 padding: 2vh;
 display: block;
 text-align: center;
}
@media(max-width: 800px){
 .mobile label{
  display: block;
 }
 .mobile input:checked .menu-mb{
  display: block;
 }
}

    <input type="checkbox" id="bt-menu">
    ≡

Shounen

Shoujo

Ecchi

Tentei usar o :checked para quando o input estiver checado o menu ficar com disblay: block; mas não funciona, Só funciona quando eles estão em uma mesma div mas não quero fazer assim.
Comment: `.mobile input:checked` Porque você não faz isso. Só existe um input:checked na classe mobile
Comment: @MauryDeveloper eu quero que quando esse input esteja checado ele altere o .menu-mb.
Answer: Isso não irá funcionar mesmo. Da forma como está sua regra .menu-mb teria que ser um filho de .mobile input:checked, o que não condiz com a sua marcação. O que você pode fazer é mover o input=checkbox para fora do elemento que ele está, como se fosse um "controlador global". Assim, a ação de :checked nele poderá alterar qualquer outro elemento seguinte.

input#bt-menu { display: none } /* Esconde o input controlador */
input:checked ~ .menu-mb { display: block !important } /* Exibe o menu quando estiver checado */

/* Menu Mobile */
.mobile{
    position: fixed;
    display: block;
    background-color: #111;
    width: 100%
}
.mobile label{
    color: yellow;
    font-size: 8vh;
    text-align: center;
    cursor: pointer;
    width: 8vh;
    display: block
}
.menu-mb{
    background-color: #111;
    display: none;
    margin-top: 9vh;
    width: 75vw;
    height: 100vh;
    width: 100%;
    position: fixed
}
.menu-mb ul{
    list-style: none;
}
.menu-mb ul li{
    float: none;
    width: 100%
}
.menu-mb a{
    text-decoration: none;
    color: white;
    padding: 2vh;
    display: block;
    text-align: center
}
<input type="checkbox" id="bt-menu">

  ≡

Shounen

Shoujo

Ecchi

Comment: vlw pela dica!!
Answer:  Tenta com as alterações realizadas no .css

/* Menu Mobile */
.mobile{

 display: block;
}
#bt-menu{
 display: none;
}
.mobile label{
 color: yellow;
 font-size: 8vh;
 text-align: center;
 cursor: pointer;
 width: 8vh;
    cursor: pointer;
}
.menu-mb{
 background-color: #111;
 display: none;
 margin-top: 9vh;
 width: 75vw;
 height: 100vh;
 transition: all 0.5s;
    transform: translateX(-100%);
}

#bt-menu:checked ~ .menu-mb{
transform: translateX(0%);
}

.menu-mb ul{
 list-style: none;
}
.menu-mb ul li{
 float: none;
 width: 100%;
}
.menu-mb a{
 text-decoration: none;
 color: white;
 padding: 2vh;
 display: block;
 text-align: center;
}
@media(max-width: 800px){
 .mobile label{
  display: block;
 }
 .mobile input:checked .menu-mb{
  display: block;
 }
}

    <input type="checkbox" id="bt-menu">
    ≡

Shounen

Shoujo

Ecchi

Comment: obrigado!!!!!!!

Problemas com :checked css


For which natural numbers n is the number $s^n+1$ divisible by $10$?

Question: For which natural numbers $n$ is the number $s^n+1$ divisible by $10$?
I want to take case of the form $10k, 10k+1, ..., 10k+9$. But I am not sure which number $s$ or $n$ to use for cases or if I am suppose to do it for?
Comment: I think the problem is missing context. where did you find this problem?
Comment: so $s$ need not even be an integer?
Comment: what conditions are you putting on $s$?
Comment: To get ya started: $3^2+1=10$.
Comment: @symplectomorphic there are no conditions on s
Comment: @symplectomorphic nope. s doesn't need to be an integer.
Comment: If $s$ is not an integer, the resulting expression is entirely at $s$ will. Besides from positivity, $n$ has no opinion here.
Comment: If you're allowing non-integers, it doesn't make sense to talk about divisibility, does it?
Comment: @Cadenza The obvious solution is to take divisible by 10 to mean "is an integer that is divisible by 10". But if one allows non-integers the problem is easily reduced back to the integer case.
Answer: Hint: $s^n +1 \equiv 0 \mod 10 \iff s^n \equiv 9 \mod 10 \iff s^n$ has a $9$ for its unit digit.