Are referees biased toward the home team?

Question: Inspired by this question but hopefully different enough to warrant a different question.
I often hear fans complaining that the "home team always gets the calls", which means that more fouls are called against the away team than the home team. This has been attributed to a number of things:

The emotion in the arena sways the officials
The home team coaches have longer conversations with the referees before the beginning of the game, and they are instructed on what types of fouls to watch for.
The referees, or the sideline replay officials, are natives of the home town and want their team to win.
The referees are paid money to make calls for the home team.

First question is: Does the home team actually get more favorable calls from the officials? Statistical research would be nice.
Second question is: If the home team gets more calls, are any of these specific complaints (or others) valid or verifiable by research?
Comment: I think this is a great answer is the answers can remain objective. On the fact it looks rather subjective, but there have been objective studies done on this subject.
Comment: @Jae I understand that, but the question is regarding statistical research about the subject. Should all questions regarding batting average be considered not constructive because all batters are different?
Comment: This is not a constructive question.
Comment: @Jae can you help me understand why you feel that way? Or start a discussion in meta?
Comment: Because it varies by referee. If he's not a fair guy, he'll side with one team. It depends, therefor it is not a constructive question.
Comment: @MarcusSwope: No because there is fact backing it up. That is what this question is lacking.
Comment: @Jae maybe try asking about this on meta and see what the consensus it.
Answer: I came across many articles with summaries of studies that indicate that referee bias does in fact exist across many sports.
In "Basketball: Bias Refs (full article)," the blurb states:

The study found that the probability of a foul call being against a
  visiting team was seven percent higher than calls against the home
  team. They also noted when the home team is ahead in the game, the
  likelihood of a foul being called against them is 6.3 percentage
  points higher than when they were behind. Finally, economists observed
  the larger the foul difference between the two teams, the more likely
  it is the next call will be made against the team with fewer fouls.

Gail Imber notes in his article "Referee Bias: Quantifying the Homer Effect and Officiating Home-Field Advantage":

Specifically, Boyko postulates that "While subconscious referee bias
  does not necessarily make home advantage unfair, our finding of
  significant variation in home advantage by referee is hard to accept
  as fair."

and

All verifiable studies decidedly concluded the "homey effect" is due
  to subconscious variations in play calling—not due to a conscious
  attempt to manipulate or "throw" the game.

There are links to several studies and articles in Imber's article. Some interesting excerpts:

"Nevill asked qualified soccer referees to analyze various challenges which had been recorded on videotape, either with or
  without sound. Nevill found that when the variable of crowd noise was
  introduced, the referees called 15.5 percent fewer fouls against the
  home team.";
"The Los Angeles Times' Douglas Farmer summed it up as
  'subconscious submission to peer pressure.'"

In the blog post titled "More evidence for referee bias in soccer," Phil Birnbaum points to two studies related to European football - in the Spanish and German leagues. He notes:

Looking at games in the Primera Division in Spain over two specific
  seasons (1994-95 and 1998-99), they found that, in games where the
  score difference was exactly one goal, referees awarded almost twice
  as much extra time when the home team was trailing as when it was
  leading. More time, of course, benefits whichever team is behind, as
  it gives them a better chance to tie the game.

and

Also, the authors note that a German magazine, "Kicker Sportmagazin,"
  reviews all games and posts an opinion on which penalty calls were
  correct and which were incorrect (both actual and missed calls). It
  turns out that for penalties called in favor of the home team, 5 out
  of 55 were illegitimate. But for visiting teams, it was only 1 out of
  21. So referees favored the home team by about twice as many false positives.
False negatives also favored the home team. There were 12 cases where
  home team should have been awarded a penalty, but wasn't; there were
  19 such cases for the visiting team.

In an article about NBA referees, James Downie notes:

They found "evidence of three biases: favoritism of home teams, teams
  losing during games, and teams that are behind in a multi-game playoff
  series. All three biases are plausibly profit-enhancing for the
  league." The authors calculate that, during the regular season, the
  turnover biases "equates to win probability changing by approximately
  2.2% when a team switches from away to home status," and a further 2.5% if fouls are included. In the playoffs, the biases do not appear to affect fouls, but the effect on turnovers becomes nearly doubles,
  keeping the probability change close to 5%. Maybe beating that 5% is
  why coaches ask players to give 110%...

So in summary, it appears that referees across all sports do show some subconscious favoritism towards the home team, even while striving to remain impartial.
EDIT: Added some excerpts mentioned in one of my comments below.
Comment: Yes, some excerpts that I saw indicated that crowd noise/peer pressure contributed to this effect: 1. "Nevill asked qualified soccer referees to analyze various challenges which had been recorded on videotape, either with or without sound. Nevill found that when the variable of crowd noise was introduced, the referees called 15.5 percent fewer fouls against the home team."; 2. "The Los Angeles Times' Douglas Farmer summed it up as 'subconscious submission to peer pressure.'"
Comment: This is a great answer to the first question, but did you come across anything that explained *why* they have this bias? I saw some references to it being a subconscious thing, but I am also curious as to what causes this.
Comment: That is actually very interesting, can you add it to the answer?
Comment: @MarcusSwope, comments added. Thanks for your feedback.
Comment: `the larger the foul difference between the two teams, the more likely it is the next call will be made against the team with fewer fouls.`  I'm guessing by "more likely" it means the likelihood is greater than when the margin is smaller, rather than fouls being more likely to be called against the fewer-fouls team than the more-fouls team, since the latter wouldn't make sense if the margin had been increasing.  Confusing wording!  On another note, I wonder if there's been any study of refs trained to be aware of possible influences on their decisions and whether such training works?


Is it possible to calculate percentiles in skewed distribution without raw data (only mean, median, SD)?

Question: If it is of any one's interest, the data is taken from the duration of men "last in bed" as studied here.
I want to calculate the percentiles (say, 95th) of a non-normal distribution without raw data. What are the minimum constraints needed? I have the following and I think some are not necessary.

n=474
mean=8.5
SD=7.47
median=6.0
min=0.1
max=52.7
Comment: There's an infinite number of possible solutions. It might be possible to derive some bounds
Answer: This is not possible. The percentile depends on the exact shape of the distribution. So unless you make a parametric assumption about the distribution or an assumption directly about the 95th percentile you cannot estimate the percentile well without the original data.


Causes of piano finger strain and ways to relieve it

Question: After I practice for a few hours on the piano, I feel a strain in my hands (I don't know if strain is the right word, It doesn't hurt or anything. It actually feels good because I feel like I have exercised my hands properly). In any case, I usually stop practice at that point, because I don't want to injure myself (RSI style). My questions are:

From where does the strain usually originate: muscles, tendons etc.
Is there a way to relieve it or deal with it beside resting. I mean something in the line of soaking my hands in hot water :).
Answer: Tom has already started a metaphor with runners. You do not train for a long-range distance (such as 20km or marathon) by running this distance. You have to help your body become the kind of body able to run such a distance. And it includes drinking water, many breaks, changes in lifestyle.
Health of the hands is not separated from the general health.
Practicing several hours without pause is the best way to injure yourself physically and waste time because your system will have low efficiency and recall.
This is sometimes counter intuitive because the first few times you train extremely hard, you have very quick results . But working too hard and in a quick and relentless progression does not work on a sustained period.
There is no magic bullet or quick fix when you feel strain in your hands.

Always start your practice session by very gentle warming of the hands, wrist and fingers, oxygenation exercices, like a dancer or a singer.
Be sure that your seat is at the correct height and distance. Be on a lookout for any backache, any strain in the shoulders, bad blood circulation in your legs, etc.
Cut your practice sessions in small units (5, 10, 15mn) between which you can stand for a few moments, drink, walk, speak, inhale and exhale deeply.
Always try not to produce forte sound by sheer force and pressure, but by a lighter but fuller engagement of the body, posture, place of fingers on the keys ...
Make slightly larger breaks every hour and do not practice more than two hours in a row (even with small breaks inside).
Try to schedule one of your schedule sessions just before or just after a nap or sleep so that you can let your body and mind rest more fully.
If you are not in a city or if you are near a park, be sure to walk or run lightly in outdoor every day you practice
Answer:
After I practice for a few hours on the piano

Do these hours include pauses? If you don't pause you will indeed get finger strain.
For the same reason you can't run for an extended time; well, you could but it would takes practice.
When you first start running, you won't reach half an hour or you will be extremely strained/tired afterwards.
How are runners able to run an half hour?
They regularly stop running to walk a bit and when they feel rested enough they will start running again, which allows them to take an half hour of practice instead of being burned out after 15 min. Over time, they need less rests as they become trained, and thus can run an half hour with less issues.
How do runners get rid of the strain?
They stretch, you might benefit from this too. Look for exercises:

Loosens stiff fingers, hands and wrists.
Completed daily for a few months, hands will become more flexible.
— Stretch Now - Exercises - Hands

Your good feeling is merely a warning sign that you are doing too much without giving your hands a rest.


prove that C = (C \D)∪(C ∩D).

Question: Let C and D be sets. Use element chasing to prove that C = (C \D)∪(C ∩D). We can only use definitions and logical deduction. You can not use properties of sets. I am having trouble figuring out where to start on this proof. I know for element chase we have to do a case by case proof.
Comment: Welcome to Mathematics Stack Exchange.  Assume $x\in (C\setminus D)\cup (C\cap D)$.  Show $x\in C$.  And vice versa
Answer: If $C = \varnothing$ you are done. If $C \neq \varnothing$, pick an element of $C$, let's say, $c$. Now, note that, $c$ satisfy one, and only one, of the following two conditions:

$c$ is an element of $D$,
$c$ is not an element of $D$.

If $c$ satisfies the first, we then have that $c \in C \cap D$, and hence $c \in (C \setminus D) \cup (C \cap D)$. In the other case, we have that $c \in C \setminus D$ and again, $c \in (C \setminus D) \cup (C \cap D)$.
In either case, we see that $c \in (C \setminus D) \cup (C \cap D)$, showing that any element of $C$ is also an element of $(C \setminus D) \cup (C \cap D)$. So, $C \subseteq (C \setminus D) \cup (C \cap D)$.
Can you show the other inclusion?

prove that C = (C \D)∪(C ∩D).


Is it legit to compute/define moving average series for a stationary process?

