Is there any closed form for this series?

Question: It's a power series that I found during the computation for my research.
\begin{equation*}
\sum_{k=0}^n \binom{n}{k}\frac{n!}{(n-k)!}x^{n-k}(-1)^k.
\end{equation*}
Without the annoying term of $\frac{n!}{(n-k)!}$, it is clearly simplified to $(x-1)^n$ due to binomial theorem.
Isn't there any name for this series? Can I simplify it as a closed-form polynomial?
Answer: You can write it this way: $$\sum_{k=0}^n \binom{n}{k}\frac{n!}{(n-k)!}x^{n-k}(-1)^k
= \sum_{k=0}^n \binom{n}{k}(-1)^k\frac{d^k}{dx^k} (x^n)
= \left(I-\frac d{dx}\right)^n x^n
$$
Comment: Interesting. I found out that it's an [associated Laguerre polynomial](http://mathworld.wolfram.com/AssociatedLaguerrePolynomial.html). By the way, would you recommend a textbook or reference on how to handle differentiation as a linear map? I don't have much background on this field and I need to learn myself on this topic.
Comment: I don't think there is much to know about on this topic.
Answer: It can be rewritten as $\displaystyle\sum_{k=0}^n{n\choose k}^2k!x^{n-k}(-1)^k$, and, unless you're willing to accept hypergeometric functions as closed form, the answer is no. My advice would be for you to try and approximate it asymptotically.
Comment: To be honest,I dont understand the other answer.
Comment: Differentiation is a linear map; the identity map is a linear map; linear maps form a ring, so $(I-d/dx)^n$ is a well defined linear map. The series given above is what $(I-d/dx)^n$ maps $x^n$ to.
Comment: @Sabyasachi ? why don't you comment on my answer?
Comment: @mookid i upvoted anyway. it looked legit.


Symfony2: File Upload throws undefined property exception

Question: I want to perform an image upload with Symfony2.
I followed the cookbook entry but failed so I firstly used the fallback "upload directly in the controller" but here's the same issue.
I am getting
<code>Notice: Undefined property:  Symfony\Component\Form\Form::$getData in
</code>
The controller isValid() part:
<code>            if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();

            $filename = uniqid('class_photo') . '.' . $photo->getFile()->guessExtension();
            $directory = __DIR__ . '/../../../../web/';
            $form['file']->getData->move($directory, $filename);
            $photo->setFile(null);
            $photo->setPath($directory . $filename);

            $em->persist($photo);
            $em->flush();
//....
}
</code>
Best Regards,
Bodo
Answer: This:
<code>$form['file']->getData->move($directory, $filename);
</code>
Should probably be:
<code>$form['file']->getData()->move($directory, $filename);
</code>
But I think you would be better off figuring out why the cookbook example did not work for you.  once a form has been validated you really should not need to go back in to it.
Comment: Hi,

I figured it out the issue was that I left $form->upload() in the controller even the entity now handles the upload


Size of files of a scanned directory - PHP

Question: I want to read a directory and get the filesize of each file.
I tried the following code:
$downloads = array_slice(scandir("downloads"),2);
$size = array();
foreach($downloads as $value) {
    $size = filesize("downloads/".$value);
    echo($size); //at this point the echo works correctly
}
echo($size); //shows the filesize of the first file
echo($size[1]) //nothing happens
foreach($size as $value) {
    echo($value); //nothing happens
    echo($size); //nothing happens
}

That's why I'm quiet confused about the work with arrays and loops right now.
It would also be nice to save the filenames and their corresponding filesizes in one array.
Thanks for your suggestions.
Answer: You're doing it wrong. You're overriding the array in the foreach.
foreach($downloads as $value) {
    $size = filesize("downloads/".$value);
    // $size is not an array anymore, just an int
    echo($size); //at this point the echo works correctly
}

This should be correct:
foreach($downloads as $value) {
    $size[] = filesize("downloads/".$value);
}

Full code:
$downloads = array_slice(scandir("downloads"),2);
$size = array();

foreach($downloads as $value) {
    $size[] = filesize("downloads/".$value);
}

foreach($size as $value) {
    echo($value).'
';
}

Answer: You are constantly overwriting the $size variable, that's why it is not carried on with each foreach execution.
You should create a $size array and store everything accordingly:
$size = array();
foreach ( $downloads as $file ) {
    $size["downloads/".$file] = filesize("downloads/".$file);
}

foreach ( $size as $fname => $fsize) {
    echo "Size of " .$fname. " is " .$fsize. " bytes.";
}

Answer: When you assign the value:
foreach($downloads as $value) {
       $size = filesize("downloads/".$value);
       echo($size); //at this point the echo works correctly
   }
you need to add it to a specific record of 'size' as
$size[ $n ] = filesize( ... );


Google Play 0 supported device

Question: I am trying to upload an update to google play store but after uploading the apk it says 0 supported device.
Some of the similar questions are caused by 3rd party libraries but i don't use any new library.
I am using v7 appcompat support library. I was using v4 previously and it had no problem with Google Play. I don't know if this is the problem but this is the only change i made in terms of external libraries.
Here is my manifest file :
<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.saliherikci.poemnotebook"
    android:versionCode="10"
    android:versionName="2.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="25" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:logo="@drawable/ic_action_logo"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.saliherikci.poemnotebook.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.saliherikci.poemnotebook.ReadPoemActivity"
            android:label="@string/title_activity_read_poem" >
        </activity>
        <activity
            android:name="com.saliherikci.poemnotebook.SelectedAuthorsPoemsActivity"
            android:label="@string/title_activity_selected_authors_poems"
            android:parentActivityName="com.saliherikci.poemnotebook.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.saliherikci.poemnotebook.MainActivity" />
        </activity>
        <activity
            android:name="com.saliherikci.poemnotebook.FavouritesActivity"
            android:label="@string/title_activity_favourites"
            android:parentActivityName="com.saliherikci.poemnotebook.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.saliherikci.poemnotebook.MainActivity" />
        </activity>
    </application>

</manifest>
</code>
I wonder what might be the problem.
Answer: I ran into the same thing last night and read the most recent articles on this and I guess there is a recent Google bug causing the supported devices to always show up as 0 until it's actually rolled out to production.
I took a chance and released the update and sure enough all the supported devices were there in production. So if you haven't changed anything in the Manifest from the last release you're probably safe to do so as well. (Also I don't see anything in the posted Manifest that would cause any issues)
Comment: Yes it was a bug from Google. I uploaded the app everything is fine. People are able to download it.

Google Play 0 supported device


linear regression with dependent and independent variables as percentages

Question: I would like to test whether the prevalence (in %) of parasite-infected individuals of population A (second host) is correlated with the prevalence of parasite-infected individuals of population B (first host). I have seven stations in total, in each of them I sampled 30 individuals of population A and 40 individuals of population B. So, I have 14 data points in total, 7 belonging to B, 7 belonging to A. In general I want to see if there is any correlation between the presence of parasites in A and the presence of parasites in B. I calculated prevalence in percentages. First, can I apply a linear regression to verify the correlation? If yes, but the data are not meeting the assumptions of linear regression, can I transform percentages (with log, for example)?
Comment: Done. As an example: in one station I have 30% of population B (first host) and 90% of population A (second host) infected with parasite species x. And I would like to see whether the prevalence of parasite x in the second host is correlated with the one of the first host. Thank you so much for further comments
Comment: You have two data points, 1. 30% of B infected with x and 2. 90% of A infected with x. You cannot do correlation between 1 data point and the other. What do you want to know from the statistical test?
Comment: In theory you can regress one against the other by doing a logit transformation.If you want to look at correlation, why don't you just perform a spearman correlation?
Comment: Hi! Actually I did perform a spearman but then my supervisor was not agree with that. He was saying that since we cannot rank them, Spearman correlation cannot be used, or something like that (I'm still a beginner).
Comment: Sorry I am quite confused now. Can you edit your post and give us more information on what your data is like? To do correlation, you should have the same individuals that are parasitised in A or B. I think something is missing between what you are supposed to find out and the nature of your data
Comment: I have seven stations in total, in each of them I sampled x individuals of population A and x individuals of population B.  So, I have 14 data points in total, 7 belonging to B, 7 belonging to A. In general I want to see if there is any correlation between the presence of parasites in A with the presence of parasites in B.
Comment: Thanks, yes that makes sense now. This is important information, so please include it in your main post. If you have on 7 data points for each, your supervisor argues it's hard to rank. You can see my answer below and tell me if it makes sense
Answer: I do not have your data, but below i simulate some data according to what you describe, and you can see how correlation works
<code># number of stations
n=7
# number of individuals sampled per station
# i assume all of them to be 40
x = rep(40,n)
# simulate probability of being infection in A
true_pA = runif(n,max=0.5)
# make the probability in B some function of A, with some error
true_pB = 2*true_pA + runif(n,max=0.1)
# simulate the data under a binomial
A = rbinom(n,size=x,p=true_pA)
B = rbinom(n,size=x,p=true_pB)
# you can see the counts are correlated
plot(A,B)
</code>
You should get something like:

Because you sampled the same number of individuals per station, you can simply do a pearson correlation between the two values, with 0.5 to handle zeros (as pointed out by AdamO):
<code> cor.test(log(A+0.5),log(B+0.5))
</code>
If however you want to correlate the ratios,let's say if you have different number of individuals sampled between population.
<code>cor.test(log((A+0.5)/x),log((B+0.5)/x))
</code>
The correlation is identical to a test of slope in linear regression (this link should be ok), but in this case we just transform the count values using log, which works as a good approximation most of the time.
Comment: 1. test of slope coefficient in OLS is identical to a test of correlation. 2. one could log transform the predictor and response, but to say that doing so tests the ratios specifically is misleading. 3. Using the 0.5 constant to the log transform is done simply to handle 0 values, and does not require 0.5 *per se* all the while introducing sensitivity as to what constant you *do* choose to offset the log transform.
Comment: Hi @AdamO, so what would you suggest? If you read the comments above, the same number of individuals are sampled, so I suggest simply correlating the counts. Yes, I agree if you have ratios or rates, then you transform them differently.
Comment: I agree with 1. and 3. , so I have changed the wording in my answer to be more specific. Thanks you for pointing that out.
Comment: Thank you so much to both of you. I think I will use pearson correlation. By the way, I really did not explain it well at the beginning. The number of individuals sampled differs from the two populations (by 5-10 more in B than A in all seven stations), and so it would may better to correlate the ratios. I guess that if I follow exactly your indication I should use the row dataset, with presence/absence (as 0 or 1) of parasite in each individual and then divide for the total. The other option is to directly use the percentages dataset, right? But I would say that the output should be the same.


Where can I find NBA stats for shots made or missed after a foul?

Question: I am looking for the names of websites that show NBA team season percentages of 2 point and 3 point shots that were made and missed after a foul.
Thanks to all for your help.
Answer: A shot that is missed, after a foul, doesn't count as a field goal attempt, so I don't think it's really possible or useful to keep track of it
Comment: How many times a team went to the line for 1 or 2 shots after a foul and for 1 or 3 shots after a foul?


When advantage is played on a DOGSO situation, and a goal is scored, should the offender always be cautioned?

Question: This question was inspired by something that happened during a Serie A match between Napoli and Milan yesterday. A defender handles the ball to prevent it from crossing the goal line: advantage is played, an opponent shows up, collects the ball and scores (here is the relevant GIF). The defender was issued a yellow card. Now I am wondering: why is it a yellow card instead of a red card?
The way I see it, there is a difference between denying a goal to the opposing team (which can only be done by handling the ball on the goal line) and denying an obvious goal-scoring opportunity to the opposing team. This said, Law 12 reads:

If the referee plays the advantage for an offence for which a caution / send off would have been issued had play been stopped, this caution / send off must be issued when the ball is next out of play, except when the denial of an obvious goal-scoring opportunity results in a goal the player is cautioned for unsporting behaviour.
  (Law 12)

This is NOT relevant to our situation, because the defender denied a goal and not an obvious goal-scoring opportunity. The following paragraph should be applied instead:

There are different circumstances when a player must be cautioned for unsporting behaviour including if a player [...] handles the ball [...] in an unsuccessful attempt to prevent a goal
(Law 12)

This is where I am questioning the referee's decision. It should not matter if the attacking team ended up scoring anyway: a goal has still been prevented, because what was scored next was another, different goal. So I think the right decision should have been to let the goal stand, and send the defending player off instead of just cautioning him.
Am I right, or is there anything in the Laws I am missing?
Comment: There are now three answers to this question. Please consider accepting one - if none are suitable, please leave commentary on each answer stating any problems you have with it.
Answer: If advantage is played for a DOGSO offence, and a goal is scored as a result, then a goal has not been denied to the advantaged team.
Therefore, the player is not sent off for DOGSO (given a red card) but instead cautioned (given a yellow card) for unsporting behaviour.
This is precisely in line with the guidance in IFAB Law 12 for this specific case:

..., except when the denial of an obvious goal-scoring opportunity results in a goal the player is cautioned for unsporting behaviour.

Therefore, the referee was correct in Law to caution the player, regardless of the sequence of actions (i.e. it doesn't matter whether the hand-to-ball or the goal happened first) because a goal was still scored.
Comment: I'm going to disagree with one element of this answer. If the goal was scored, and then the player handled the ball, there should be no caution. This is because the ball is out of play as soon as the goal is scored and it is not an offence to deliberately handle the ball when it is out of play.
Comment: @studro it is not an offence as handling the ball, but it is an offence as unsporting behaviour.
Comment: What exactly is unsporting about handling the ball when it is out of play? I believe the caution was given because the referee believed the ball was still in play when the defender handled it. If the ball is out of play, and it is the defender's restart (ie. a kick-off), they are entitled to handle it.
Comment: The defender believed the ball was in play, and their deliberate handling was done with intent to prevent a goal being scored. That's unsporting behaviour - regardless of the fact it wouldn't have stopped a goal. The same as if he'd tried to punch someone. It doesn't matter that he missed and therefore didn't actually make contact, it's still violent action and would be sanctioned.
Comment: Tactical misconduct is generally *not* punished based on intent. If a player fouls an opponent who is away on a promising attack, they are cautioned, even if they intended to win the ball. It's impossible to deny a goal if the ball is out of play, so it's impossible to attempt to deny a goal if the ball is out of play.
Comment: Furthermore, violent conduct is not usually judged on intent either. If a player swings an arm with excessive force near or at an opponent, whether or not the ball is in play, this is violent conduct. It's irrelevant as to whether the player intended to strike the opponent or not.
Comment: @studro Nij is 110% right. I don't think handling the ball **intentionally assuming the ball is still in play** to block a goal is tactical misconduct. You missed one point. The defender (who is cautioned) does it when he is 100% confident that the ball is in play. Why would he touch the ball when he knows the ball is out of play? You should note that picking up the ball for a faster attack or counter-attack and handling the ball are completely different.
Comment: It **is** tactical misconduct. Committing a foul to break prevent a goal is entirely tactical. That's why it's punished with more than just a free kick or penalty kick ie. a sending-off or caution depending on the circumstances. It's completely irrelevant what the defender thinks. If the ball is out of play, it can't be a foul. If it can't be a foul, it can't have denied an obvious goal or obvious goalscoring opportunity. If it hasn't done that, it's not a cautionable or sending-off offence.
Answer: There are a number of points in your question that I will address separately.

When advantage is played on a DOGSO situation, and a goal is scored, should the offender always be cautioned?

From what I can gather, the first question is whether attempted but unsuccessful denial of a goal or denial of an obvious goalscoring opportunity by committing an offence should always result in a caution for unsporting behaviour, or whether the referee can choose to not caution the player.
From Law 12, Section 3, Laws of the Game:

Advantage
If the referee plays the advantage for an offence for which a caution / send off would have been issued had play been stopped, this caution / send off must be issued when the ball is next out of play, except when the denial of an obvious goal-scoring opportunity results in a goal the player is cautioned for unsporting behaviour.

So if the player would have been sent-off for denying an obvious goalscoring opportunity or goal had play been stopped, the send-off is instead downgraded to a caution for unsporting behaviour. By the letter of the law, this caution is mandatory.
In previous editions of the Laws, this caution was discretionary (notice the wording change - must vs may).
p. 132 of the 2015/16 FIFA Laws of the Game:

If the referee applies advantage during an obvious goalscoring opportunity and a goal is scored directly, despite the opponent's handling the ball or fouling an opponent, the player cannot be sent off but he may still be cautioned.

It will be interesting to see whether this was an intentional change or an oversight - there have already been a number of errors in this edition of the Laws, as it has been a significant revision and was undertaken in a very short period of time. Some have been amended in the FAQ (eg. see Q6 and Q7 here - reading the Laws without the FAQ initially implied a direct free kick rather than an indirect free kick restart for dissent) and others have not (as shown in this answer).

This is where I am questioning the referee's decision. It should not matter if the attacking team ended up scoring anyway: a goal has still been prevented, because what was scored next was another, different goal. So I think the right decision should have been to let the goal stand, and send the defending player off instead of just cautioning him.

The second element, is whether the player should be sent-off, for example, if they handle the ball on the line, the ball bounces outwards and then another shot is taken - ie. the first goal is denied illegally, but the second one is scored.
Returning to the quote from Law 12, Section 3, Laws of the Game:

... except when the denial of an obvious goal-scoring opportunity results in a goal the player is cautioned for unsporting behaviour

I believe there has been editorial oversight here - how it should have read is:

... except when the denial of a goal or an obvious goal-scoring opportunity results in a goal the player is cautioned for unsporting behaviour

The reason the send-off is impossible if the goal is scored, is due to advantage clause in Law 5, Section 3 of the Laws of the Game:

The referee:
...

allows play to continue when an infringement or offence occurs and the non-offending team will benefit from the advantage and penalises the infringement or offence if the anticipated advantage does not ensue at that time or within a few seconds

When a player commits an offence that denies a goal or an obvious goalscoring opportunity, there are only two possible outcomes:

the denial results in a goal, meaning the anticipated advantage has ensued. The player is cautioned for unsporting behaviour, and a kick-off is taken by the conceding team.
the denial does not result in a goal, meaning the anticipated advantage has not ensued. Therefore, the referee must award a free kick or penalty kick, and sends-off the player for denial of a goal or goalscoring opportunity (unless the offence occurred in the penalty area, is a genuine attempt for the ball and was not pushing or holding, in which case the player is cautioned for unsporting behaviour - see Law 12, Section 3, Denying a goal or an obvious goal-scoring opportunity ).

The sending-off punishment is mostly restorative in nature. If the denial results in a goal, even if it isn't the original attempt, there is no need to give the scoring team the advantage of an extra player. That is why the offence results in a caution rather than a send-off. The caution is given to deter the player from committing further tactical fouls in future.
In the situation you linked, it has been noted in other answers that the player actually handled the ball after it had crossed the line. The reason the player was cautioned was because the referee believed that the player deliberately handled the ball while it was in play, and had advantage not ensued (ie. by a goal being scored), he would have been sent-off.
However, since the player could not possibly have been sent-off here, since the ball was out of play when the deliberate handling occurred, the referee would have been correct to not caution the player. A verbal warning would have still been appropriate.
Answer: It is very important to note that the fourth goal was recorded as Romagnoli's own goal, which means the goal was already scored before the defender (Romagnoli) tried to handle the ball to prevent it from crossing the goal line. It had already crossed the line bouncing off him before he touched it. Even if he had not handled it, the goal would have been scored. The sequence of the actions is

The ball was bounced off him.
The goal was scored as his own goal (Advantage was not played).
He tried to prevent the goal with his hand not knowing the goal had crossed the goal line. In other words, the handling foul was committed after the goal crossed the goal line.
The referee issued a yellow card to him.

The linked article clearly shows the record as follows:

Napoli: Reina; Hysaj, Albiol (Vlad Chiriches 89'), Koulibaly, Ghoulam;
  Allan, Jorginho, Hamsik; Callejon, Milik, Mertens (Insigne 78')
Goals: Milik (18', 33'), Callejon (74'), Romagnoli O.G. (90'+2)
AC Milan: Donnarumma; Abate (Calabria 80'), Gomez, Romagnoli, De
  Sciglio; Kucka (red 75'), Montolivo, Bonaventura; Suso (Lapadula 86'),
  Bacca (Jose Sosa 80'), Niang (red 87')
Goals: Niang (51'), Suso (55')
(Emphasis mine)

There is no reason why the law you stated in the question can't be applied. It was the right decision to issue a yellow card to him.
Comment: Yesterday's match did inspire my question, but it is independent of what actually happened on the field of play. Even if it was counted as Romagnoli's own goal, what I'd like to know is: should have he been cautioned or sent off, in the hypothetical situation the ball had not crossed the line before he touched it with his hands? And if the correct answer is a yellow card, what is the flaw in my argument?
Comment: @FilippoLaBarbera Well, your argument is based on the fact that you didn't know it was his own goal saying **advantage was played**. No, there was no advantage. There is no flaw in the Law. The goal was scored anyway and why would the referee send off the defender which is against the Law? If the goal is not successful, the defender will be sent-off. It is clearly stated in the Laws. It all depends on whether the goal is prevented by handling.


Auto send userA's profile URL to userB

Question: I thought this could be easy, but I don't know what's the best way to achieve this.
I have an acting "job" application site, userA need to finish his "profile2" first which including photos, weight, height etc..  userB will post a job node, then userA will click an "apply" button within the job node, userB will receive a message/email which including the userA's profile URL, then userB can look at userA's profile to decide if this person is ok for his job. I can't figure out which module I should use to make this process works, email/webform/privatemessage ? if you can suggest how to make this works. thanks
Answer: You could build a flow like this using the Flag module.
General steps

Create a flag, Apply for job that targets the job node entity.  Make it a per-user flag, not a global flag.
Give job applicants permission to flag job nodes.
Create a view that show's the job poster all the flags on their job node, and use a relationship to pull in each applicant's profile.
Comment: thanks it works
Comment: @lee You're welcome.  On *Drupal Answers* and other Stack Exchange network sites, you don't need to say thanks; instead, if the answer solves your problem, you can click the checkmark to "accept" the answer and mark your question as solved.  This is the Stack Exchange network way of saying thanks.

Auto send userA's profile URL to userB


Mysql/PHP PDO statement failing with wildcard

Question: $pdo = $db_con->prepare("SELECT COUNT(*) FROM table WHERE Age=:Age AND ClientID=:ClientID AND LastName=:LastName");
$pdo->bindValue(':Age', $_SESSION['Age']);
$pdo->bindValue(':ClientID', $ID);
$pdo->bindValue(':LastName', $Last_Name."%");
$pdo->execute();

Adding the wildcard after $Last_Name is causing the statement to produce no results.
If the value for $Last_Name is Smith that produces a results but only if the wildcard is not there. I have tried the wildcards on both sides and the same thing happens.
No errors are generated.
Answer: That's because you're not using a LIKE comparison. Wildcards only apply when using LIKE. Since you're doing an equality test (=), you're literally requiring that a % be present in the matched data.
Try
SELECT .... AND LastName LIKE :LastName

instead.
Answer: You want to use LIKE:
SELECT COUNT(*) FROM table WHERE Age=:Age AND ClientID=:ClientID AND LastName LIKE :LastName


Creating a cumulative sum column

Question: Sample table ID: (num is a key so there wouldn't be any duplicates)
num
1
5
6
8
2
3

I need a query to make this:
Desired output:
 (Should be sorted and have a cumulative sum column)
num cumulative
1    1
2    3
3    6
5    11
6    17
8    25

In Mysql I have
Select num as n,
       (select sum(num) from ID where num <= n)
from ID order by n;

I picked up this example in this link but in MySqlServer
Comment: Then there will be no exact decision without proper identifying column
Comment: No, this column is simple value column @OlegDok
Comment: Table layout, please! And sum of what anyway?
Comment: You find a solution here:
https://stackoverflow.com/questions/2120544/how-to-get-cumulative-sum
Answer: Try this:
SELECT num,(SELECT SUM(num) FROM tab WHERE num<=t.num) AS CumulativeSum
FROM tab t

Answer: Since num is not unique, you may need to use row_number to get a unique number in there, then do the sum:
declare @t as table (num int)

insert into @t (num) values (1)
insert into @t (num) values (5)
insert into @t (num) values (6)
insert into @t (num) values (7)
insert into @t (num) values (2)
insert into @t (num) values (3)

;with rows as (
    select
        num,
        ROW_NUMBER() over (order by num) as Row
    from @t
)
select num, (select sum(num) from rows where row <= r.row)
from rows r

Creating a cumulative sum column


Intuition / motivation for 2 "measure" values on a bullet chart

Question: I am trying to understand a bit more about the statistical intuition behind bullet charts. This one in particular has two "measure" readouts, one is dark blue one is light blue:

For clarity, the gray shadings that we see are the qualitative measures, often depicting ordinal thresholds (above xx level = good, above yy level = great, ect). The black marker is used as a "marker" to show the value of something (though I suppose it could be repurposed to show other descriptive stats, like median)
Question
Is there an existing convention regarding how to interpret the existence of two "measure" readouts (dark blue bar, light blue bar)? I concede the point that with visualization the sky is the limit, of course we can depict whatever we want. What I'm after is: what is the motivation, generally speaking, for wanting this kind of granularity in the visualization?
Choose any of the examples: Revenue, profit, order size, new customers, satisfaction if you dont mind a basic worked out example / applied analysis to demonstrate why it would be meaningful to two colors for the inner blue bars.
Data
<code>[
  {"title":"Revenue","subtitle":"US$, in thousands","ranges":[150,225,300],"measures":[220,270],"markers":[250]},
  {"title":"Profit","subtitle":"%","ranges":[20,25,30],"measures":[21,23],"markers":[26]},
  {"title":"Order Size","subtitle":"US$, average","ranges":[350,500,600],"measures":[100,320],"markers":[550]},
  {"title":"New Customers","subtitle":"count","ranges":[1400,2000,2500],"measures":[1000,1650],"markers":[2100]},
  {"title":"Satisfaction","subtitle":"out of 5","ranges":[3.5,4.25,5],"measures":[3.2,4.7],"markers":[4.4]}
]
</code>
Answer: I don't know that there is a convention. To make sense in the bullet chart context, we should have:

dark blue value can never be greater than light blue value
each value can be interpreted against the thresholds.

The first requirement rules out things like previous-year/current-year. The second rules out part-to-whole uses, such as domestic and foreign parts.
The most reasonable interpretation I can think of is to represent a low/high range to show uncertainty or a summarization of multiple values.


Update a menu link programmatically

Question: For a migration project, we had some links on the main menu stubbed out to an external site. Now I want to update the links with their actual final path. However, I can't do this beforehand, because I don't know what the node ids of the newly-created imported nodes would be.
I want to update the menu links with node ids in my import script, but I haven't found how to do that programmatically. We would like to avoid updating them manually during the final migration.
How can I do this?
Comment: One option is to create your nodes with menu items in primary menu and delete/disable the existing menu items  at the end of the import.
Answer: I assume you know the path of the link you need to change and that's all?
If so this should work for you.
Note that I have put comments in place of any error/success reporting, which you can add if you want it.
It also assumes you know how to integrate this into the migration.
This shows the menu link saving only.
I can expand to show migrate integration although that is really a separate question.
Note: The paths used for menu items are drupal internal paths, not path aliases. To convert a path alias to an internal path you can use drupal_get_normal_path().
<code>// Variables used below. Set these to the values you need.
// The current path of the link.
$path = '';
// The menu the link is in. If you don't want to be menu specific remove the menu_name part of the SQL below.
$menu = '';
// The new path for the link.
$new_path = '';

// Get the menu link ID for the given path in the given menu.
// If you donb't know the menu it is in you can omit that part of the query.
// This also handles the case where there are multiple menu links for the same
// path.
$mlids = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :path AND menu_name = :menu", array(':path' => $path, ':menu' => $menu))->fetchCol();
if ($mlids) {
  // Loop through the matching menu items and update them.
  foreach ($mlids as $mlid) {
    if ($menu_link = menu_link_load($mlid)) {
      // Set the new menu link data.
      $menu_link['link_path'] = $new_path;
      // Save the menu link.
      if (!menu_link_save($menu_link)) {
        // There was an error saving the link.
      }
      else {
        // The link has been saved successfully.
      }
    }
    else {
      // Menu link $mlid not found.
    }
  }
}
else {
  // No menu links were found for this $path.
}
</code>
Comment: I have added a note about path aliases to the answer as well.
Comment: I would like future readers to note that this method destroyed my link if I tried to set the `$new_path` to a nodes alias. Use `drupal_get_normal_path()` to get its "true" path, which will show up in the database as `node/{nid}' but the alias will display properly in your menu.

Update a menu link programmatically


Does more MySQL user will require more CPU & memory usage?

Question: Usually I will make 1 MySQL user for every database, instead 1 MySQL user for all database.
but I just wonder.. does more MySQL user will require more CPU & memory usage?
Answer: Simply put NO..
The amount of users is not comparable to memory or cpu..
In fact, to get to the point..
It is the amount of connections ( which use MEMORY )
and
What those connections are doing ( Which use CPU )
Usually a connection/thread is capable of maximising 1 cpu core
Hope this helps :)
Answer: More Memory: Yes, though not in a relevant area.
More CPU: similar.
Multiple logins, multiple open connections e tc. - but at the end not in a range that is relevant compared to query processing and caching. I actually doubt you will be able to measure the higher use outside of lab scenarios (hundreds or thousands of users with no real load) designed to measure exactly this.


drupal_redirect_form not working with entity

Question: I have created custom submit form handler for entity using below
$form['#submit'][]='app_contact_form_submit_message_alter';

but when i used
drupal_get_messages($type = NULL);
drupal_set_message('Thanks for your feedback we will contact soon.');
drupal_redirect_form($form_state);

It redirect correctly but entity is not created.
and even if i use drupal_goto() same thing happening.
Comment: As side note, the name of the submission handler could potentially conflict with a hook implementation of `hook_form_FORMID_alter()` done for a form with ID equal to submit_message.
Answer: If you want to redirect a form submit you should use the redirect parameter:
function app_contact_form_submit_message_alter(&$form, &$form_state) {
  drupal_get_messages($type = NULL);
  drupal_set_message('Thanks for your feedback we will contact soon.');
  $form_state['redirect'] = 'node/23'; // The path you want to go
}

This will call drupal_redirect_form($form_state) byt its self, if you call it directly you are skipping the save step.
More info: https://api.drupal.org/comment/18139#comment-18139


Active Directory concurrent password policies

Question: I have an interesting problem for you.
Do you know of any method to set 2 concurrent password policies in AD ?
Here is the idea :

Policy 1 : if password length between 8 and 14 char --> impose complexity rule
Policy 2 : if password length greater than 14 char --> no complexity rule

As far as I know, by default, Windows will execute the policies sequentially.
Meaning, by default, Windows will override the first policy with the second, which is not what I'm looking for.
Thanks in advance for your comments.
Answer: You cannot have separate password policies the way you described (or the way I understood your question):

There can be only one password policy if you use the password policy settings in a GPO.

Microsoft password policies: GPO-based vs. fine-grained policies
Your best bet would be using Fine-Grained Password Policies, where you can specify different password requirements for specified users or groups:
AD DS: Fine-Grained Password Policies
AD DS Fine-Grained Password - Step-by-Step Guide


Average no. of objects in a box,when m objects are filled in n boxes.$(m>n)$

Question: The formula for the average no. of objects in a box,when m objects are filled in n boxes $(m>n)$
is given by $[m/n]$ ,if $(m/n)\in \mathbb Z$
and $[m/n]+1$,if $(m/n)\notin \mathbb Z$ .
The thing I can't understand is why in the second case did we take $[m/n]+1$ and not $[m/n]$.
Answer: This formula is incorrect.  For example, if $m=6$, $n=5$, then perhaps four boxes have one object and one box has two objects.  However $[m/n]+1=2$, so the "average no." is $2$.
The correct formula is $m/n$, with no floors, and no plus one, assuming "average" means "mean".


How to write a file to file system in Java?

Question: How can I write a file to the file system of a computer, using Java? I know how to save a file in a location relative to the location of the compiled program, but I don't know how to save the file in a specified location in the computer.
What would be the simplest way to do so?
Thanks
Comment: This is a little too general. Yes, it can be done. ... give a good effort, then return with some code & error messages.
Comment: Have you tried setting absolute paths?
Comment: The simplest way is what suits your need. =)
Answer: You need to use absolute paths to write to specific locations rather than relative locations. The mechanism depends on whether you choose to use the java.io package or java.nio package.
Also, I must add, you can get absolute paths for some well-known locations like current directory, user's home directory, etc by using System.getProperty() method.
Please have a look at the tutorials provided to get started. These are java.nio tutorials. To quickly show you, you can create an absolute path as such:
Path path = Paths.get("C:\\home\\joe\\foo");

Answer: Look at this tutorial to give you an idea about how to work with files in Java.


How to create an rray of composites strings

Question: Hi everyone: I have a collection of 50 strings that represent comments in a text file where each line represents a separate comment with different sentences .
Each string is a user review of a product, and each string or review has several several sentences.
How could I to create an array with these strings using Python?
Example of reviews:
Review 1.  "I was disapointed with the product. The quality was reality bad and the price was not fair.  Never in my life I'll buy again this brand.
Review 2. "I'm really happy with this product.  It's all what i desired.  Thanks brand J"
.... and so far.
Desired Results:

[('disappointed', 'product'), ('quality', 'really', 'bad', 'price', 'fair')]
[('happy', 'product'), ('all', 'desired'), ('thanks', 'brand')]
...

I want each processed comment in a separate line to save it in a csv file
Comment: And what do you want the output to look like?
Comment: what does your collection of strings look like?
Comment: My collection of comments is a txt file and each line means a separate review with different sentences.  After apply stopwords I want a result like this: 1. [('disappointed', 'product'), ('quality', 'really', 'bad', 'price', 'fair')]
2. [('happy', 'product'), ('all', 'desired'), ('thanks', 'brand')]
3. ...  I want each processed comment in a separate line to save it in a csv file.
Comment: sorry edited your question so i could understand it better, plus you gave more needed information but didnt put it in the question.
Answer: One of my first projects was similar to this. I believe your asking for help in getting the text file lines as an array.
To open the file for reading:
file = open("/path/to/file", "r")
I would then split on spaces so:
for line in file:
      print line.split(' ')

this would give you an array of words from each line in the txt file.
Then use the csv module in python to input into a csv file.
References:

Python the Hard Way - Opening and Closting Files
split() function
CSV Module


Add a relationship to logged in user, not content author, on content view?

Question: I want to filter my content view by a field on the logged in user (the content type has that same field). I could implement hook_query_alter and add add a where condition with the field from $global user, but is there a way to do this out of the box though the UI?
Comment: `I want to filter my content view by a field on the logged in user` ??? Not sure if I understand this correctly. So the logged in user has field x, which containts the word `hello` and you want to the filter the view by the word `hello`?
Comment: @NoSssweat Edited question.
Comment: I still don't get it.
Comment: The general problem is getting to fields attached to User (specifically the logged-in user) from a content view. Does this make sense?

In my specific case, I have a view that shows pieces of content of a certain content type. On that content type there is a certain field. That same field is also attached to Users. I want to filter the view to only those content pieces that have the same setting as the current user.
Comment: ok I get it now. humm yea I don't think there is a way with just the UI.
Answer: There is no way to accomplish this via UI. At least not if the User field may contain multiple values.
In the example below 'field_test' is a List(text) field w/ select widget (unlimited values allowed for user account). When the same field is added to Content type - I set it to allow for single values.
The code will take in consideration multiple values from User field and add WHERE  clause to the View that shows all nodes of a Content type.
WHERE clause filters out all nodes that have 'field_test' set to anything other than what currently logged in user has set in 'field_test' on their own account.
/**
* Implements hook_views_query_alter().
*/
function MYMODULE_views_query_alter(&$view, &$query) {
  // 'test_related_field' -> view's machine_name
  if ($view->name == 'test_related_field') {
    global $user;
    $user = user_load($user->uid);

    // 'field_test' -> field that is shared between user accounts ans content type
    $user_field = field_get_items('user', $user, 'field_test');
    if($user_field) {
        $query->ensure_table("field_data_field_test");
        // create query that processes multiple values of User 'field_test'
        $db_or = db_or();
        foreach ($user_field as $item){
            $db_or->condition('field_data_field_test.field_test_value', $item, 'IN');
        }
        $query->add_where('test_field_group', $db_or);
    }
    // use dpm() to see added WHERE clause
    //dpm($query);
  }
}

UPDATE:
If User field and Content Type field are allowed to have only single values then you can use UI for filtering view's results.

add shared field as Contextual Filter
Provide Default value for the field -> select PHP Code
enter the following code in the box

global $user;
$user_fields = user_load($user->uid);
$test_field = $user_fields->field_test['und'][0]['value'];
return $test_field;
Comment: Hmm. Thanks, but if I have to use php code at all I think I should put it in a custom module.
Comment: Say the field doesn't allow multiples?
Comment: it works for single and multiple values. The code simply loads the field values and loops through values array. Then according to each value -  adds appropriate WHERE clause. If there is only one value or the field allows for only one value, then only one WHERE clause will be added to the View query.
Comment: Right. I was still wondering about the UI though. You have a qualifier: "There is no way to accomplish this via UI. At least not if the User field may contain multiple values."
Comment: right, check the updated answer for UI method
Comment: yes you should. Since you asked about UI method - adding that snippet thru Views UI I think qualifies for it. It is definitely not the best practice and not maintainable, but available as an option.
Answer: Don't think there is a way. For the record, here's some starter code.
/**
* Implements hook_views_query_alter().
*/
function MYMODULE_views_query_alter(&$view, &$query) {
  if ($view->name == VIEWNAME) {
    global $user;
    $user = user_load($user->uid);
    $user_field = field_get_items('user', $user, 'field_NAMEOFFIELD');
    if ($user_field) {
      // only care about the first result for now
      $user_field = $user_field[0]['value'];
    }
    $query->ensure_table("TABLENAME");
    $query->add_where(0, "TABLENAME.NAMEOFFIELD_value", $user_field);
  }
}


Como criar esse tipo de relacionamento usando as Models Django

Question: Após ver uma modelagem que eu deveria implementar no Django, fiquei um pouco confuso e vou explicar o que tentei fazer e o que me foi enviado.
A imagem a seguir é o relacionamento que devo implementar em Django

O que tentei fazer foi:
class Contato(models.Model):
    pessoa = models.OneToOneField(Pessoa)

class Pessoa(models.Model):
    contato = models.ForeignKey(Contato)

Porém isso não funciona, ambas as classes estão no mesmo arquivo. Li a documentação de ManyToManyField, OneToOneField e ForeignKey, mas o que me deixa confuso é o modelo querer a varialvel nas duas classes, em modelos anteriores que vi existia essa mesma relação, porém a varialvel só existia em uma das classes. Qual a maneira correta de implementar isso?
Answer: Entendo que uma pessoa pode ter um ou mais contatos, certo?
Dê uma olhada abaixo:
from django.db import models

class Pessoa(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=40)

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Contato(models.Model):
    contato = models.CharField(max_length=50)
    pessoa = models.ForeignKey(Pessoa, on_delete=models.CASCADE)

    def __str__(self):
        return self.contato

    class Meta:
        ordering = ['pessoa']

Espero que ajude.
Comment: Olá, Paulo, depois de realizar alguns testes eu já tinha chegado na mesma conclusão que você, então vou considerar sua resposta como a correta visto que a implementação foi parecida. Obrigado.


Como fazer um redirecionamento via .htaccess de um subdomínio para o domínio principal?

Question: Tenho um domínio (www.dominio.com.br) e uma subpasta (www.dominio.com.br/pasta) e gostaria de redirecionar todos os links dessa pasta para o domínio.
Exemplos:
www.dominio.com.br/pasta
www.dominio.com.br/pasta/noticia/nome-da-noticia
www.dominio.com.br/pasta/contato.php
www.dominio.com.br/pasta/tag/nome-da-tag
www.dominio.com.br/pasta/trabalhos.php
Todos os links requisitados da "pasta" com e sem extensão, quero redirecioná-los para o domínio principal.
Como faço? E aonde coloco o arquivo .htaccess?
Answer: Crie um diretório chamado "pasta" no DocumentRoot onde estão os arquivos páginas do www.dominio.com.br ("/var/www/html", "/opt/site/" etc) e dentro dele crie o arquivo ".htaccess" com o seguinte conteúdo:
<IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteBase /
    RewriteRule ^(.*)$ http://www.dominio.com.br/$1

</IfModule>

Neste caso TUDO, o ^(.*)$ no REGEX, que chega em http://www.dominio.com.br/pasta/ será redirecionado para http://www.dominio.com.br/; o $1 no final é justamente o resto da URL ("index.html", "admin.php", "post/2018/03/26" etc).
Comment: Remova o "$1" do final, é ele que complementa a URL. Tinha entendido que você queria também traduzir os acessos.
Comment: Dessa forma fiz um teste assim:

www.dominio.com.br/pasta/subpasta

redirecionou o endereço para:

www.dominio.com.br/subpasta
Comment: Então funcionou?
Comment: Não! Era pra ter ido pra home do site.
Comment: Deu certo! Muito obrigada.


HttpResponseMessage.Content.ReadAsStringAsync don't deserialize JSON when it come from CreateErrorResponse

Question: if i return from my selfhosted webapi
Request.CreateResponse(HttpStatusCode.OK, "YAY");

everything is fine.. so i can read it like that:
var responseStr = await Client.Content.ReadAsAsync<string>();
and then make something like "MessageBox.Show(responseStr);

if i return
Request.CreateErrorResponse(HttpStatusCode.NotFound, "something went wrong!");

and i read it out the same way or even with(doesn't matter how):
Client.Content.ReadAsStringAsync();

the string is not deserialized and i get an error when trying to parse / read as string.
if i read it as object .. it's fine.. but i can't perform object.ToString();
i get errors..
why? and how to fix it?
Comment: Please explain _"the string is not deserialized and i get an error when trying to parse / read as string"_. Preferably show the code that does this and the exact exception you get. I think the error response doesn't contain a body, so `Content.Read...()` won't return anything.
Comment: i mean not deserialized from json to string
Comment: so if that is true that it doesn't contain a body, then CreateErrorResponse isn't creating a response body?
Comment: oh the problem was that i was returning the HttpStatusCode.NotFound .. that seams to not create a body. you helped me out thank you
Answer: I found that there were extra '\' and '"' in the returned JSON.
So before I serialize back to an object, I needed to remove the extra chars.
e.g.
string jsonString = httpResponseMessage.Content.ReadAsStringAsync()
                                               .Result
                                               .Replace("\\", "")
                                               .Trim(new char[1] { '"' });

List<VwAisItemMaster> vwAisItemMasterList = JsonConvert.DeserializeObject<List<VwAisItemMaster>>(jsonString);

Comment: Thanks, you saved me
Answer: The better solution is just to fix the issue when creating the response in the webapi method.
Note the type in the CreateResponse method.
IList<VwItemMaster> vwItemMasterList = this.itemMastersGetByUpc(unitOfWork, upc);

HttpResponseMessage httpResponseMessage = this.Request.CreateResponse<IList<VwItemMaster>>(HttpStatusCode.OK, vwItemMasterList);

httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");


In Powershell, how to I extract only the 7-digit numbers from email subject-lines?

Question: Here is my Powershell code :
$outlook = new-object -com Outlook.Application
$sentMail = $outlook.Session.GetDefaultFolder(6)
$sentMail.Items | % { $_.TaskSubject | Select-String -Pattern '\d{7}' }

So this will print all the email subject lines containing a 7-digit string. However, I want to only print the 7-digit string in these lines.
I should use match , I believe. But match returns true/false ? What is the way to go about it? thanks
Answer: Try this
$sentMail.Items | % { $RESULT=[Regex]::Match($_.TaskSubject ,"\d{7}"); if($RESULT.Success){$RESULT.Value} }

Comment: I've changed the script to only show the one's that matched.
Comment: this works, but when it outputs it then it has a bunch of extra new-line characters so it takes long to shoot them out. any way to keep them all in one-quick line?  thanks so much !!
Answer: I am answering myself, because I just figured one way to do so:
We need another pipe ( | ) , and in this we use the match command:  like so -
$sentMail.Items | % { $_.TaskSubject | Select-String -Pattern '\d{7}'
                                     | % {([string]$_) -match '\d{7}' | out-null;                                     $matches) }

This prints out :
Name                   Value
-----                  -----
0                      8293798
0                      8233798
0                      1223798
..etc etc..

But this is 2 columns, I'd want just 1 column


Jquery Datatable -Is it possible to bind href property of link with razor syntax dynamically

Question: I am using Jquery Datatables plugin. I am showing list of employee details with an provision to edit using the above plugin. My questioon is
Is it possible to set href property of the edit link dynamically along with razor syntax of MVC ?
If not what is the alternate solution to navigate to edit page ?
HTML markup is
        table = $("#dataTableMenuRole").dataTable({
        "ajax": {
            "url": "@Url.Action("LoadGridView", "MenuSettings")",
            "method": "POST",
            "dataType": "json",
            "data": function (d) {
                d.roleId = $("#ddlRoles").val()
            }
        },
        columns: [
            { "data": "MenuName" },
            { "data": "CanAdd" },
            { "data": "CanEdit" },
            { "data": "CanDelete" },
            { "data": "CanView" },
            { "data": "MenuRoleId" }

        ],
        "bProcessing": true,
        "aoColumnDefs": [{
            "targets": 5,
            "bSortable": false,
            "render": function (data, type, full, meta) {
                return ''+
               //Here data cannot be assigned as shown
                        ''+
                    ''
            }

        }]

    });

Answer: You need to render an HTML link like this (apologies for any quote errors!):
return '';

The full parameter is the full datasource for the current row, so assuming MenuRoleId is the Id you want to use, you access it using full[5]
You could use Razor syntax to create the url, but it means that the datatables javascript code would need to be in View, which is not ideal.


Printing File list

Question: I've got some problems trying to print the list of available directories.
Here's my code with comments:
File f = new File(System.getProperty("user.home"));
System.out.println(f.list().toString()); //the output here is absolutely incorrect

This is the output
[Ljava.lang.String;@1540e19d

Comment: define "absolutely incorrect" for us please.
Comment: You're getting an array of String. Iterate through that array, or print it out with `System.out.println(java.util.Arrays.toString(f.list()));`
Comment: No, f.list() returns the array. What you're seeing is the typical `toString()` output of any array of String. `[` means array. Then you see the class name for String, then the array's hashcode.
Comment: Ok. It's [Ljava.lang.String;@1540e19d
Comment: Ok. As I understand f.list().toString returns an array of strings. But what does the f.list() return?
Answer: Your output, [Ljava.lang.String;@1540e19d, is the typical toString() output of any array of String. [ means array. Then you see the class name for String, then the array's hashcode.
You're getting an array of String. Iterate through that array in a for loop
for (String fileName : f.list()) {
    System.out.println(fileName);
}

or print it out with
System.out.println(java.util.Arrays.toString(f.list()));

The key is to use the File API as it will tell you what the File#list() will return, here an array of String.
Comment: @MaximGotovchits: the key is to use the API as it will tell you what the `File#list()` will return, here an array of String.
Answer: To find directories, you need to filter the list. listFiles() is a better method to use as it returns a list of File objects rather than String, this is ultimately more powerful and allows things like testing if the "file" is a directory which I believe you're trying to do.
File home = new File(System.getProperty("user.home"));

for (File file : home.listFiles()) {
    if (file.isDirectory()) {
        System.out.println(file);
    }
}

Alternatively you can use a FileFilter in listFiles(), this will return a primitive array of File, which you can change to a List with Arrays.asList
List<File> directories = Arrays.asList(home.listFiles(new FileFilter() {

    @Override
    public boolean accept(File pathname) {
        return pathname.isDirectory();
    }
}));

Regarding the issue of the "incorrect" output [Ljava.lang.String;@1540e19d, this is normal for printing out primitive arrays, unlike Collection types which typically have a nice toString() implemention. You can use the utility method java.util.Arrays.toString to "pretty print" each element.
If you require a recursive listing I'd consider using the newer java.nio.Files.walk() functionality rather than writing your own recursive method.
List<Path> paths = Files.walk(home.toPath()).filter(new Predicate<Path>() {
            @Override
            public boolean test(Path path) {
                return path.toFile().isDirectory();
            }
        }).collect(Collectors.toList());

Or more concisely with Java 8 closures.
List<Path> paths = Files.walk(home.toPath()).filter((path) -> path.toFile().isDirectory()).collect(Collectors.toList());

Comment: Best answer of the bunch. 1+
Answer: this ll print number files as well as list the file in current directory :
File f = new File(System.getProperty("user.home"));
System.out.println(f.list().length);

for (String fileName : f.list()) {
    System.out.println(fileName);
}

if you want to list files with subdirectory and it's file then :
public void listFiles( String path ) {

        File root = new File( path );
        File[] list = root.listFiles();

        for ( File f : list ) {
            if ( f.isDirectory() ) { // check that if current instance is file or directory
                listFiles( f.getAbsolutePath() );
                System.out.println( "Dir:" + f.getAbsoluteFile() );
            }
            else {
                System.out.println( "File:" + f.getAbsoluteFile() );
            }
        }
    }

    public static void main(String[] args) {
        Test t = new Test();
        fw.listFiles("c:\\" );
    }

Answer: Do it this way
File f = new File(System.getProperty("user.home"));
  String tok[]=f.list();
  for(String s:tok){
      System.out.println(s);
  }

Alternatively you can use java.util.Arrays to convert String array returned by f.list() to string as:
Arrays.toString(f.list());

Printing File list


The view is not filtering the duplicate nodes

Question: i have a view which is not filtering the duplicated nodes and i tried couple of solutions but it looks like they are not working.
The code I am using is the following.
<code>function mymodule_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'basicnews') {
    $unique_nids = $new_results = array();

    // Loop through results and filter out duplicate results.
    foreach ($view->result as $index => $result) {
      if (!in_array($result->nid, $unique_nids)) {
        $unique_nids[] = $result->nid;
        $new_results[] = $result;
      }

      // Replace $view->result with new array. Apparently views requires sequentially keyed
      // array of results instead of skipping keys (e.g. 0, 2, 4, etc), so we can't just
      // unset the duplicates.
      $view->result = $new_results;
    }
  }
}
</code>
Is there any patch or work-around for this issue?
Answer: You can handle most duplicate node issues using Views Aggregation options.
Go to advanced in the view and select "Use Aggregation"
Then in the fields area, set the aggregation settings.  Generally, you just want the group together option with Entity ID as the group column.  Sometimes you have to play around with other settings as well.


APC minimal shm size

Question: What is the minimal amount of shm Space APC needs to operate properly? I'm currently running a Wordpress blog on a VPS based on virtuozzo and I can't set kernel shm to anything above 32 mb. Is there any way of telling APC to use "normal" memory instead of shared one (I've got plenty of ram...)
My current apc.ini looks like this, yet apc tells met that it's using just 30 MB (1 Segment(s) with 30.0 MBytes (mmap memory, pthread mutex locking)):
extension = apc.so
apc.enabled = 1
apc.shm_segments = 15
apc.num_files_hint = 2700
apc.user_entries_hint = 2700
apc.ttl = 7200
apc.user_ttl = 3600
apc.gc_ttl = 600
apc.cache_by_default = 1
apc.max_file_size = 2M
apc.stat = 1

Answer: Use the files apc.php from the APC package to check how APC use memory.
Increase it until APC have 20% free spare memory.
A single Wordpress with some plugins can require more than 40M.
Answer: There may be a limit set on how large a shared memory segment you can request.
However, you can add a number of such segments for APC to use in the configuration: apc.shm_segments=2
http://php.net/manual/en/apc.configuration.php#ini.apc.shm-segments
Comment: That sadly doesn't seem to work, see my config from above, APC still reports 1 segment with 30 MB....
Comment: Did you actually put 15 in there, because that would try to allocate 450 megabytes. Try with 2.  Also, why do you want so much? I'm running a Wordpress install, and there is less than 20mb in APC for the PHP files to be cached.
Comment: Well I tried it with different values, also with those fifteen, out of anger as it was not working. I wanted more because I didn't get the expected performance boost with just 30mb, but as it turned out, more didn't help either.
Answer: Found the solution myself:
By default apc now uses mmap for shared memory. In theory, mmap should not be bound to the maximum shm size by the kernel, but it seems it is, at least in shared server environments like virtuozzo. Also mmap ignores apc.shm_segments because it won't create multiple anonymous files to map into memory without a mask, so unless you also set apc.mmap_file_mask this seems to be useless.
Another way is to recompile apc using --disable-apc-mmap and use IPC shared memory instead!

APC minimal shm size


transactional replication using script

Question: I am able to configure transactional replication using SSMS and it works properly. But i want to configure it using script so that i use it from my c#/vb application.
Is there any way to do that?
Answer: DECLARE @returncode int
EXEC @returncode = xp_cmdshell 'dtexec /f "C:\thePackage.dtsx"'

Answer: Check out sp_addpublication, sp_addarticle, and sp_addsubscription in BOL.
Answer: If you complete all the step of transactional replication using SSMS then it's not complicated to do with the script.
Just carefully observe that when you configure distribution, publication and subscription SSMS gives you the option to generate script in every step.
You can use that generated script.
But only difference is when you add articles to publication. You can use the following code to add article
declare @name nvarchar(50)
declare curname cursor for
select name from sysobjects where type = 'U'
open curname
fetch next from curname into @name
while @@FETCH_STATUS = 0
begin
if exists(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name AND TABLE_SCHEMA = 'dbo')
begin
exec sp_addarticle
@publication = N'publication_name', @article = @name, @source_owner = N'dbo',
@source_object = @name, @type = N'logbased', @description = null, @creation_script = null,
@pre_creation_cmd = N'drop', @schema_option = 0x000000000803509F,
@identityrangemanagementoption = N'manual', @destination_table = @name,
@destination_owner = N'dbo', @vertical_partition = N''
end
fetch next from curname into @name
end
close curname
deallocate curname

Or, you can see https://hasibarnab.wordpress.com/category/sql-server/replication/
Comment: [sysname](http://technet.microsoft.com/en-us/library/ms191240%28v=sql.105%29.aspx) is a better type for @name. Your script would not work for names longer than 50 characters. sysname is the internal type of object names and equivalent to nvarchar(128).

transactional replication using script


Is the Representation Matrix of Every Quantum Channel Diagonalizable?

Question: Given a quantum map with input and output states of equal (finite) dimension---that is, a completely positive trace-preserving linear map $\Phi:\mathbb C^{n\times n}\to\mathbb C^{n\times n}$---is the matrix $\hat\Phi\in\mathbb C^{n^2\times n^2}$ which one obtains from the action of $\Phi$ on a vectorized state $\operatorname{vec}(\rho)$ (i.e. $\hat\Phi$ satisfies $\operatorname{vec}(\Phi(\rho))=\hat\Phi\operatorname{vec}(\rho)$) always diagonalizable?
While this question is trivial if one asks about the Choi matrix $C(\Phi)$ of $\Phi$ instead -- which is always positive semi-definite because $\Phi$ is completely positive, hence $C(\Phi)$ is even unitarily diagonalizable -- this may change if one chooses a different arrangement of the elements of $\Phi$. Note that the matrix $\hat\Phi$ differs from the Choi matrix as follows:
$$
\langle k\otimes l|\hat\Phi |i\otimes j\rangle=\langle k\otimes i|C(\Phi)|l\otimes j\rangle
$$
One way to see this is directly via
$$
\hat\Phi=\sum_{i,j,k,l=1}^n\big\langle l,\Phi(|i\rangle\langle j|)k\big\rangle\ |k\rangle\langle j|\otimes|l\rangle\langle i|\ .\tag{1}
$$
The motivation here is of course the fact that the spectrum of $\Phi$ and $\hat\Phi$ coincide, whereas the spectrum of $C(\Phi)$ in general differs from that.
As stated before, the question -- most relevant for spectral analysis -- now is:

If $\Phi$ is a quantum channel, is $\hat\Phi$ always diagonalizable?
Answer: The answer is no, and we give some counter-examples below: two in $2$ and one in $3$ and more dimensions. References for the two-dimensional examples are this paper and this paper, and the three-dimensional example also appears in a slightly different form in these old lecture notes of M. Wolf (Example 8.1). However, in my opinion, these examples are rather difficult to find if you're not already familiar with these references---hence why I decided to create this post.
Interestingly, the second paper linked above shows that---while not all channels can be diagonalized---every channel can be approximated by diagonalizable channels arbitrarily well.
1. The Qubit Case
1a. Example 1
First we will construct some examples based on the Pauli transfer matrix, which is just the representation matrix with respect to the orthonormal basis $\{\frac1{\sqrt2}{\bf1},\frac1{\sqrt2}\sigma_x,\frac1{\sqrt2}\sigma_y,\frac1{\sqrt2}\sigma_z  \}$. The idea here is that the Pauli transfer matrix of a unital (i.e. identity-preserving) qubit channel is always of the form
$$
\begin{pmatrix}
1&0\\0&\Lambda
\end{pmatrix}\tag{1}
$$
for some $\Lambda\in\mathbb R^{3\times 3}$. Interestingly, the Fujiwara-Algoet conditions---which in the unital case are necessary and sufficient conditions on the singular values of $\Lambda$ such that (1) gives rise to a quantum channel---show that for every $\Lambda\in\mathbb R^{3\times 3}$ there exists $c>0$ such that the block-diagonal matrix $1\oplus c\Lambda$ corresponds to a unital channel. This gives rise to a simple machinery to construct non-diagonalizable channels:

Starting from your favorite non-diagonalizable real $3\times 3$-matrix $\Lambda$, the channel with Pauli transfer matrix $1\oplus c\Lambda$ (for all $c$ "small enough") is not diagonalizable.

To show this construction in action, one of the simplest examples then is the channel with Pauli transfer matrix
$$
\begin{pmatrix}
1&0&0&0\\0&0&1/2&0\\0&0&0&1/2\\0&0&0&0
\end{pmatrix}
$$
is obviously not diagonalizable. Complete positivity of the corresponding (trace-preserving) linear map
$$
\Phi\begin{pmatrix}a_{11}&a_{12}\\a_{21}&a_{22}\end{pmatrix}:=
\begin{pmatrix}
 \frac{a_{11}+a_{22}}{2} & \frac{1}{4} i (-a_{11}+a_{12}-a_{21}+a_{22}) \\
 \frac{1}{4} i (a_{11}+a_{12}-a_{21}-a_{22}) & \frac{a_{11}+a_{22}}{2} \end{pmatrix}
$$
is due to the fact that its Choi matrix
$$
\frac14\begin{pmatrix}
 2 & -i & 0 & i \\
 i & 2 & i & 0 \\
 0 & -i & 2 & i \\
 -i & 0 & -i & 2
\end{pmatrix}
$$
has eigenvalues $1$, $1/2$ (2-fold), and $0$.
Geometrically, the effect of this three-dimensional Jordan block is that

first, $\Phi$ maps the Bloch ball to a smaller circle in the $y-z-$plane,
a second application of $\Phi$ yields (part of) the $z$-axis,
and applying $\Phi$ a third (and more) times always yields the Bloch vector zero.

This is readily verified by the action of $\Phi$ on any Bloch vector:
$
\Phi:(x,y,z)^\top\mapsto (y/2,z/2,0)^\top
$.
In contrast, if the eigenvalue $0$ had geometric multiplicity three (while the identity matrix stays the fixed point of $\Phi$) it would not take three, but only one application of $\Phi$ to map the whole Bloch ball to the origin.
1b. Example 2 (minimal Kraus rank)
Next, two examples where we focus more on the Kraus rank, and we try to make it as small as possible.
The first one is again a unital channel, now of Kraus rank 2 which has appeared in the literature before; its Pauli transfer matrix reads
$$
\begin{pmatrix}
1&0&0&0\\0&0&0&-1\\0&0&0&0\\0&0&0&0
\end{pmatrix}\,,
$$
and it can be written as dephasing followed by the unitary channel generated by
$$
\frac1{\sqrt2}\begin{pmatrix}-1&1\\1&1\end{pmatrix}\,.
$$
To show that diagonalizability can also fail for non-unital channels consider $\Phi:\mathbb C^{2\times 2}\to\mathbb C^{2\times 2}$ defined via
$$
\Phi\begin{pmatrix}a_{11}&a_{12}\\a_{21}&a_{22}\end{pmatrix}:=
\begin{pmatrix}
a_{11}+\frac23a_{22}&\frac13a_{12}+\frac13a_{22}\\
\frac13a_{21}+\frac13a_{22}&\frac13a_{22}
\end{pmatrix}\,.
$$
Again, $\Phi$ is obviously trace preserving and $\Phi$ is completely positive because its Choi matrix
$$
C(\Phi)=\begin{pmatrix}
1&0&0&1/3\\
0&0&0&0\\
0&0&2/3&1/3\\
1/3&0&1/3&1/3
\end{pmatrix}
$$
has three positive ($\approx 1.177,0.782,0.040$) and one zero eigenvalue.
Even better, the representation matrix of $\Phi$ is already in upper triangular form so we can read off that it has a simple eigenvalue $1$ and a three-fold eigenvalue $1/3$:
$$
\hat\Phi=\begin{pmatrix}
1&0&0&2/3\\
0&1/3&0&1/3\\
0&0&1/3&1/3\\
0&0&0&1/3
\end{pmatrix}
$$
This triangular form, however, already lets one suspect that the geometric multiplicity of the eigenvalue $1/3$ is less than $3$. And indeed, its Jordan normal form reads $\hat\Phi=SJS^{-1}$ with
$$
J=\begin{pmatrix}
 1 & 0 & 0 & 0 \\
 0 & \frac{1}{3} & 0 & 0 \\
 0 & 0 & \frac{1}{3} & 1 \\
 0 & 0 & 0 & \frac{1}{3}
\end{pmatrix}\quad\text{ and }\quad S=
\begin{pmatrix}
 1 & 0 & 0 & -1 \\
 0 & 0 & \frac{1}{3} & 0 \\
 0 & 1 & \frac{1}{3} & 0 \\
 0 & 0 & 0 & 1
\end{pmatrix}\,.
$$
Note that this can be used to construct a family of non-diagonalizable channels: simply replace the last column of $\hat\Phi$ by $(2/3,b,b^*,1/3)^T$ for any $b\in\mathbb C\setminus\{0\}$. Then $\hat\Phi$ is not diagonalizable, and $\Phi$ is a channel (completely positive) if and only if $|b|\leq\frac{2\sqrt3}9$.
In this limiting case we obtain the in some sense simplest possible example of a non-diagonalizable channel:
$$
\Phi\begin{pmatrix}a_{11}&a_{12}\\a_{21}&a_{22}\end{pmatrix}:=
\begin{pmatrix}
 a_{11}+\frac{2 a_{22}}{3} & \frac{1}{9} \left(3 a_{12}+2 \sqrt{3} a_{22}\right) \\
 \frac{1}{9} \left(3 a_{21}+2 \sqrt{3} a_{22}\right) & \frac{a_{22}}{3}
\end{pmatrix}
$$
is a channel with Kraus rank 2 (a choice of Kraus operators is
$$
K_1=\sqrt{\frac{3 +\sqrt3}{18}}\begin{pmatrix} \sqrt3&\sqrt3-1\\0&1 \end{pmatrix}\quad\text{ and }\quad K_2=\sqrt{\frac{3-\sqrt3}{18}}\begin{pmatrix} -\sqrt3&1+\sqrt3\\0&1 \end{pmatrix}
$$
as is readily verified)
but $\hat\Phi$ is not diagonalizable per our previous considerations.
2. Higher Dimensions: Classical Channels
Consider the map $\Phi:\mathbb C^{3\times 3}\to\mathbb C^{3\times 3}$ defined via
$$
\Phi\begin{pmatrix}
a_{11}&a_{12}&a_{13}\\
a_{21}&a_{22}&a_{23}\\
a_{31}&a_{32}&a_{33}
\end{pmatrix}:=
\begin{pmatrix}
a_{11}+\frac23a_{22}+\frac13a_{33}&0&0\\
0&\frac13a_{22}+\frac13a_{33}&0\\
0&0&\frac13a_{33}
\end{pmatrix}
$$
so $\Phi$ is even a classical channel, hence the Choi matrix of $\Phi$ is already diagonal.
Using equation (1) it is easy to see that
$$
\hat\Phi=\begin{pmatrix}
1&0&0&0&\frac23&0&0&0&\frac13 \\
0&0&0&0&0&0&0&0&0 \\
0&0&0&0&0&0&0&0&0 \\
0&0&0&0&0&0&0&0&0 \\
0&0&0&0&\frac13&0&0&0&\frac13 \\
0&0&0&0&0&0&0&0&0 \\
0&0&0&0&0&0&0&0&0 \\
0&0&0&0&0&0&0&0&0 \\
0&0&0&0&0&0&0&0&\frac13
\end{pmatrix}\simeq
\frac13\begin{pmatrix}
3&2&1\\
0&1&1\\
0&0&1
\end{pmatrix}\oplus 0_6\ .
$$
Now the non-trivial part of $\hat\Phi$ (which we will denote by $D_\Phi$ for "diagonal action") is not diagonalizable; indeed the Jordan normal form of $D_\Phi$ reads $SJS^{-1}$ where
$$
J=\begin{pmatrix}
3&0&0\\
0&1&1\\
0&0&1
\end{pmatrix}\quad\text{ and }\quad S=\begin{pmatrix}
1&-1&-1\\
0&1&0\\
0&0&1
\end{pmatrix}\quad\text{ so }\quad
S^{-1}=\begin{pmatrix}
1&1&1\\
0&1&0\\
0&0&1
\end{pmatrix}\,.
$$
For more examples of non-diagonalizable stochastic matrices refer, e.g., to this math.SE answer.
Moreover, the structure of this counterexample generalizes to any dimension $n\geq 3$.

Addendum: if trace-preservation is dropped, finding a counterexample is a lot easier. Indeed, the—obviously non-diagonalizable—matrix
$$
\begin{pmatrix}0&0&0&1\\0&0&0&0\\0&0&0&0\\0&0&0&0\end{pmatrix}
$$
is the superoperator corresponding to the map
$$
\Phi(X):=\begin{pmatrix}x_{22}&0\\0&0\end{pmatrix}\,,
$$
and $\Phi$ is completely positive as $\{|0\rangle\langle 1|\}$ is a set of Kraus operators of $\Phi$. However, $\Phi$ is obviously not trace-preserving.


Expected value of $\max(a, b)$

Question: What is the expected value of $\max(a, b)$ where $a, b$ are uniformly distributed from $[0,1]$?

My intuition for this question was to say $E[a] = 0.5$. This means there is probability $0.5$ that $b > a$. If $b > a$ we can say $E[b] = 0.75$ where $b$ would now be the max. Given this, my calculation for $\max(a, b)$ is $0.5(0.5) + 0.5(0.75) = 0.625$, but this does not appear to be the correct answer. Why is this approach wrong?
Comment: You also need to consider what happens in the cases $b>a$ or $ba$ is more likely when $a$ is small, while $bb) ~{\large\gneq}~ \mathsf E(a)$ .
Answer:
My intuition for this question was to say E[a]=0.5. This means there is probability 0.5 that b>a.

Yes...ish.  It is by symmetry that we may say:  $\mathsf P(a>b)=\mathsf P(b>a)$ when the variables are independent and identically distributed.

If b>a we can say E[b]=0.75 where b would now be the max. Given this, my calculation for max(a,b) is 0.5(0.5)+0.5(0.75)=0.625, but this does not appear to be the correct answer. Why is this approach wrong?

Well, now, by the Law of Total Expectation we do have:
$\qquad\begin{align}\mathsf E(\max(a,b)) &=\mathsf E(a\mid a>b)~\mathsf P(a>b)+\mathsf E(b\mid a\leqslant b)~\mathsf P(a\leqslant b)\\&=\tfrac 12\big(\mathsf E(a\mid a>b)+\mathsf E(b\mid b \geqslant a)\big)\end{align}$
However, we would not expect the conditional value of $a$ to be $1/2$ when given $a>b$.  Indeed, knowing that $a>b$ should raise our expectations for $a$.
$\qquad\mathsf E(a\mid a>b)\gneq \mathsf E(a)$
Likewise we cannot say $\mathsf E(b\mid b>a)=0.75$.   Rather it is that $\mathsf E(b\mid b>0.5)=0.75$, which is not the same thing at all.
Indeed, by the symmetry of the random variables:
$\qquad\mathsf E(a\mid a>b)=\mathsf E(b\mid b>a)$

How do we figure how much to raise our expectation under the condition of largeness?  Integration is one way.
$\displaystyle\qquad\mathsf E(a\mid{a>b}) = \dfrac{\int_0^1\int_0^a a\, \mathrm d b\,\mathrm d a}{\mathsf P(a>b)}$

Intuitively
Consider the expected placement for the maximum and minimum of $a,b$ on the $[0,1]$ interval.   By symmetry and unbiasedness of the uniform distributions, these points should be expected to partition the interval into three equal segments.
So...

Expected value of $\max(a, b)$


Given a recurrence relation for the coefficients of an analytic function $f$ find a functional equation for which $f$ is a solution

Question: Let $f(z)=\sum\limits_{n=0}^\infty a_nz^n$ be an analytic function on some open set $U\subset\mathbb{C}$ and assume that the coefficients of the above series are all positive and satisfy
$$\frac{1}{a_n}=\frac{b}{a_{n-1}}+\frac{c}{a_{n-2}},\quad n\geq 2,$$
where $b$ and $c$ are some constants. Is it then possible to find some functional (differential) equation for which $f$ is a solution?
Comment: $b_n:=\frac{1}{a_n}$ satisfies a Fibonacci-type recursion. Therefore you get a closed formula for $a_n$. With that you can test on a functional equation.
Answer: If $u_n = 1/a_n$, we have
$$ u_n = b u_{n-1} + c u_{n-2}$$
Let's suppose the quadratic $r^2 = b r + c$ has two distinct roots $r_{+}$ and $r_{-}$.  Then the solutions
of this recurrence are
$$ u_n = A_+  r_+^n + A_- r_-^n$$
for arbitrary constants $A_+$, $A_-$.  Thus
$$ a_n = 1/(A_+ r_+^n + A_- r_-^n) $$
This has ordinary generating function
$$ f(z) = \sum_{n=0}^\infty a_n z^n = \sum_{n=0}^\infty \frac{z^n}{A_+ r_+^n + A_- r_-^n} $$
which does satisfy a functional equation
$$A_+ f(r_+z) + A_- f(r_- z) = \sum_{n=0}^\infty z^n = \frac{1}{1-z} $$
Note that the coefficients $A_+$ and $A_-$ of this
functional equation can be obtained from $a_0$, $a_1$, $r_-$ and $r_+$:
$$ \eqalign{A_+ &= \frac{a_0 - r_- a_1}{a_0 a_1 (r_+-r_-)}\cr
A_- &= \frac{a_0 - r_+ a_1}{a_0 a_1 (r_- - r_+)}}$$
Comment: Thank you! Is it possible to find such an equation in case the reccurence is given by $\frac{1}{a_n}=\frac{b+cn}{a_{n-1}}+\frac{d}{a_{n-2}}, n\geq 2$? It seem that in this case obtaining an explicit formual for $a_n$ is a bit more complicated.
Comment: More than a bit, I think.


Diferença no casting em Java

Question: Qual a diferença entre os 2 códigos abaixo?
1º
int x = 10;
float i = (float) x;

2º
int x = 10;
float i = Float.parseFloat(x);

Answer: É bem simples, o primeiro funciona e o segundo não, não faz sentido fazer um parsing  em um número inteiro, apenas em strings. Então a documentação mostra que só pode passar uma string.
Aliás o nome do método é um "primor" :P
O primeiro indica que um número que era inteiro deva ser interpretado como um tipo de ponto flutuante binário. Haverá uma conversão porque os formatados de cada tipo é diferente. Na verdade funciona sem isso, há uma conversão implícita de int para float conforme especificação da linguagem.
Comment: Obrigado pela ajuda

Diferença no casting em Java


Is setting the Authorization header in HttpClient safe?

Question: I'm working in a MVC5 ASP.NET project, and learned that to send authenticated requests to a WEB API from the controller I could do the following to add a token to the header(using an example code):
public static class APICaller
{
    // Use a single instance for HttpClient to reduce overhead
    private static readonly HttpClient client = new HttpClient();

    //Set the Authorization Header
    public static string SetHeader( string token )
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        return("Success");
    }
}

Is setting the header this way on the HttpClient thread-safe? Will other users have a way to access this same token, given that there is only one instance of this HttpClient?
EDIT:
I'd like to ask one more question to get a better understanding of how it works. Would I need to add the header each time I'm making a request with the same HttpClient object?
Answer: With the approach you have, once you've set the default request header on your static instance, it will remain set without you having to keep setting it. This means that if you have multiple requests coming into your server, you could end up in a situation where the header is set for one user and then changed by another request before that first request makes it out the door.
One option to avoid this would be to use SendAsync when using user-specific authorisation headers. This allows you to tie the header to a specific message, rather than setting it as a default for the HttpClient itself.
The code is a bit more verbose, but would look something like this:
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://path/to/wherever"))
{
    httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "TheToken");

    using (var httpResponseMessage = httpClient.SendAsync(httpRequestMessage))
    {
        // ...
    }
}

As you can see, the header is set specially on each request and therefore the issue of mixing up the headers goes away. The obvious downside is that this syntax is more verbose.
Answer:
Will other users have a way to access this same token, given that there is only one instance of this HttpClient?

Yes, that is why you need to be careful when setting the default headers.

Would I need to add the header each time I'm making a request with the same HttpClient object?

No, because you set the default header all requests created with that object will have the header.
For things like a Bearer token it is better to not put in the default headers and instead put it in the request header by creating a new HttpRequestMessage object, setting the headers you need there, then using HttpClient.SendAsync(  passing in the request message to send the headers along with your request.


Using a View in a tooltip for an image map hover link

Question: I have a imagemap with various  tags, it works well in my Drupal instance, I can click on the various areas to get to my pages.
Now I want to hover one area and display a tooltip with information inside (example: if I hover France, I will have a tooltip showing little information on Paris, with a picture). I will find myself how to do it by the way if you can't help with it - that's just my final goal.
Following various sites tutorials, I made a View with contextual filters in order to display the city content by passing an argument to the view. It works like a charm. I also rewrote the output to use tokens for display
I have actually no idea how to display my View in a tooltip - and searching didn't help me either ...
Modules I am using :

Views
Tipsy (or qTip or else, I don't have any preferences, as long as it works)
Comment: It is not possible to show the whole view in a tooltip
Comment: You can display the view fields in tool tip, but not the whole views.
Comment: OK can you please explain to me how I display the view fields ? I can't see how it works ...
Comment: I done it with https://drupal.org/project/beautytips module. have a look at this, if have a idea to use it, then i will tell you the steps.
Comment: OK so I installed the Beautytips module and configured the UI to fit my needs. Can you tell me the steps ?
Comment: While waiting for you answer, I found out this page : http://www.wootenswebdesign.com/quick-and-easy-beauty-tips which is exactly what I am trying to do - but it is Drupal 6 compliant, and he uses Custom Field module which is deprecated in Drupal 7.

How can I achieve this result in D7 ?
Answer: You can easily use replacement patterns to achieve something similar.
Add the fields you would want as the view and then in replacement pattern you can render a views block or even customize the display via html.


@media print css

Question: Talvez essas perguntas podem ser tachadas como "idiota", mas acreditem em mim, preciso muito perguntar isso aqui por que não encontrei em nenhum lugar na internet e quem puder me ajudar ficarei muito grato...
Existe alguma maneira de fazer 2 (dois)  ou mais "@media print" do css? Por exemplo, eu fiz um para imprimir uma determinada div, agora quero imprimir outra div totalmente diferente com outras configurações de formatação, como eu faria usando o proprio @media print?
Aproveitando a pergunta, existe alguma maneira de formatar a div como desejado antes de mandar imprimir pelo javascript, não gostei da impressão do javascript, não vem quase nada do que foi feito na página além da escrita pura. '-'
@media print {
body * {
    visibility: hidden;
}
.noneImprime
{
    display: none;
}
#imprime, #imprime * {
    visibility: visible;
    margin-top: -160px !important;
}
#imprime
{
    width: 1100px;
}
.btn-resultado{
    display: none;
}
@page{
     size: landscape;
    }
}

Acima tem o código que estou usando para imprimir minha div com o ID: imprime, no entanto eu tenho outra div, que no meu caso é o conteúdo de uma modal para imprimir, como eu faço para imprimir somente o conteúdo desejado como mostra corretamente acima e no mesmo print imprimir somente o conteúdo da minha modal?
 Neste caso toda vez que eu clico no botão designado ele vai imprimir sempre a mesma div.
Answer: Pra formatar duas div's diferentes, coloque classes diferentes nela e colocar as propriedades diferentes dentro do @media print
Pra testar como funciona antes de gerar a impressão do javascript você pode ir na opção 'More tools > Rendering settings > Emulate media > print' da ferramenta de desenvolvedor do Chrome:

Você provavelmente vai ter que usar alguns !important para sobrescrever o estilo padrão da folha de impressão e como você vai fazer isso dentro do Media query de print, é bem tranquilo.
Comment: Não, mas a sua resposta está correta, obrigado por sua ajuda, obrigado mesmo.
Comment: Entendi Vinicius, muito obrigado pela resposta, no entanto tenho mais uma dúvida, no meu caso uso o visibility: hidden e visible para mostrar na folha de impressão somente o conteudo desejado, para fazer isso com duas divs diferentes acho que não dá né, por que ou mostra uma ou mostra a outra.
Comment: Cara, se for possível edita sua pergunta com o código que fica mais fácil de entender isso, mas aí é questão de atribuir uma id ou uma classe diferente e trabalhar com as regras CSS.
Comment: Editei o post, acho que não to sabendo explicar direito, de qualquer forma eu agradeço muito a sua ajuda.
Comment: Hm, a explicação tá meio complicada de entender pra ser sincero, não sei se o HTML ajudaria, mas não seria só uma questão de forçar um display no conteúdo do modal?

@media print css


How to check Bacula version

Question: How do I check the Bacula version?
I installed Bacula using the apt-get install command on Ubuntu. I want to know the version I am using.
Answer: Run this:
apt-cache policy bacula

This will show you the version of bacula that is currently installed, as well as all versions of bacula available to you from all repositories in /etc/apt/sources.list.
Answer: This can be a complicated question to answer because there are a lot of pieces involved, pieces that are different depending on what the purpose of the machine is and what versions of Bacula (or Baculum) you're dealing with. Even on the same machine, it's possible to have several parts with different versions (which may or may not be a problem—it's complicated).
For example, both my main Bacula server (where all the backups are stored) and the machines it backs up have some version of the package bacula-common installed, but only my main server has bacula-mysql installed, and nothing has the package just named "bacula" installed.
Apt
Depending on your setup, you may be able to use apt-cache policy package-name to get a list of what was installed via apt or could be installed:
# All Bacula packages
apt-cache policy bacula*
# A specific one
apt-cache policy bacula-common

This was helpful when I was trying to upgrade Bacula. It's also the only way I know of to check the version of Baculum (the web interface).
Note that upgrading to Ubuntu 22.04 from 20.04 will make it impossible to find Bacula in the Ubuntu repos (thus returning an error even if you had previously installed Bacula this way and preventing Bacula from working) and in 20.04 the highest version available is Bacula via these repos is 9. Because of this, I had to edit /etc/sources.list (or a subfile like /etc/sources.list.d/baculum.list) to pull from Bacula's own repos.
Note also that the Bacula apt packages you need vary based on what version you're running. Bacula 9 has bacula-sd and bacula-director for example, but Bacula 13 has you install the bacula-dir package and no bacula-sd package—more on these missing packages later.
Command line tools
The Bacula command line tools (e.g., bconsole) accept the question mark flag (-?) as a way to print out the version (and information about the other flags). While there's no support for -v, typing in an invalid command like that will also show this same help message. You can also run bconsole alone to start up the console, which will also show the version (but usually requires more permissions than -? on account of having to load the conf files and you also have to exit it). The version returned by bconsole should be the same as in apt-cache (if installed that way), though they are in slightly different formats—the former gives the date of publication for that version of the software, for example.
For your copy/pasting convenience:
bconsole -?

This proved challenging to use in a script where I only wanted to see the version. I ended up with this monstrosity which is a little verbose since it outputs the entire line with the version:
version=$(bconsole -? >(grep 'Version') 2>(grep 'Version'))

Other versions
In addition to the above, I soon realized that there are important binaries that didn't have an installed apt package and couldn't be accessed by just typing in a command like bconsole. For example, bacula-sd is installed with apt if you have Bacula 9, but there is no such package for Bacula 13. In Bacula 9, the binaries seem to have been in /usr/sbin/, while in Bacula 13 they're in /opt/bacula/bin/.
Files
Something else worth noting is that for me many files in Bacula 9 were installed in /etc/bacula/ while everything in Bacula 13 got installed into /opt/bacula/. This means that anything that references something in /etc/bacula/ (such as /etc/init.d/bacula-sd) is from the version 9 installation.
Meanwhile, Baculum for me is in /etc/baculum/—it did not move when I installed the most recent version (Baculum 11).

How to check Bacula version


Compute QNR whose Jacobi is 1

Question: How do I compute a QNR in ZN which has a Jacobi of 1? N is product of distinct primes.
Answer: Let's assume $n=pq$ with different primes $p,q$. If $\left(\frac{a}{p}\right) = -1\;$ and
$\left(\frac{a}{q}\right) = -1\;$ then $\left(\frac{a}{n}\right) = 1\,$ but $a$ is a QNR modulo $n$, because (Wiki):

This is because for a to be a residue (mod n) it has to be a residue
  modulo every prime that divides n, but the Jacobi symbol will equal
  one if for example a is a non-residue for exactly two of the primes
  which divide n.

So to get for example a QNR modulo 35 with $\left(\frac{a}{35}\right) = 1\;$ look for those $a$ which are simultaneously QNRs modulo 5 and 7. The first one is $a=3$ (by inspection you can find that there is no $x$ with   $x^2 = 3 \pmod{35}$.

Compute QNR whose Jacobi is 1


What does the exclamation mark do?

Question: I've seen this but never knew what it does. Can any one let me in on the details? Thanks.
Comment: One of my students: "What is $7!$... is it like SEVEN?!?!"
Comment: "Among the worst of barabarisms is that of introducing    symbols which are quite new in mathematical, but perfectly     understood in common, language. Writers have borrowed from the     Germans the abbreviation n! to signify 1.2.3.(n - 1).n, which
gives their pages the appearance of expressing surprise and    admiration that 2, 3, 4, &c. should be found in mathematical results." - Augustus de Morgan, 1842.
Comment: @TheChaz: in a high squeaky voice? ;)
Comment: @J. M. - Not exactly! He was actually one of the bigger college students that I've worked with... I used to run into Thomas at the gym every so often.
Answer: Probably you're thinking about the symbol for the factorial function:
$$n! = 1\times 2 \times 3\times \cdots \times (n-1) \times n$$
Answer: An exclamation mark can also be shorthand for "unique". For example, the statement
$$\forall y\in f(A), \exists!x\in A \text{ s.t. } y=f(x)$$
would be read as "for all $y$ in the range of $f$, there exits a unique $x$ in the domain such that $y=f(x)$". In other words, $f$ is one-to-one.
Answer: ...or possibly double factorial $n!! = n \times (n-2) \times (n-4) \times \cdots $, or maybe subfactorial, $!n$, also known as derangement number.
Added ... and superfactorial for desert.
Comment: the superfactorial has little rainfall? :-)
Comment: ...and there's even a hyperfactorial, too. :)
Answer: For completeness:
Although in mathematics the $!$ almost always refers to the factorial function, you often see it in quasi-mathematical contexts with a different meaning.
For example, in many programming languages it is used to mean negation, for example in Java the expression !true evaluates to false. It is also commonly used to express inequality, for example in the expression 1 != 2, read as '1 is not equal to 2'.
It is also used in some functional languages to denote a function that modifies its input, as in the function set! in Scheme, which sets its first argument to the value of its second argument.
Answer: I just wanted to add a common usage for it as well since that may be of more interest to you.
A common usage for the factorial is in permutations.
For example:
If there were 3 people in a race, how many possible ways could there be to arrange the ranking.
The answer would be 3! (3 factorial) or 3 x 2 x 1 or 6 ways.
Listing them the brute force way:
1) A,B,C
2)A,C,B
3)B,A,C
4)B,C,A
5)C,A,B
6)C,B,A
This extends into a lot of other things but most commonly associated with statistics, I believe.
Answer: If it is $6!$, it would be $6 \times 5 \times 4 \times 3 \times 2 \times 1$, if it was $9!$, it would be $9 \times 8 \times 7 \times 6 \times 5 \times 4 \times 3 \times 2 \times 1$. Do you see the pattern?
$$6! = 720\\
9!= 362,880.$$
Comment: Welcome to math.se! Please take a look on [how to format mathematics here](http://math.stackexchange.com/help/notation). I'll edit your post, and you can see all changes pressing edit button, but do formatting yourself in the future.

What does the exclamation mark do?


Can we have negative modulo in modular arithmetic?

Question: Why can't we have modulo to a negative number? I have never seen this.
Comment: What's stopping you from trying yourself? What did it result in?
Answer: We can, but you'll notice by looking at the definition that $a\equiv b\pmod {(-n)}\iff a\equiv b\pmod n$, so it's a bit silly.