Question: Suppose we have $X_{1}, X_{2}, ..., X_{n}$ sequence of $iid$ random variables with mean $\mu$ and standard deviation $\sigma$. By definition, the time series $x_{1}, x_{2}, ..., x_{n}$ is a stationary process with mean $\mu$ and standard deviation $\sigma$. If so, is it legit to compute a moving average series for the process as follows:
$$s_k=\frac{x_{1}+x_{2}+...+x_{k}}{k}?$$
As the process is stationary, we assume that the mean should be time invariant, i.e., $\mu$. Then if it is legit to compute moving average series, how we interpret it in the context of stationarity? (I assume if it makes sense, then interpretation should relate to long- and short-run dynamics of the series. )
Comment: $s_k$ obviously is "legitimately" computed (there's no obstacle at all to forming linear combinations of finitely many random variables)--but $(s_k)$ is not stationary, as you can tell by calculating that its standard deviation is $\sigma/\sqrt k,$ which varies with $k.$
Answer: Yes it is legit to compute a moving average on a stationary series, and it can be convenient too, for the most various reasons. Stationarity in itself means the process has an unconditional constant expected value, but a stationary process can still have different expected values for different time points, conditioned to the previous values. For instance a process can have a tendency of giving new observations that are close in value to the previous ones, and still be stationary as long as these values tend to go back to the unconditional mean over time.
This answer wouldn't be complete without citing the notorious MA models, which make a weighted moving average of the process in order to make a forecast of new observations. I'm bringing them up because estimating MA weights requires stationarity.
Comment: To me *a weighted moving average of the process* sounds more like an AR model than an MA model. The latter works with residuals, not the original process.
Comment: I admit I used the MA process as an example because of the name, and that was probably an error, because the name is quite misleading (the fact that MA processes can have negative parameters is particularly problematic), but an AR model is not a better example. Also MA processes can be refactored as infinite AR processes (and viceversa).
Comment: AR model is the general case of what you describe.


Avoiding redundancies in makefile rules

Question: Consider the following makefile:
C_COMPILER      = gcc
C_COMPILER_OPTS = -DFOOBAR

OBJECTS=obj/dir1/foo.o obj/dir2/bar.o obj/dir3/test.o

obj/dir1/%.o: src/dir1/%.c
    $(C_COMPILER) -o $@ $(C_COMPILER_OPTS) src/dir1/$*.c

obj/dir2/%.o: src/dir2/%.c
    $(C_COMPILER) -o $@ $(C_COMPILER_OPTS) src/dir2/$*.c

obj/dir3/%.o: src/dir3/%.c
    $(C_COMPILER) -o $@ $(C_COMPILER_OPTS) -DANOTHEROPTION src/dir3/$*.c

libfoobar: $(OBJECTS)
    ar rs $@.a $(OBJECTS)

obj/dir1/foo.o: src/dir1/foo.c
obj/dir2/bar.o: src/dir2/bar.c
obj/dir3/test.o: src/dir3/test.c

As you can see, the build rules for the files in src/dir1 and src/dir2 are identical. Files in src/dir3, however, are built differently.
So is there a way to reduce the two build rules for src/dir1 and src/dir2 into just one rule, thereby eliminating the redundancy?
Answer: I would try something like (GNU make only):
C_COMPILER      := gcc
C_COMPILER_OPTS := -DFOOBAR
DIRS            := dir1 dir2 dir3
TOP             := libfoobar.a

.PHONY: all clean

all: $(TOP)

dir1_C_COMPILER_OPTS := $(C_COMPILER_OPTS)
dir2_C_COMPILER_OPTS := $(C_COMPILER_OPTS)
dir3_C_COMPILER_OPTS := $(C_COMPILER_OPTS) -DANOTHEROPTION

# $(1): dir, $(2): file basename
define COMPILE_rule
OBJECTS += obj/$(1)/$(2).o
obj/$(1)/$(2).o: src/$(1)/$(2).c
    $$(C_COMPILER) -o $$@ $$($(1)_C_COMPILER_OPTS) $$<
endef
$(foreach d,$(DIRS),$(foreach f,$(patsubst src/$(d)/%.c,%,$(wildcard src/$(d)/*.c)),$(eval $(call COMPILE_rule,$(d),$(f)))))

$(TOP): $(OBJECTS)
    ar rs $@ $(OBJECTS)

clean:
    rm -f $(OBJECTS) $(TOP)

foreach var,$(VAR) loops over words in $(VAR) and assigns the current word to $(var).
call var,$(v1),$(v2) performs an expansion of var where it substitutes $(1) with the current value of $(v1), $(2) with the current value of $(v2)... and $$ with $.
eval instantiates the result of the call expansion as a regular rule.

If you do not want to use the foreach-eval-call construct, you can also try this slightly more verbose solution (it separates the dependencies from the recipes):
C_COMPILER      := gcc
C_COMPILER_OPTS := -DFOOBAR
TOP             := libfoobar.a

.PHONY: all clean

all: $(TOP)

OBJ1 := $(patsubst src/dir1/%.c,obj/dir1/%.o,$(wildcard src/dir1/*.c))
OBJ2 := $(patsubst src/dir2/%.c,obj/dir2/%.o,$(wildcard src/dir2/*.c))
OBJ3 := $(patsubst src/dir3/%.c,obj/dir3/%.o,$(wildcard src/dir3/*.c))

obj/dir1/%.o: src/dir1/%.c
obj/dir2/%.o: src/dir2/%.c
obj/dir3/%.o: src/dir3/%.c

$(OBJ3): C_COMPILER_OPTS += -DANOTHEROPTION

$(OBJ1) $(OBJ2) $(OBJ3):
    $(C_COMPILER) -o $@ $(C_COMPILER_OPTS) $(patsubst obj%.o,src%.c,$@)

$(TOP): $(OBJ1) $(OBJ2) $(OBJ3)
    ar rs $@ $^

clean:
    rm -f $(OBJ1) $(OBJ2) $(OBJ3) $(TOP)

Comment: Thanks, but this looks really complicated. I was hoping for an easy way to remove the redundancy but since this is apparently not possible, I think I'll just stick with my version...
Comment: It may look complicated the first time you see it, but it is not, I swear. Just loops and variable substitutions. And learning how to use this `foreach-eval-call` construct can improve your GNU make productivity by a significant factor.
Comment: Many projects ban these constructs, though, because they feel they make makefiles even less maintainable.
Comment: OK, OK, considering the lack of enthusiasm for the `foreach-eval-call` construct, I added another option, maybe a bit easier to understand.
Answer: Make variables defined with = are evaluated recursively, until no substitutions remain:

Two Flavors of Variables

So you could use this:
compile-command = $(C_COMPILER) -o $@ $(C_COMPILER_OPTS) src/dir1/$*.c

obj/dir1/%.o: src/dir1/%.c
    $(compile-command)

(Although I personally consider this make behavior a hack and dislike it—but the alternatives are $(eval …) and scripted generation of makefiles, and those are not ideal, either.)

Avoiding redundancies in makefile rules


Group data on weekly basis

Question: I am stuck with following problem. How can I group following data in the way that it will sum up count on weekly basis.
<code>    +---------------------+-----+
    |          data       |count|
    +---------------------+-----+
    | 2012-08-01 00:00:00 |  4  |
    | 2012-08-02 00:00:00 |  5  |
    | 2012-08-03 00:00:00 |  6  |
    | 2012-08-04 00:00:00 |  6  |
    | 2012-08-05 00:00:00 |  8  |
    | 2012-08-06 00:00:00 |  6  |
    | 2012-08-07 00:00:00 |  8  |
    | 2012-08-08 00:00:00 |  6  |
    | 2012-08-09 00:00:00 |  2  |
    | 2012-08-10 00:00:00 |  0  |
    | 2012-08-11 00:00:00 |  5  |
    | 2012-08-12 00:00:00 |  4  |
    | 2012-08-13 00:00:00 |  4  |
    | 2012-08-14 00:00:00 |  0  |
    +---------------------+-----+
</code>
Output  should be following
<code>+----------------------+------+
|     data             | count|
+--------------------- +------+
| 2012-08-06 00:00:00  |  43  |
| 2012-08-13 00:00:00  |  21  |
+----------------------+------+
</code>
Answer: You just have to use a function that "rounds" all your dates to the date you want, maybe something like this:
<code>select
    DATEADD(week, DATEDIFF(week,0,data), 0) as Monday,
    sum([count]) as [count]
from
    yourtable
group by
    DATEADD(week, DATEDIFF(week,0,data), 0)
</code>
Comment: That original SQL groups Sunday - Saturday weeks always to the Monday, but if you want Sunday - Saturday to be placed in the Sunday, then it's DATEADD(day, -1, DATEADD(week, DATEDIFF(week,0,data), 0))

Group data on weekly basis


If $p\equiv 1,9 \pmod{20}$ is a prime number, then there exist $a,b\in\mathbb{Z}$ such that $p=a^{2}+5b^{2}$.

Question: I have to prove that if $p\equiv 1,9 \pmod{20}$ is a prime number then there exist $a,b\in\mathbb{Z}$ such that $p=a^{2}+5b^{2}$.
I consider the quadratic field $\mathbb{Q}(\sqrt{-5})$, with ring of integers $A=\mathbb{Z}[\sqrt{-5}]$. It is easy to check that $\left (- \dfrac{5}{p} \right)=1$ if $p\equiv 1,9 \pmod {20}$. According to this, $t^{2}+5$ has two different roots in $\mathbb{F}_{p}$. In consequence, $pA=P_{1}P_{2}$ for certain prime ideals $P_{1}, P_{2}$ with norm $p$. A is not a PID, but if I prove that $P_{1}$ or $P_{2}$ are principal, then I had there exist $\gamma=a+b\sqrt{-5}\in A$ such that:
$p=N(P_{i})=N(\gamma A)=|N_{\mathbb{Q}(\sqrt{-5})|\mathbb{Q}}(\gamma)|=a^{2}+5b^{2}$,
and I would have finished. The problem is that I do not know how to prove this. If there is an easier way, please, let me know.
Comment: There is an elementary proof too, suggested by r9m in a comment [here](http://math.stackexchange.com/questions/685958/let-p-be-prime-and-frac-3p-1-prove-that-p-is-of-the-form-p-a23b2?lq=1#comment1439095_685982).
Comment: It's worth asking why the other primes where $-5$ is a square don't count; $p\equiv 3,7\pmod {20}$.
Comment: Thank you barto, r9m's comment solves the problem.
Comment: Hint: there's a paper by David Brink which asserts that if $p \equiv  1 \pmod{20}$ then both $p = x^2 + 20y^2$ and $p = x^2 + 100y^2$ hold or neither holds.
Answer: I'm not sure which level to write this at. Here is a completely elementary proof:
As you say, if $p \equiv 1$, $3$, $7$ or $9 \bmod 20$, then $\left( \frac{-5}{p} \right) = 1$. Let $p$ be in one of these residue classes and let $a$ be a square root of $-5$ modulo $p$. Let $\Lambda \subset \mathbb{Z}^2$ be the lattice of pairs $(x,y)$ such that $x \equiv ay \bmod p$. For any $(x,y) \in \Lambda$, we have $x^2+5 y^2 \equiv (ay)^2 + 5 y^2 \equiv (-5+5) y^2 \equiv 0 \bmod p$. Since $\Lambda$ has index $p$ in $\mathbb{Z}^2$, the fundamental domain of $\Lambda$ has area $p$. The ellipse $\{ (x,y) : x^2+5y^2 < N \}$ has area $\pi N/\sqrt{5}$.
Therefore, taking $N = (4\sqrt{5}/\pi) p \approx 2.85 p$, Minkowski's theorem shows that $\Lambda$ contains a point $(x,y)$ with $0 < x^2+5y^2 < 2.85 p$. Since $x^2+5y^2 \equiv 0 \bmod p$, we deduce that $x^2+5y^2 = p$ or $2p$.
So far, the proof works for all four residue classes $1, 3, 7, 9 \bmod 20$. Now note that, if $p \equiv 1$ or $9 \bmod 20$, the equation $x^2+5y^2 = 2 p$ is impossible modulo $8$.

You can tweak this proof to be more or less sophisticated, as you please.
More If $\left( \frac{-5}{p} \right)=1$ then the ideal $p$ splits as $\mathfrak{p} \bar{\mathfrak{p}}$ in $\mathbb{Z}[\sqrt{-5}]$. From the Minkowski bound, $\mathfrak{p}$ must have the same ideal class as an ideal of norm $< 4 \sqrt{5}/\pi \approx 2.85$, so either $\mathfrak{p}$ is principal or else $\mathfrak{p} \sim \langle 2, 1+\sqrt{5} \rangle$, in which case $\mathfrak{p} \cdot \langle 2, 1+\sqrt{5} \rangle$ is principal. In the former case, we have a solution to $x^2+5y^2=p$; in the latter case, we have a solution to $x^2+5y^2=2p$ which is impossible modulo $8$. It's not a surprise that the same numbers are showing up -- the above proof is simply this one without mentioning ideal classes.
Less If you don't want to mention Minkowski's theorem, you can mimic the pigeonhole proof here that any prime which is $1 \bmod 4$ is the sum of two squares. Consider the numbers $x-ay$ for $0 \leq x < \sqrt[4]{5} \sqrt{p}$ and $0 \leq y < \sqrt{p}/\sqrt[4]{5}$ and proceed as in the link. The inequality isn't as good as you get with Minkowski: You conclude that you can solve $x^2+5y^2 \equiv 0 \bmod p$ with $0 < x^2+5y^2 < 2 \sqrt{5} p \approx 4.46 p$.
But that's good enough, you just get a few more cases. If $x^2+5y^2=p$, you win. If $x^2+5y^2=2p$, you get a contradiction modulo $8$, if $x^2+5y^2 = 3p$, you get a contradiction modulo $4$. If $x^2+5y^2=4p$ then looking modulo $4$ shows that $x$ and $y$ are even, so $(x/2)^2+5(y/2)^2=p$.


How to get the URL of the get_avatar_url function in WordPress

Question: Would you be able to help me with my problem?
What I'm trying to do is get the exact URL of the get_avatar_url() function in WordPress. Then use the URL as the background-image url.
Here's how my code looked like.
<?php $avatar_url = get_avatar_url(get_avatar($author->ID, 150), array("size"=>260)); ?>
<div class="col-xs-5 nopadding author-picture" style="background: url('<?php echo $avatar_url; ?>')">
    <a class="author-block " href="<?php echo get_author_posts_url($author->ID); ?>">

                 <?php echo get_avatar($author->ID, 150); ?>

However, on the page it is returning like this:
Comment: Related: https://stackoverflow.com/questions/35314867/get-avatar-urlget-avatar-always-return-default-96-size
Answer: The usage of get_avatar_url is get_avatar_url( mixed $id_or_email, array $args = null ). Why are you passing get_avatar to this function.
You can use this directly like this:
get_avatar_url($author->ID, array("size"=>260 ));

Comment: Hi Amit, unfortunately this is the return that I get.
background: url(https://secure.gravatar.com/avatar/e57e294e57b764ab4f6ffc3ee2d07466?s=260&d=mm&r=g
Comment: Hi Amit, thanks for the quick response. I've been actually scouring google for possible solution to my problem prior to me posting the question. That code you see was the last one I tried from the suggestion I saw online.

I tried your answer as well but it still didn't return the actual URL of the image.

Or, maybe I was using the wrong term in my question. My goal is to get the value of the "src" attribute of the get_avatar function so I can use it on the background-image url.
Comment: But  `get_avatar_url` is supposed to return the url that `get_avatar` uses to create the `src` in the `img` element it creates. so using that function should suffice.
Comment: The get_avatar_url  function seems to be returning the URL. Whats not working for you? Is it that the URL returned is that of default gravatar? If it is then may be that particular user doesnt have gravatar account. if the issue is that the URL of gravatar sent is not being shown in your pages, then may be its baecause your site is being served with HTTP and the gravatar URL is on HTTPs
Answer: like this:
<?php $avatar_url = get_avatar_url(get_the_author_meta( 'ID' ), array('size' => 450)); ?>

<div class="col-xs-5 nopadding author-picture" style="background: url('<?php echo esc_url( $avatar_url ); ?>')">

Comment: Hi Mo'men, unfortunately it's still returning the same thing.
This is what it returns:
https://secure.gravatar.com/avatar/d8ce87606c540f1d8bf07bcff50e5516?s=450&d=mm&r=g
Comment: Put this function in your functions.php |

 function get_avatar_url($get_avatar){
    preg_match("/src='(.*?)'/i", $get_avatar, $matches);
    return $matches[1];
}
Comment: Hi Mo'men, I added the script on in the functions.php file as per your suggestion but it unfortunately rendered the page empty. As in it did not load the whole HTML at all.
Answer: I think the background URL rule must contain a recognizable image extension (jpg, jpeg, gif, png).
To achieve this, you can:
first, get the whole html of the avatar for the specified user ID...
... then extract the url containing the image extension from it, using regex...
and finally use it in your code as follows.
$imageHtml = get_avatar($author->ID, 150);

$imageUrlWithType = [];

preg_match('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $imageHtml, $imageUrlWithType);

<div class="col-xs-5 nopadding author-picture" style="background: url('<?php echo $imageUrlWithType[0]; ?>')">
    <a class="author-block " href="<?php echo get_author_posts_url($author->ID); ?>">

                 <?php echo get_avatar($author->ID, 150); ?>

Answer: get_avatar_url( $current_user->ID );

Comment: Did you read the question? Asker wants to know where this function itself can be found, not just how to call it (I think they could figure this out on their own).


How to solve "jQuery requires a window with a document" error?

Question: At Nuxt.js, I have some problems importing jQuery.
I found some code which I can use jQuery at Nuxt.js
head: {

//other codes...

script: [
  {
    src: 'http://code.jquery.com/jquery-latest.min.js'
  }
]}

If I insert it, '$ is not defined' error occurred.
I already tried this, too:
vendor: ['jquery', 'bootstrap'],
  plugins: [
   // set shortcuts as global for bootstrap
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery'
    })
],

it works, but 'jQuery requires a window with a document' error appears.
This is my code:
//nuxt.config.js

const webpack = require('webpack');

module.exports = {
  /*
  ** Headers of the page
  */
  head: {
    title: 'nuxt_test_d',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Nuxt.js project' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ],
    script: [
      {
        src: 'http://code.jquery.com/jquery-latest.min.js'
      }
    ]
  },
  /*
  ** Customize the progress bar color
  */
  loading: { color: '#3B8070' },
  /*
  ** Build configuration
  */
  build: {
    // vendor: ['jquery'],
    /*
    ** Run ESLint on save
    */
    vendor: ['jquery', 'bootstrap'],
    plugins: [
      // set shortcuts as global for bootstrap
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
      })
    ],
    extend (config, { isDev, isClient }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  }
}

//index.vue

<template>

ID

            <input type="text" id="id" class="id input_tag" name="id" onchange="login_id(this)"/>

PW

            <input type="password" id="pw" class="pw input_tag" name="pw" onchange="login_pw(this)"/>

</template>

How can I solve this problem, and use jQuery in Nuxt.js?
Comment: Don't use jQuery.simple as that. Use bootstrap-vue
Answer: As Nuxt also renders on the Server you can't use JS that relies on window because on server render it's not available.
Put your jQuery scripts into the mounted() hook.
Check this guide https://www.encode8.com/js/guide-to-integrate-jquery-in-nuxt to see a example.


Clear views cache on specific node

Question: I want to clear the cache of specific node's view. In my database in cache_views_data table I found the cid of my view and the format is like
"views_name:display:hash" but I cannot find this hash where is reffering to.
Answer: Here's how you can clear cache of specific view:
<code>cache_clear_all('ctools_export:views_view:' . $NAME_OF_YOUR_VIEW, 'cache_views', TRUE);
cache_clear_all($NAME_OF_YOUR_VIEW, 'cache_views_data', TRUE);
</code>
Comment: What do you mean "only for one node"? Is this a particular block (i.e. display in views), or you mean one node *within* a view? If it's the latter, you can't do that I think.
Comment: No, I do not want to clear all the view's cache. I want to clear the view's cache but only for one node.

Clear views cache on specific node


How to implement getch() function of C in Linux?

Question: In TurboC++, I can use the getch() function from conio.h. But in Linux, gcc doesn't provide conio.h. How can I get the functionality of getch()?
Comment: turbo c is dead.Don't use it.
Comment: Possible duplicate of [Linux Equivalent for conio.h getch()](https://stackoverflow.com/questions/34474627/linux-equivalent-for-conio-h-getch)
Answer: Try this conio.h file:
#include <termios.h>
#include <unistd.h>
#include <stdio.h>

/* reads from keypress, doesn't echo */
int getch(void)
{
    struct termios oldattr, newattr;
    int ch;
    tcgetattr( STDIN_FILENO, &oldattr );
    newattr = oldattr;
    newattr.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
    return ch;
}

/* reads from keypress, echoes */
int getche(void)
{
    struct termios oldattr, newattr;
    int ch;
    tcgetattr( STDIN_FILENO, &oldattr );
    newattr = oldattr;
    newattr.c_lflag &= ~( ICANON );
    tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
    return ch;
}

You can also use the ncurses library in gcc for some functions similar to conio.h.
Comment: Is the `ICANON` flag really required? What is its effect?
Answer: If echoing to the screen is not a problem, you could try using getchar() from stdio.h.
Comment: Echoing to the screen is not the only difference between `getch()` and `getchar()`. `getch()` doesn't wait for a carriage return before being reading from the buffer. E.g. to input 'a' using `getchar()`, you have to type `a[ENTER]`. With `getch()`, you only need type 'a'.
Answer: Check out curses:
http://en.wikipedia.org/wiki/Curses_%28programming_library%29
Comment: I downvoted this because it's a link only answer, and, in its current form, it should probably rather be a comment than an answer. While this may actually be a relevant link, I'd upvote, if you'd actually add a paragraph of text directly to your post, about the curses library and why you think it is relevant to solve the OPs problem.
Comment: @Isaac If you're using one part of `conio.h` then you're probably using others. And of you're porting an application that uses `conio.h` heavily, curses is probably the best choice. I think the downvote is more along the lines of the answer looking link-only.
Comment: Maybe people see that as an overkill
Comment: Agreed, the downvote is unjustified - curses actually provides a `getch()` function.
Answer: getch() seems to be included in curses library.
Answer: According to these solution code you must manually use open source code for getch() and getche() function as described the code is as following .
#include <termios.h>
#include <stdio.h>

static struct termios old, new;

/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  new = old; /* make new settings same as old settings */
  new.c_lflag &= ~ICANON; /* disable buffered i/o */
  new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
  tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void)
{
  tcsetattr(0, TCSANOW, &old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
  char ch;
  initTermios(echo);
  ch = getchar();
  resetTermios();
  return ch;
}

/* Read 1 character without echo */
char getch(void)
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void)
{
  return getch_(1);
}

Just put it before your main method of code
Answer: If, for any reasons, you can't use curses, try this:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
# include <termios.h>

/* get a single char from stdin    */
int getch(void)
{
   struct termios oldattr, newattr;
   int ch;
   tcgetattr(0, &oldattr);
   newattr=oldattr;
   newattr.c_lflag &= ~( ICANON | ECHO );
   tcsetattr( 0, TCSANOW, &newattr);
   ch=getchar();
   tcsetattr(0, TCSANOW, &oldattr);
   return(ch);
}

Answer: In Unix, getch() is part of the ncurses library. But I wrote a workaround for this question that lets you use getch-like functionality without the rest of the curses baggage.
Answer: conio.h is only in Dos,
for linux, use
sudo apt-get install libncurses-dev

& then
-lncurses

// In IDE, you have to link it:
for example: codeblocks, Setting -> Compiler -> Linker setting, and add 'ncurses'
Answer: getch() is in libcurses. the use of curses is a bit more complex because it has deep links to the underlying terminal and has to be initialized. a working example for curses getch() with initialization of libcurses is in getchar() returns the same value (27) for up and down arrow keys
Answer: You can use getch() equivalent from libcaca:
__extern int caca_conio_getch (void)

Answer: You can also use system command to control the terminal in linux like this
char getch()    {

        char c;

        system("stty raw -echo");

        c = getchar();

        system("stty -raw echo");

        return c;

}

This function does not requires the user to press enter and takes input from the user without echoing It requires you to add stdlib.h library to your code
Note : This function is only applicable to UNIX-based OS
Any improvements or pointing out any issues in the code will be appreciated
Regards
Comment: Although technically it works, the "system" and dependency on a utility is just an affront to my senses; see https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html
Answer: If you want to use conio.h on Ubuntu, then follow these steps:-

Open terminal
sudo apt-get install git
git clone https://github.com/zoelabbb/conio.h.git
cd conio.h
sudo mv conio.h /usr/include/
Close your IDE and open again. Done.

If you are in trouble then follow this link: enter link description here


Accessing VMWare Management Network from a different subnet

Question: Here's the scenario...
We've got a VSphere ESXi 5 box running on a 9.x subnet, our office runs from the 1.x subnet. We can access the VM's running on the box without issue (which also have 9.x IP's) however we can ping the management network interface for the VM box but can't either browse to the box http/https nor use VSphere client to connect to it. The connection just times out. We have a VPN connection between the two subnets and have checked both firewalls and nothing is being blocked (which is also supported by the fact that all traffic can pass to/from the VM's).
Is there a setting within VMWare that restricts management traffic by default, to its local subnet? It would make sense for that to be the case...but I can't find any options within VSphere client. The default gateway is definitely correct for the management network, again supported by the fact that we can ping and get a response from its IP from our 1.x network.
If anyone has any suggestions, they would be kindly appreciated!
Thank you!
Comment: Perhaps if you articulate exactly what IP addresses and netmasks both the server and the system you are attempting to connect from have, along with their default routes, we might be able to better assist in troubleshooting.
Answer: This isn't anything whatsoever to do with vSphere, it's a simple Layer 3 routing issue, get some working routing in place, that's it.
Comment: All traffic between the two subnets including L3 is routing fine, apart from traffic to/from the VMWare management network. Surely if it was a L3 routing issue at the firewalls nothing (L3) would be able to traverse the connection?
Comment: Does no one have any other thoughts on this? I don't think it's a layer 3 routing issue as all traffic is routed between the two subnets...it's literally just managing this VMWare box that is causing us problems.
Comment: It's not a terribly clearly-written question to be honest - have you tried connecting from inside the same vlan? that'll tell you if it's a server or network issue right?
Comment: My apologies...everything within the same VLAN works fine (incl VMWare Mgmt). Everything between VLAN's works fine...APART from connecting to the VMWare management network. We can connect fine to other hosts on that VLAN/subnet without issue. The only thing we can't access on that particular VLAN is the VMWare Management Network...servers on that VLAN can be accessed fine. Not sure if that makes it any clearer? If we were having other L3 issues when accessing this subnet I would agree that it points towards routing, but it's literally just VMWare
Comment: Right, so it all works inside the same vlan, have you checked the netmask & gateway on your esxi server? maybe it's not right and it's not got a valid way out of that vlan? other than that I guess it's just a basic L2/L3 routing/firewall/client config issue - there's no option in esxi to just allow connections from its own vlan, unless the netmask/gateway is wrong.
Comment: I'm afraid so, that was my first guess. Gateway and subnet mask are both correct; it does seem odd that I can ping that interface. Everything is routed as it should be by the looks of the firewalls which is just routing everything over the VPN to our office.
Answer: I know this is an old thread, but I've seen this problem before and wanted to help any other vsphere admins who run into the same issue. When you can manage the esxi environment from the local subnet but not from a remote, the trouble is going to be a layer 3 or higher issue. Since other traffic can traverse from one subnet to another you know the problem isn't in the router or firewalls in between. So the problem must be on the esxi device. The situation you have described can easily occur if a VKERNAL adapter is set up to belong do a different IP range than is correct. You can verify this easily by navigating to Host -> Manage -> Networking -> TCP/IP configuration _> IPv4 routing table. If you see that the host is trying to locally route (gateway 0.0.0.0) to a subnet that it is not a part of then you have found your culprit. Track down the vkernal adapter that is misconfigured and get it configured correctly!
Answer: @Jacob Maron. This was exactly the problem. THANKS
In my case, there was not gateway configured.thats why I could access it on the same network but not any other network (vpn, for example).
Right Click on the Host>Configuration>Networking>Properties>Management Network (you may have renamed your mgmt network something else)>Edit>Check the default gateway and subnet mask.
Comment: Yup this fixed my problem as well vSphere --> Host Configuration --> Networking -->(vSwitch with Management Network VMkernel Port) vSwitch0 --> Properties --> Management Network --> Edit… --> IP Settings --> VMkernel Default Gateway --> Edit… --> Gateway IP
Answer: If it's not a layer 3 and the gateway is defined - Even though the IP settings look correct, select static and review (edit the gateway) then click okay, that will get it to respond.


WebService - xsd:Date field

Question: I'm creating a webservice for a customer in ASP.Net v3.5.
Currently, we have the an object similar to the following that gets returned by one of the webservice methods:
public class blah
{
 public DateTime datetime;
 public int someData;
}

Now, the customer has sent me the following request:

In your schema you have a single entry for a xsd:dateTime. Can you
  split that into two fields one for date and the other for time. The
  use of a xsd:date and xsd:time should be fine as the object types.

Obviously, I can alter the class as follows:
public class blah
{
 public DateTime date;
 public DateTime time;
 public int someData;
}

But I assume that will actually produce two fields of "xsd:DateTime" and not one of each as he is requesting.
Please can you advise how I would achieve the results my customer is expecting?
Answer: In .NET there is no Time object, this is part of the DateTime object.
I would go on having two strings objects instead
public class blah
{
    public string date;
    public string time;
    public int someData;
}

and then parse them into a DateTime object soon you get them
DateTime dateOut;
if(DateTime.TryParseExact(
          string.Format("{0} {1}", date, time),
          "yyyy-MM-dd HH:mm",
          null,
          System.Globalization.DateTimeStyles.None,
          out dateOut))
{
   // date is valid
}
else
{
    // send error back saying that DATE or/and Time needs to follow a pattern
}

To make a property assume a specific type you can decorate with:
public class blah
{
    [XmlElement(DataType = "Date")]
    public string date;
    [XmlElement(DataType = "Time")]
    public string time;
    public int someData;
}

but there are forums that .NET has some problems with this... give it a try and test it your own using Fiddler for example to simulate a call to your service.
Comment: but how do I provide the "xsd:Date" and "xsd:Time" object types in the WDSL / SOAP that the client requires?
Comment: .NET does not output such type. PHP or Java do. Even you override, you can get in trouble. Answer edited for this.
Comment: I know .Net doesn't have a "Time" type, but there has to be a way of telling the client you are expecting as "XSD:Time" type? Obviously, internally we could have that as a string...
Answer: public class Blah
{
 [System.Xml.Serialization.XmlElement(Namespace="http://www.w3.org/2001/XMLSchema", DataType="time")]
 public DateTime time;

 [System.Xml.Serialization.XmlElement(Namespace="http://www.w3.org/2001/XMLSchema", DataType="time")]
 public DateTime date;

 public int someData
}

This seems to be exactly what I'm looking for!

WebService - xsd:Date field


How to display the rendered entity of the user's profile with comments?

Question: I installed the modules "Twig tweak" and "Profile"
In the comment twig, I want to display the rendered entity of the profile ("personnel" type and "teaser" display). I tried this :
{{ drupal_entity('profile', comment.uid.target_id, 'teaser') }}

But it does not work.
The goal is to view the author's profile, not are user account.
{#
/**
 * @file
 * Default theme implementation for comments.
 *
 * Available variables:
 * - author: Comment author. Can be a link or plain text.
 * - content: The content-related items for the comment display. Use
 *   {{ content }} to print them all, or print a subset such as
 *   {{ content.field_example }}. Use the following code to temporarily suppress
 *   the printing of a given child element:
 *   @code
 *   {{ content|without('field_example') }}
 *   @endcode
 * - created: Formatted date and time for when the comment was created.
 *   Preprocess functions can reformat it by calling format_date() with the
 *   desired parameters on the 'comment.created' variable.
 * - changed: Formatted date and time for when the comment was last changed.
 *   Preprocess functions can reformat it by calling format_date() with the
 *   desired parameters on the 'comment.changed' variable.
 * - permalink: Comment permalink.
 * - submitted: Submission information created from author and created
 *   during template_preprocess_comment().
 * - user_picture: The comment author's profile picture.
 * - status: Comment status. Possible values are:
 *   unpublished, published, or preview.
 * - title: Comment title, linked to the comment.
 * - attributes: HTML attributes for the containing element.
 *   The attributes.class may contain one or more of the following classes:
 *   - comment: The current template type; for instance, 'theming hook'.
 *   - by-anonymous: Comment by an unregistered user.
 *   - by-{entity-type}-author: Comment by the author of the parent entity,
 *     eg. by-node-author.
 *   - preview: When previewing a new or edited comment.
 *   The following applies only to viewers who are registered users:
 *   - unpublished: An unpublished comment visible only to administrators.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 * - content_attributes: List of classes for the styling of the comment content.
 * - title_attributes: Same as attributes, except applied to the main title
 *   tag that appears in the template.
 * - threaded: A flag indicating whether the comments are threaded or not.
 *
 * These variables are provided to give context about the parent comment (if
 * any):
 * - comment_parent: Full parent comment entity (if any).
 * - parent_author: Equivalent to author for the parent comment.
 * - parent_created: Equivalent to created for the parent comment.
 * - parent_changed: Equivalent to changed for the parent comment.
 * - parent_title: Equivalent to title for the parent comment.
 * - parent_permalink: Equivalent to permalink for the parent comment.
 * - parent: A text string of parent comment submission information created from
 *   'parent_author' and 'parent_created' during template_preprocess_comment().
 *   This information is presented to help screen readers follow lengthy
 *   discussion threads. You can hide this from sighted users using the class
 *   visually-hidden.
 *
 * These two variables are provided for context:
 * - comment: Full comment object.
 * - entity: Entity the comments are attached to.
 *
 * @see template_preprocess_comment()
 *
 * @ingroup themeable
 */
#}

      {{ drupal_entity('profile', comment.uid.target_id, 'teaser') }}
      {{ created }}

     {{ content.field_article_commentaire }}
     {{ content.links }}
     {{ content.flag_report_comment }}

On the "compact" view of the user, a profile field appears.
How to display in twig, the url of the profile?
I want the image and the user name to point to his profile (not to his account).
Answer: If I understand you correctly. You can render profile entity using Twig tweak
{{ drupal_entity('profile', comment.uid.entity.personal_profile.target_id) }}

FYI : The first Parameter for drupal_entity function is the entity type, Then id of the entity, then view mode. See TwigExtension.php file in twig_tweak/src folder

public function drupalEntity($entity_type, $id = NULL, $view_mode = NULL, $langcode = NULL, $check_access = TRUE)

Its better to install Devel module and then you can use kint() for debugging the variables
Comment: Finally I will display the rendered entity of the user, it will be easier. There is a field that appears on the display from the user to the profile. How to display the profile url on the user account? I updated my question
Comment: Replace `field_profile` with the machine name of field. I have updated the answer assuming field name `field_profil_personnel`. **PS :** When you render it `profile.html.twig` TEMPLATE is rendered.
Comment: It does not work. I would like to display the url of the profile (personnal_profile) of the author of the comment. A field (personal_profile) is present in the user's teaser display (see the last screenshot of my question)
. How to retrieve the url of the profile in the user account from the comment twig ?
Comment: profil_personnel is not a field but a type of profile
Comment: I opened a question to display the profile url https://drupal.stackexchange.com/questions/260148/how-to-display-the-profile-url-in-the-user-view
Comment: I am assuming the field name as `personal_profile` that links the user account with the `profile` Entity. I have updated the code @drup8.


Differentiating Spitzer's identity

Question: Let $(S_n)$ be an arbitrary random walk. Define $$M_n:= \max(0,S_1,...,S_n)$$ and $$S_n^{+} := \max\{0,S_n\}.$$
Spitzer's identity states that for $0<r<1$, we have
$$\sum_{n=0}^{\infty} r^n E(e^{itM_n}) = \exp \left( \sum_{n=1}^{\infty} \frac{r^n}{n} E(e^{itS_n^{+}}) \right) .$$
By differentiating I am supposed to show that
$$E(M_n) = \sum_{k=1}^n \frac{1}{k} E(S_k^{+}). $$
However, differentiating with respect to $t$ and putting $t=0$ gives me
$$(1-r)\sum_{n=0}^{\infty} r^n E(M_n) = \sum_{n=1}^{\infty} \frac{r^n}{n} E(S_n^{+}).$$
I cannot see how to get the required result from this.
Many thanks for your help.
Answer: Denote $a_n:=\mathbb E[M_n]$ and $b_n:=\mathbb E[S_n^+ ]/n$. The LHS is
$$\sum_{n=0}^\infty r^na_n-\sum_{n=1}^\infty r^na_{n-1}=a_0+\sum_{n=1}^\infty r^n(a_n-a_{n-1}).$$
By identification of the coefficients of power series, we derive that for each $n\geqslant 1$,
$$a_n-a_{n-1}=b_n,\quad a_0=0,  $$
from which the wanted formula follows.

Differentiating Spitzer's identity


Image não contém uma definição para FromStream

Question: Estou usando um método para converter um array de bytes de uma imagem no banco dados em uma imagem porem o código diz que Image não contem uma definição para FromStream().
private Image ConversaoByteparaImagem(byte[] arraybytes)
    {
        MemoryStream ms = new MemoryStream(arraybytes);
        Image imagem = Image.FromStream(ms);
        return imagem;
    }

Linha onde ocorre o erro:
Image imagem = Image.FromStream(ms);

Comment: O erro é bem claro. Qual o namespace de `Image`?
Comment: ```System.Windows.Controls```
Answer: De fato esta classe não tem o método FromStream() conforme mostra a documentação. Precisaria ver o que quer fazer e achar outra solução, mas o erro é claro e isto não pode ser feito. Já a classe do Windows Forms tem esse método, conforme documentação. Se usá-lo então dá para fazer o que deseja, porém não posso afirmar que é uma boa solução (pode funcionar, mas só entendendo o problema em detalhes para analisar). Usando assim deveria resolver o problema específico (mesmo que cause algum outro):
using System.Drawing;

provavelmente no lugar de:
using System.Windows.Controls;

Não está funcionando por outros motivos (não tem um dado válido, mas o erro que afirma ter não acontece com o namespace correto), assim:
using System.IO;
using System.Drawing;

public class Program {
    public static void Main() {
        Image.FromStream(new MemoryStream(new byte[1024]));
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Comment: @LINQ de fato deve ser isso, coloquei exemplo mostrando "funcionando" já que ele afirma que o erro persiste.
Comment: Provavelmente ele está confundindo com a classe `Image` da `System.Drawing`.
Comment: Tentei usar com System.Drawing e ele nem sequer reconhece o Image
Comment: tentei o novo codigo mas ele continua dizendo que não contem uma definição
Comment: Eu mostrei funcionando, você não está fazendo o que eu fiz.
Comment: estou fazendo, usei o codigo junto com os namespaces e ainda assim ele continua a informar que não possui definição para FileStream
Comment: Então use o `FromStream()` que era o que você queria usar.
Comment: pelo visto o erro era com a IDE,eu reiniciei o programa e estava sem erros


Ajax in textfield adding extra div in markup

Question: I have created a form using a custom module. I am working on ajax functionality and updating markup when user enter text in textfield of the form.
Creating form in module
/**
 * Implements hook_form().
 */

  $form['name'] = array(
    '#type' => 'textfield',
    '#description' => 'Enter your name',
    '#title' => 'Name',
    '#size' => 50,
    '#ajax' => array(
        'callback' => 'custom_print_ajax_name_callback',
        'wrapper' => 'custom-print-name',
        'method' => 'replace',
  ),
  );

  $form['name_msg'] = array(
    '#type' => 'item',
    '#markup' => (!empty($form_state['input']['name']) ? $form_state['input']['name'] : ''),
    '#prefix' => '
',
    '#suffix' => '
',

  );

Ajax submit callback:
/**
 * Ajax callback
 */
function custom_print_ajax_name_callback($form, &$form_state) {

  return $form['name_msg'];
}

Everything is working correctly except that when I checked HTML of the page, an extra div is added in HTML of markup after updating ajax as shown in below image.
I do not have any idea why is this extra div rendering with markup.
Thanks in advance.
Comment: What's in `custom_print_ajax_name_callback`?
Comment: Its returning the `return $form['name_msg'];`. I have already added function `custom_print_ajax_name_callback()` in question.
Comment: ok, and how do you know it's AJAX's fault? And not some module theming issue? Also things like that you should inspect using source, firebug shows DOM tree as browser understood it, not as you rendered it to HTML.
Comment: I'd debug `item` type theme function as I don't know about it. I couldn't find any information about it anywhere..
Comment: @Mołot, I am working on fresh `drupal` installation and using default theme and I have checked `html` before `ajax` and after `ajax` and I only get extra 'div' after `ajax` call. I have also checked source of html, as I am using, so it did not show any update html.
Comment: @xurshid29, I had also `debug` and I also did not find anything. I am sure that I am missing something but not idea.
Comment: @Molot, I have checked with `ajax example` module and I found same issue there. So, I think, it issue with `ajax`.
Comment: @JayendraKainthola if you have the same issue with Examples, the very module that was tested by literally hundreds of developers, I can bet dollars to doughnuts that it is *not* issue with AJAX itself, or with implementation (Examples are way too simple and too thoroughly tested), but with some 3rd party, like theme or module you are using. Or it's on the browser side? Well, maybe there is some regression with Core's AJAX, but I have some up-to-date environments and I never noticed it.
Comment: @Mołot, I will also look into this into other environment. I also faced this issue first time, so looking into more into this. I know that this is not a big issue but this can effect the designing.
Comment: Big or no, it is an interesting issue. I simply think you probably blame wrong part of your setup.
Comment: @Mołot, I am simply trying to find a reason why this issue arise.
Answer: I have checked ajax.js in Drupal site and I have found that extra div is added as ajax wraps new content inside an empty div after a successful ajax request.
Comment Mentioned in ajax.js:

We don't know what response.data contains: it might be a string of
  text without HTML, so don't rely on jQuery correctly iterpreting
  $(response.data) as new HTML rather than a CSS selector. Also, if
  response.data contains top-level text nodes, they get lost with either
  $(response.data) or $('

').replaceWith(response.data).

Code:
var new_content_wrapped = $('

').html(response.data);
var new_content = new_content_wrapped.contents();

Check this also.
Comment: Sorry, Jayendra is wrong. The extra div is added as a container for drupal status messages. Check out includes/ajax.inc line 549 in 7.26: Add the status messages inside the new content's wrapper element, so that on subsequent Ajax requests, it is treated as old content.


NPM - Error: Cannot find module '../'

Question: I'm reading this doc on hapi-auth-cookie and trying to run sample server.here is what i did :
1-putting sample server in server.js
2-npm init
3-node server.js
4-npm install --save hapi
5-node server.js but this time i get a new error
Error: Cannot find module '../'
somewhere in the code it's requiring '../'
server.register(require('../'), (err) => {

    if (err) {
        throw err;
    }

But i don't understand this part really.you can see the full code in the link above.what should i do? thanks
Comment: Looking at the link you posted, the index.js file of that module is in the /lib directory and usually you want to import a module by name in the npm construct
Comment: i think you are right and might need to post it as the answer.i will work on it,
Answer: I had the same error. I just deleted the node_modules directory and rerun install.
rm -rf node_modules/
npm install

After that the app runs correct again.
Comment: same here. any idea why that is?
Answer: Maybe there isn't a index.js file in directory ../.
Answer: Looking at the link you posted, the index.js file of that module is in the /lib (https://github.com/hapijs/hapi-auth-cookie/tree/master/lib) directory and usually you want to import a module by name in the npm construct.
So put your server.js in /lib
Comment: It is possible to `require` a folder? What exactly does that? Or did I misunderstand your answer?
Comment: I might be understanding as well, but in npm if you want to require hapi you'd want to write the line `var hapi = require('hapi');` instead of requiring a specific file within a module after installing.
Comment: Yea, exactly, what surprises me is the line in the example of hapi where they have that `server.register(require('../'))`. I first thought that you have to replace it with something, but that wouldnt really be an example.
Answer: You can replace
server.register(require('../'), (err) => {

with
server.register(require('hapi-auth-cookie'), (err) => {

and be sure to run
npm i -S hapi-auth-cookie

and
npm i -S hapi

before you start your server

NPM - Error: Cannot find module '../'


How to alter an existing Views display?

Question: I know in order to create views displays you simply declare it as:
  $view = views_get_view('AN_EXISING_VIEW', TRUE);

  $handler = $view->new_display('page', 'YOUR_DISPLAY_NAME', 'YOUR_DISPLAY_MACHINE_NAME');
  $handler->display->display_options['title'] = 'TITLE';
  ...
  views_save_view($view);

You can do this in hook_enable in your install file or using hook_views_default_views
All I need is however to programatically alter an existing view display of a Workbench Moderation module (workbench_moderation): 'YOUR_DISPLAY_NAME' and 'DEFAULT' in order add other fields and permissions on those fields.
My questions are:

How do I effectivelly get the specific display: e.g. $views->get_display?
How do I save it so that will not mess the views caches?
Comment: I have impression that there are to many questions here, really. And do you want to alter view provided by another module (allowing user to alter your alterations), or override what user edited?
Comment: @Mołot, I have reedited for better understanding, yes I need to alter the view provided by workbench_moderation by adding fields to its display.
Comment: Do you need to do that after the query executed or do you need to alter the query as well?
Comment: Drupont seems to be the exact use case provided as an example on API page. Hope my answer is what you have in mind. Anyway I'm still a bit unclear if that's what you meant, and it seems @ЕлинЙ. share some of my doubts, so please confirm or clarify again.
Answer: Views provided by a module are defined using hook_views_default_views - and as almost anything, they can be modified using "alter" version of this hook, namely hook_views_default_views_alter:
Alter default views defined by other modules.

This hook is called right before all default views are cached to the database. It takes a keyed array of views by reference.
Example usage to add a field to a view:

$handler =& $view->display['DISPLAY_ID']->handler;
// Add the user name field to the view.
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = 'Author';
$handler->display->display_options['fields']['name']['link_to_user'] = 1;

Source code from API help page linked above.
Comment: @Drupont They are called on install, really - as you are modifying default views, there is no need to call them repeatedly, they are needed only once and then there is view cached in views' cache and that's all to it ;)

How to alter an existing Views display?


Continuous Music Theory

Question: Is there a musical theory of harmony or a system of chord-understanding that does not rely on the 12-tone temperament?
For example, a fretless instrument has (theoretically) an infinity of tones between one note and the next.  Thus, the concept of note becomes blurry and the point of interest becomes the interval (or frequency-distance) between tones.
Therefore, I am curious if there is a (more-or-less magical) conjoined theory that works on a continuous (or non-quantized temperament).
If not, is there any research or have there been past attempts at a system ?
Comment: Look up Microtonal music. The subject is too vast for a real answer. I offer the music of Harry Partch as one of many many varied and vastly different examples along this subject. This includes some music that is ethnomusicological as well as new made up systems and theories of music.
Answer: It depends on how you define the 12-tone octave.
Up until at least the 19th century, several theories did not use equal temperament to conceptualize musical space. Imagine that you ascend from C by perfect fifth; if you do this twelve times in equal temperament, you will end on a C that is perfectly in tune with the original starting C. If, however, you do this in just intonation, your final C will be considerably higher than your original C. In this sense, these theories did in fact have "an infinity of tones between one note and the next." As a good starter on this, maybe check out the Tonnetze by Oettingen and Riemann.
More recently, you can look at analyses and theories of microtonal and spectral music.
But in both cases, these are based off of the 12-tone octave, just with gradations between the pitches.
In terms of a "more-or-less magical" conjoined theory...I'm not sure I can help there.
Answer:
theory that works on a continuous (or non-quantized octave).

In musique concrète, the theoretical framework is audio waveforms, not octaves or tunings or scales. You're not limited to a system of writing down musical notes so that the next person can play them on a standard instrument with a standard octave and standard tuning, because you write down musique concrète with an audio recorder. You just write down the audio itself.

a fretless instrument has (theoretically) an infinity of tones between one note and the next. Thus, the concept of note becomes blurry

That is a musique concrète way of looking at a fretless instrument: based on the infinity of sounds you can make with it, not the particular set of standard notes or tunings you can use it to play from a score. You could also rattle the bass, strike the body of the bass, interfere electromagnetically with the pickups, use any number of effects processors. Anything that makes a sound that you can record.
Musique concrète — Wikipedia
Comment: [Musique concrète](http://www.britannica.com/art/musique-concrete) is using everyday sounds to compose music, you wouldn't use recordings of instruments as that would defeat the purpose of it. Also it's a composition technique not a theoretical system.
Comment: @Dom I got the impression that any sound is valid in a concrète piece, including vocal or instrumental sounds (e.g. the piano and singing in *Cinq études de bruits* by Pierre Schaeffer). I thought the key point of concrète is an emphasis on the music being defined by actual ('concrete') recorded sound, rather than the tradition of instrumentalists rendering a (definitive) score.
Comment: @topomorto you wouldn't just throw samples of a song together and call it musique concrète. The recording aspect of it is why it is named that way, but the point was to use the recordings so you could have access to sounds you wouldn't have any other way espically from a performance stand point. There may be typical instruments in some musique concrète pecies, but that is not the focus of it.
Comment: @Dom true that instruments aren't a focus of music concrete - I was just saying that it's going a bit far to say that you *wouldn't* use recordings of instruments.
Answer: The octave can be split into more intervals than 12. There is 19 equal temperament, and other temperaments based on octave division into 31, 41 or 53 equal intervals.
Some 30 years ago I had to work on a mathematical problem where it was proved that some divisions were "better" than others. Better in the sense that they better approximated simple fractions.
The ear likes chords composed of notes with frequencies in simple (fractional) ratios. Hence the traditional division into 12 equal parts comes from the fact that 2^(7/12) is a good approximation of 3/2 (perfect fifth), 2^(4/12) an approximation of 5/4 (major third), and 2^(3/12) an approximation of 6/5 (minor third).
Comment: As you say.  But of course it's a tradeoff between how good the intervals you need (fifths, fourths, thirds) sound and how many divisions you need.  Twelve tone equal temperament has great fifths but only mediocre thirds; 53 TET has great fifths and thirds but a lot of notes.

Continuous Music Theory


why does elasticsearch calculates score for term queries?

Question: I want to make a simple query based on knowing a unique field value using a term query. For instance:
{
  "query": {
    "term": {
      "products.product_id": {
        "value": "Ubsdf-234kjasdf"
      }
    }
  }
}

Regarding term queries,  Elasticsearch documentation states:

Returns documents that contain an exact term in a provided field.
  You can use the term query to find documents based on a precise value such as a price, a product ID, or a username.

On the other hand, documentation also suggests that the _score is calculated for queries where relevancy matters (and is not the case for filter context which involves exact match).
I find it a bit confusing. Why does Elasticsearch calculates _score for term queries which are supposed to be concerned with exact match and not relevancy?
Answer: term queries are not analyzed, hence they would not go with the analysis phase, hence used for an exact match, but their score is still calculated when used in query context.
When you use term queries in filter context, then it means you are not searching on them, and rather doing filtering on them, hence there is no score calculated for them.
More info on query and filter context in official ES doc.
Both the example of term query in filter and query context shown in my below example
Term query in query context
{
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "title": "c"
                    }
                }
            ]
        }
    },
    "size": 10
}

And result with a score
"hits": [
            {
                "_index": "cpp",
                "_type": "_doc",
                "_id": "4",
                "_score": 0.2876821, --> notice score is calculated
                "_source": {
                    "title": "c"
                }
            }
        ]

Term query in filter context
{
    "query": {
        "bool": {
            "filter": [ --> prev cluase replaced by `filter`
                {
                    "term": {
                        "title": "c"
                    }
                }
            ]
        }
    },
    "size": 10
}

And search result with filter context
 "hits": [
            {
                "_index": "cpp",
                "_type": "_doc",
                "_id": "4",
                "_score": 0.0, --> notice score is 0.
                "_source": {
                    "title": "c"
                }
            }
        ]

Comment: how to formulate must clause with filter clause?
Comment: @Nag can you post a new question  with all the details and comment here
Answer: Filter context means that you need to wrap your term query inside a bool/filter query, like this:
{
  "query": {
    "bool": {
      "filter": {
        "term": {
          "products.product_id": {
            "value": "Ubsdf-234kjasdf"
          }
        }
      }
    }
  }
}

The above query will not compute scores.
Comment: Fair enough... Maybe @Nag didn't open it in the first place
Comment: @Opster Elasticsearch Ninja, apologies - i somehow missed your answer and directly came from google results to see the answer from Val, I will remove it.
Comment: @OpsterElasticsearchNinja Better safe than sorry... since your answer is also the same as mine ;-)
Comment: yeah, we both gave the answer at exact same time(see timestamp) with some more explaination and I was wondering why user @Nag is commenting the same link.
Comment: @Val, exactly my point, maybe you have much more reputation than me :wink  :p


glm.nb function, why do I get 2 different p values using the same variables; summary of multiple varaibles vs single variable?

Question: I get two different p values depending on how I type this formula out...
stands<-glm.nb(formula = dta$spr_sum ~ mean_CC + SC_con + SC_dec + SC_shr + mean_con_DBH + mean_dec_DBH + BA_con + BA_dec, data = dta)
summary(stands)

if I decide I don't want to summarize everything and I only pick one variable, "SC_shr", I get a different p value for the same exact variable (SC_shr) than what was listed in the summary.  WHY?!?!?!
glm.nb(formula=dta$spr_sum ~ dta$SC_shr, data=dta)

Comment: In a multivariable regression each variable is adjusted for the others. That is the point.
Answer: I'll try to expand @mdewey's comment. If an explanatory variable is well correlated with another, its effect is explained by the correlated one. This results in less precise estimates and consequently different pvalues. I believe the keyword to google for is collinearity.
Here's an example. x1 and x2 are correlated with each other ($r = 0.83$) and with the response y. Including both x1 and x2 in the model results in much less precise estimates of their coefficients and their p-values are closer to 1 compared to a model with only x1 or x2:
set.seed(1234)
x1 <- 1:50
x2 <- x1 + rnorm(n= length(x1), sd= 10)
y <- rowMeans(cbind(x1, x2)) + rnorm(n= length(x1), sd= 10)

cor(x1, x2) # 0.83
cor(x1, y)  # 0.81
cor(x2, y)  # 0.79

summary(lm(y ~ x1 + x2))

            Estimate Std. Error t value Pr(>|t|)
(Intercept)   -1.270      3.018   -0.42   0.6757
x1             0.639      0.183    3.49   0.0011 **
x2             0.458      0.172    2.66   0.0107 *

summary(lm(y ~ x1)) # Only x1

            Estimate Std. Error t value Pr(>|t|)
(Intercept)   -1.940      3.192   -0.61     0.55
x1             1.042      0.109    9.56  1.1e-12 ***

summary(lm(y ~ x2)) # Only x2

            Estimate Std. Error t value Pr(>|t|)
(Intercept)    4.571      2.787    1.64     0.11
x2             0.957      0.107    8.91  9.5e-12 ***
```

Comment: Thank you!  I am obviously very new to R and statistics!!!  Much appreciated!


phpWord file growth issue when adding images

Question: Ok, here's the scenario.  I need to generate about 200 MS Word documents based off of data collected and stored in my database.  Generating the word docs with or without photos is a user option.  After Word doc generation I then want to create a zip file of all the files generated.  The zip part is done, the word file generation for the most part is done.
When the user chooses to generate the reports without the photos, the site queries the database and returns about 200 records for the report, and then with a foreach loop I run the PHPWord coding to generate and write the files to a temp folder and then after the foreach loop I'm running code to zip them all up and then delete the temp files.  Works great.  BUT, when the option to generate the reports WITH photos is selected, it starts generating the Word docs, but the file sizes increase every time a file is created.  First file is 70k, the second file is 140k, the third is 210k and so on, where each file should only be 70k each.  The only difference in the two operations in the inclusion of the addImage commands with the table cells like so:
$table->addCell()->addImage('photos/thumb_image.jpg, $imageStyle);

Help please!
Comment: Posting more code would be helpful
Comment: I probably should add to this a bit.  If I modify the initial query that the foreach loop is based on to output only one record at a time and leave the other code exactly the same, the site generates the Word files perfectly.  AND, if I compare the files that are supposed to be the same (normal vs inflated file size), they're identical. Same text, same images, same amount of pages, etc.

I could post a boatload of code, but I've narrowed the problem to the addImage function of PHPWord.
Comment: @Bill_VA : Which version of PhpWord do you use ? It seems that the first file has one image, and the second file stores two images, and so on... Could you give us two files ?
Comment: @Bill_VA : Could you give us more code with your loop, for example ? That will help us for helping you.
Answer: Use Media::resetElements() between loops that were available since 0.10.0.


Interview: Summing numbers in two linked lists

Question: During an interview yesterday, I was asked how I would go about summing the values of two singly linked lists that contained digits. They also said the lists could be unequal lengths.
I asked if the list was stored backwards, as that's how I learned about it at uni, but they said no, it was stored forward.  They also said I couldn't simply reverse the lists, add then, then reverse it to get it forward again because that option required too much processing.  This sort of solution is all I've been able to find online.
I was unable to give an answer, even after they hinted that I should be doing this with a recursive function.
Can anyone help me out with what the solution would have been. This was for a C++ job and I'm hoping that if I ever get called back and I'm able to explain I researched the solution, they might see that as a good sign. Thank you.
For those confused about how the summation is supposed to work, it was presented in this way.
List 1: 1->2->9
List 2: 1->3
So since the numbers are stored forward, I would need to begin by adding the 9 and 3 (end of both lists).  Then take the 1 carry and do 1 + 2 + 1.  Etc.
Comment: What exactly were you supposed to calculate? l1[0]+l2[0] -> l3[0], or would it be l1[0]+l1[1]+... -> sum? I don't really get it ;)
Comment: It shows that your interviewer was stupid. Doing it recursively is at least as slow as simply counting the lists length once. Instead of reversing the lists directly, he wants to use the stack as a reverse list. If you want I can write the code, but at this point it should be quite clear.
Comment: Sounds like a C question. Why recursion???
Comment: Yeah, I'm a little confused too. What about summing two linked lists is difficult? Can't you just iterate through them and add up the numbers?
Comment: quite a vague question as there are no details given on what kind of linked list is being used, if it's an std::list, you can use std::accumulate
Comment: @cli_hlt: I'm confised by that too, I even thought the lists would represent numbers in base-10, each item being a digit.
Comment: @xanatos, if you could provide an example, that would be great. I'm confused as to if I would need two stacks.
Comment: @jpalecek Yeah that must be the case. Otherwise the question (and the partial answers to it) makes no sense.
Comment: If your interviewer had a script in mind for how you were to solve it, that script should be built into the question itself.  Otherwise he should have let you solve it however you wanted--let you get it working--and then impose additional constraints to see how you react.  Anyhoo...if you're really interested in the job for some reason, it can't hurt to send follow-up solution(s) that demonstrate good style as well as hard data on metric comparisons of alternative  methods.
Comment: Modified with a second method that uses a scratchpad but traverses only once the lists.
Answer: You count the length of both lists. You pad at the beginning the shorter list with a number of  0 digits so that they are equal in length. Now you pad both numbers with an extra 0 (it will be used by the carry of the first digits. So that it's possible that 9 + 1 = 10).
You create a third linked list of length equal to the previous two.
Now you do a class like this:
class Digit
{
    public:
    Digit *Next;
    int Dt;
}

and a function like this:
int Sum(const Digit* left, const Digit* right, Digit* runningTotal)
{
    int carry = 0;

    if (left->Next != NULL)
    {
        carry = Sum(left->Next, right->Next, runningTotal->Next);
    }

    carry += left->Dt + right->Dt;

    runningTotal->Dt = carry % 10;

    carry /= 10;

    return carry;
}

This is "version 0".
In "version 1" you remove the extra padding for the last carry and you add it only if needed.
In "version 2" you remove unnecessary "0" digits from the front of the linked lists.
In "version 3" you create the runningTotal linked list directly in Sum. You give to the first level Sum only the "Head" of the Running Total.
In "version 4" instead of padding the shorter LL, you pass a parameter on the number of digits to skip from the longest LL (this is the most difficult passage).

There is another possibility, much more complex, but that doesn't require to pre-count the length of the lists. It uses two recursive functions:
The first recursive function simply traverses left and right while both are present. If both finishes at the same time then you can simply roll-back as in the previous example.
If one of them finishes before the other, then you use another recursive function like this (the initial value of *extraDigits is 1):
void SaveRemainingDigits(const Digit *remaining, int *extraDigits, int **buffer)
{
    int currentDigit = *extraDigits - 1;

    *extraDigits = *extraDigits + 1;

    if (remaining->Next)
    {
        SaveRemainingDigits(remaining->Next, extraDigits, buffer);
    }
    else
    {
        *buffer = (int*)malloc(sizeof(int) * extraDigits);
    }

    (*buffer)[currentDigit] = remaining->Dt;
}

when this function finally returns, we have a scratchpad from where to extract the digits and the length of the scratchpad
The innermost level of our first recursive function has now to sum its current digit of the shortest linked list with the last digit of the scratchpad and put the current digit of the longest linked list in the scratchpad in place of the digit just used. Now you unroll your recursive function and you use the scratchpad as a circular array. When you finish unrolling, then you add elements to the runningTotal linked list taking them directly from the scratchpad.
As I've said, it's a little complex, but in 1-2 hours I could write it down as a program.
An example (without carry)
1 2 3 4
6 5

you recurse the first two elements. So you have
1-6 (in the first level)
2-5 (in the second level)

Now you see that the second list is finished and you use the second function.
3 (extraDigit enters as 0, is modified to 1. currentDigit = 0)
4 (extraDigit enters as 1, is modified to 2. currentDigit = 1.
   malloc of 2 elements,
   buffer[currentDigit] = 4 => buffer[1] = 4)

unroll and we return to the previous row

3 (currentDigit = 0
   buffer[currentDigit] = 3 => buffer[0] = 3)

Now we return to the previous function
2-5 (in the second level,
     with a lengthBuffer == 2,
     we set index = length(buffer) - 1
     currentDigitTotal = 5 + buffer[index] => currentDigitTotal = 5 + 4
     buffer[index] = 2 => buffer[1] = 2;
     index = (index - 1 + lengthBuffer) % lengthBuffer => index = 0

1-6 (in the first level,
     with a lengthBuffer == 2,
     index = 0,
     currentDigitTotal = 6 + buffer[index] => currentDigitTotal = 6 + 3
     buffer[index] = 1 => buffer[0] = 1;
     index = (index - 1 + lengthBuffer) % lengthBuffer => index = 1

now we exited the recursive function.
In an external function we see that we have a buffer.
We add its elements to the head of the total.

Our Linked list now is 9-9 and our buffer is 1,2 with index 1

for (int i = 0; i < lengthBuffer; i++)
{
    runningTotal.AddHead(buffer(index));
    index = (index - 1 + lengthBuffer) % lengthBuffer
}

Comment: What I'd like to know is if this explanation was clear... Is anyone able to comprehend what I've written or is it only gibberish?
Comment: The scratchpad bit was hard to follow, but what recursive description isn't?
Comment: Suppose length of L1 is 1000 and length of L2 is 200, are you going to pad 800 zeroes at the beginning of L2? Don't you think that's quite inefficient?
Comment: @Mag That was "version 0". As I've written then there are many optimizations you can do. What you want is "version 4"... But in the end this is more a theoretical problem than a practical problem.
Answer: I will approach this problem in something like this
Let's suppose the 2 lists are :
1->2->7->6->4->3  and
5->7->2
The sum is  1->2->7 + Sum(6->4->3, 5->7->2)
Now we make a function that take 2 lists of same size and returns their sum
which will be something like
list1->val + list2->val + Sum(list1->next, list2->next)

with base case if(list1->next == NULL) return list1->val+list2->val;
Note :: we can handle the carry in next pass easily or you can handle that in our sum function itself
So after all this our ans will be 1->2->7->11->11->5
then recursively do %10 and take carry and add it to previous value.
so final ans will be 1->2->8->2->1->5
Answer: I would have created a node like *head or *tail to store the address of the node that I started from, then iterate through the list making sure im not back at my start point. This doesn't require to to have to count the length of each, which sounds inefficient.
As for the recursiveness just do this check at the top of the function and return (node->value + myfunct(node->prev));  It'd be more efficient given you're doing the math once.
Answer: The lists "1, 2, 9" and "1, 3" each represent the numbers "129" and "13", in which case the sum is "142".
Using recursion

Compute the length of each list.
If the lengths differ, pad the shortest with zeroes at the beggining.
Iterate over the lists recursively, returning: a) the carry number if any, or zero otherwise, and b) the tail of the list.

In pseudocode:
def sum_lists_rec(a, b, start_a, start_b, length_a, length_b):
    """Returns a pair of two elements: carry and the tail of the list."""

    if the end of the lists:
        return (0, empty_list)

    result = sum_lists_rec(a+1, b+1, start_a+1, start_b+1, length_a, length_b)

    carry = (a[0] + b[0] + result[0]) / 10
    digit = (a[0] + b[0] + result[0]) % 10

    return (carry, [digit] ++ result[1])

def sum_lists1(a, b):
    length_a = length(a)
    length_b = length(b)

    if length_a < length_b:
        a = [0, 0, ..., (length_b - length_a)] ++ a
    else if length_b < length_a:
        b = [0, 0, ..., (length_a - length_b)] ++ b

    result = sum_lists_rec(a, b, length_a, length_b, 0, 0)

    if result[0] != 0:
        return [result[0]] ++ result[1]
    else:
        return result[1]

As an alternative, you can use a stack:

Compute the length of each list.
If the lengths differ, pad the shortest with zeroes at the beggining.
Push each digit of both lists on the stack.
Pop the stack until is empty, creating the new list.


Chomp all keys of a map (using less code)

Question: I'm trying to do something like
my %my_map = map { chomp($_) => 1 } @my_arr;

That doesn't do what I expect it to do, so I need to:
my @chomped_arr = @my_arr;
chomp @chomped_arr;
my %my_map = map { $_ => 1 } @chomped_arr;

What is the shorter way to do it?
Comment: Calling `chomp()` multiple times doesn't make sense from performance perspective, so `chomp @chomped_arr;` or `chomp(my @chomped_arr = @my_arr);` is better in that regard. Also it is good to avoid `map` when slice can do the job => `my %my_map; @my_map{@chomped_arr} = (1) x @chomped_arr;`
Comment: *"it is good to avoid map when slice can do the job"* Why do you say that?
Answer: The gotcha here is chomp modifies the variable, but doesn't return it. So it won't work in a map.
A workaround that I like is to use the r regex modifier -
my %my_map = map { s|\n||gr => 1 } @my_arr;

Which returns the modified result, but does so without altering the original (which would change @arr).
Note - the above doesn't quite chomp - it removes any linefeeds. (You can of course, stick a $ in your regex. e.g. s|\n$||r )
r regex flag is a newer feature (not that new). Can't recall OTOH which version of perl it was introduced in.
Can do it this with file handle input too :
my %stuff = map { s|\n||gr => 1 } <$fh>;

Strictly though, chomp removes $/ from the end of line so you might want
s|\Q$/\E\z||r

Which I think strictly reproduces chomp - but this might be a tradeoff of readability.
Comment: For clarity, I would modify the code snippets to use the `\n$` variant you mention, since the others aren't remotely equivalent to `chomp`.
Comment: True, but that might be more like `$/$`  may edit when I am near a proper keyboard again :)
Comment: I particularly enjoy the last edit. Reduced redability somehow has a perverse glory about it in Perl.
Answer: Problem with your map is that chomp inside modifies its argument, and returns some unrelated and usually useless value. The solution is to create temporary variable that holds copy of $_, chomp it, and then use it as key:
my %my_map = map { my $k = $_; chomp $k; $k => 1 } @my_arr;

Comment: You could also do `map { s/\n$//r => 1 }`
Comment: @HåkonHægland That doesn't take `$/` into account. In most cases it should work, though.
Answer: I suggest that the contents of your file shouldn't have been read into an array in the first place
This is a better way
my %my_map;
while ( <> ) {
    chomp;
    $my_map{$_} = 1;
}

or, if you must have the file contents in an array, then
my %my_map = do {
    chomp(my @temp = @my_arr);
    map { $_ => 1 } @temp;
};

Answer: The problem with this is that chomp doesn't return an altered value, it mutates its argument in place. One way I often like to solve this is to create a new function chomped which does work as a pure function.
sub chomped { my $v = shift; chomp $v; return $v }

You can then use that in the map
my %my_map = map { chomped($_) => 1 } @my_arr;


Where does querystring of "ui=2&view=dim&iv=amo1tqfqsw2s=ic" come from

Question: In my rails app (Rails 4.2.4 Ruby 2.1.2) I have suddenly started getting errors due to weird stuff in the url.
For example where the valid url would be :
/note/new?client_id=nnnn

The url that appears from time to time on the production server is:
/note/new?ui=2&view=dim&iv=amo1tqfqsw2s&it=ic

I have no idea where the spurious querystring is coming from.
Googling seems to come up with various pages concerning Gmail but are no help.
The browser appears to be chrome when the error occurs.
Comment: people can enter this in the browser url window or use curl. if this breaks your code you should fix your code.
Comment: Why on earth would somebody enter such a bizarre querystring in the browser? Its not the sort of thing you just make up for the fun of it! It is worth pointing out that multiple users from different geographical locations all somehow got that same querystring
Comment: Does look like the little cross that google added in labs - https://productforums.google.com/forum/#!topic/gmail/uOM5CLR9xMw. But why do you care?
Comment: I care because I dont know where it is coming from and whether it is preventing users from doing what they want to do.
Answer: I'm having the same issue, turned out people was copy/pasting from their Gmail emails into our system logs/comments (we have CKEditor for logs). So every time they were looking at those logs we receive these errors on our servers.
I've checked the log and this is content of one of them
<img alt="" class="ajz" id=":ps" src="https://mail.google.com/mail/u/0/images/cleardot.gif" style="background:url("?ui=2&view=dim&iv=amo1tqfqsw2s&it=ic")

So as you see this image background is pointing to those
ui=2&view=dim

Comment: It is definitely something to do with gmail and I suspect that it is when people past something from gmail into the editor on my web page (summmernote editor). However I cant replicate the error and I have no idea how to prevent it happening.


When is $f^{-1}(\tilde{M})$ a quasi-coherent sheaf?

Question: To be precise, I want to know whether the following statement is true or false:

Let $A$ be a ring (it can be reduced), $f:\rm{Spec}(A/I) \to \rm{Spec}(A)$ is a closed immersion, $\tilde{M}$ is a quasi-coherent sheaf of $\mathcal{O}_{\rm{Spec}(A)}$-module, is it true $f^{-1}(\tilde{M})$ is also a quasi-coherent sheaf of $\mathcal{O}_{\rm{Spec}(A/I)}$-module?
Comment: No, it is even not a module over $O_{\mathrm{Spec}(A/I)}$ in general. Actually let $F=\tilde{M}$. The stalk $f^{-1}(F)_x=F_{f(x)}$ and the RHS is not a $A/I$-module (not killed by $I$) in general.
Comment: Yes, I see. Thank you!
Answer: I think the answer depends on what exactly you mean by $f^{-1}$.
One has the usual inverse image sheaf $f^{-1} \mathcal F$.
However, in the case of $\mathcal O$-modules (where $(X,\mathcal O)$ is a scheme), one usually considers a variant of $f^{-1}$. Namely:
Let $f : X \to Y$ be any morphism of schemes and let $\mathcal F$ be a $\mathcal O_Y$-module on $Y$.
Then one defines the pullback $f^{*}\mathcal F := f^{-1}\mathcal F \otimes_{f^{-1}\mathcal O_Y} \mathcal O_X$, which is a $\mathcal O_X$-module on $X$.
Using this notion of pullback, one can show that quasi-coherent sheaves on $Y$ pull back to quasi-coherent sheaves on $X$ and also for example that rank $n$ vector bundles pull back to rank $n$ vector bundles.


Background image not covering 100% vertically

Question: Currently trying to figure out why my background image is not covering the body fully. All the css is correct from what I can see, and i've tried looking other places for help. Below is a section of the code that needs to be reviewed, as well as a screenshot of what I am seeing. There is a little white section below the clouds that can be seen, even though the cloud image as a whole should be covering it. Any ideas?
The screenshot can be found here:
<!doctype html>

      <link rel="stylesheet" type="text/css" href="css/style.css">

COMPUTER +

Services for both home, and business

The following css:
@import url(https://fonts.googleapis.com/css?family=Martel+Sans);
@import url(https://fonts.googleapis.com/css?family=Oswald);

* {
    padding: 0;
    border: 0;
    margin: 0;
    font-family: 'Martel Sans', sans-serif;
}
body {
    background-image: url( ../img/backg.jpg );
    background-position-x: center;
    background-position-y: top;
    background-position: center top;
    background-repeat: no-repeat;
    background-size: 100%;
    background-attachment: fixed;
}

/*
 __        __
 \ \      / /  _ __    __ _   _ __    _ __     ___   _ __
  \ \ /\ / /  | '__|  / _` | | '_ \  | '_ \   / _ \ | '__|
   \ V  V /   | |    | (_| | | |_) | | |_) | |  __/ | |
    \_/\_/    |_|     \__,_| | .__/  | .__/   \___| |_|
                             |_|     |_|
*/

#wrapper {
    width: 85vw;
    margin: 0 auto;
}

/*
  _   _                      _
 | | | |   ___    __ _    __| |   ___   _ __
 | |_| |  / _ \  / _` |  / _` |  / _ \ | '__|
 |  _  | |  __/ | (_| | | (_| | |  __/ | |
 |_| |_|  \___|  \__,_|  \__,_|  \___| |_|

*/

#socialmediaicons {
    width: 15%;
    margin: 0 auto;
}
#socialmediaicons img {
    width: 35px;
    padding-left: 10px;
    padding-right: 10px;
    padding-top: 15px;
}
#header {
    height: 830px;
}
#header h1 {
    text-align: center;
    font-size: 120px;
    padding-top: 25px;
    margin-top: 160px;
    letter-spacing: 5px;
    color: white;
    text-shadow: 2px 2px 2px black;
}
#header h3 {
    text-align: center;
    padding-top: 10px;
    font-size: 18px;
    padding-bottom: 10px;
    color: white;
    text-shadow: 2px 2px 2px black;
}

Answer: use background-size: cover - that does what you want
Comment: Not supported by older browsers though.
Comment: @zeropublix If the OP uses `vw` as a unit (see code in question), the browsers that support `vw` will also support `background-size: cover`...
Comment: Alright alright. Just a basic Warning that you can't have nice things in paid development .


Fusion Layer not showing data when querying against a text column

Question: https://gist.github.com/2017706
The HTML file at the gist above will successfully load the data from the referenced fusion table into a map layer, yet when I try to query against the Name column (yes I know columns are case-sensitive in queries) I get the "Data may still be loading" error displayed, yet clearing the input box to reset the layer without a query works again.
I got this to work with a small fusion table created manually, the only difference with this data is that it was imported from an Excel file.  Is there anything I'm missing?
Answer: I believe the problem falls at the following line:
select: 'Latitude,Longitude',

In a table with a 2-column location, you only need to select the one column that was marked as a Location. In this case, it appears to be your Latitude column. Try updating the above line to the following, and see if that works:
select: 'Latitude',


CDI Portable Extension for Struts 1.3?

Question: here's an idea i have been playing with for a while.
is it possible to mix CDI and Struts 1.3 ?
E.g. via a CDI Portable Extension..?
As for 'why', there are still a few projects 'out there' which are stuck on an old stack and don't have the option to switch to struts 2..
Just throwing it out there, i'm interested in your ideas =)
greetings from germany
Answer: I just committed my library to github, called struts-cdi. You should check it out.
https://github.com/reegnz/struts-cdi
It only works with Struts Actions for now, and not with ActionForms. If the need arises, I will also  try to do container managed ActionForms. :^)
Comment: *cough* well that's embarrassing considering i am an active JEE Developer.. damn beans.xml file was missing again (so easy to forget that thing)
your extension works like a breeze! i just successfully tested the usage of injection, producers and observers in a struts action. many many many thanks, now i finally got a good point to sell some migration efforts to management =D this library is exactly what i was looking for. #
Comment: damn that's nice, this is basically what I was thinking about doing after doing some digging around in the struts 1 documentation, looking for a place to hook the cdi provider into..
i definitely will give this a try!
Comment: well i just threw this into a fairly huge project and it failed with an exception "weld argument bean may not be null"
after your post i already forked your github repository, i will dig into this in the coming days and will keep you posted ;)
Comment: Even though the information you have given is very vague, I believe it might be an issue with the BeanLookup.
More precisely the action to be instantiated is not managed by CDI, therefore the Bean returned by CDI is null, and thus the BeanManager#getReference method is throwing the exception.
The CDI validation on deployment is not seeing this, since you do not inject those actions anywhere, so it doesn't need to check if they are registered or not.

tl;dr: Do not forget to add beans.xml to the archives your actions are in (WEB-INF for war, META-INF for jar files).
Answer: Stripes Injection Enricher satisfies injection points specified declaratively using standard Java EE annotations (@EJB, @Inject and @Resource).
Comment: Thanks, I will look into that one. Did I get it right that stripes is some sort of wrapper around struts?
Comment: It was based on Struts, but it's different. Inject resources in Struts 1.x is not possible because the _actions_ are not **managed** by the _container_ but by a _servlet_, in this case the `org.apache.struts.action.ActionServlet`.

CDI Portable Extension for Struts 1.3?