Can you help me find the harmony for the following melody?

Question: I've recently composed a melody and I've been struggling to find a suitable harmony for it.
For now I've got the harmony as Cm, Gm, Fm, G - Cm, G, D#aug5, Fm
Chords change every two beats.
Comment: Harmonically, the melody it doesn't go anywhere. You could harmonize the whole thing with 4 bars of C minor. Your chord sequence doesn't seem to "go anywhere" either - it seems like a "random" sequence of chords.
Comment: I'd likely switch up the chords even more often than every 2 beats (e.g. use Fm-Cm in the 3rd and 4th beats of Bar 4), but I agree with 4 bars of Cm more than the question asker's proposed harmonization. The 1st and 2nd beats of Bar 2 fit Cm a lot more strongly than Fm, as the only notes it contains are C, Eb, G, and B--and Cm is C-Eb-G, while Fm is F-Ab-C.
Comment: @dekkadeci How about Cm on the first and second beat and Fm on 3rd and G on 4th?
Answer: Schoenberg said he wouldn't give his students assignments that asked them to harmonize a given melody, because it was too hard, or add a melody to a given chord progression, because it was too easy.  Rather, melody and harmony must be conceptualized together.  Unfortunately, you are the only one who can decide on the harmony for your own melody so it can sound the way you imagine it.  If you are having difficulty figure out which chords are possibilities, you can first look at the triads and 7th chords the melody notes belong to.  Try them out and experiment to see which ones "fit" the idea in your head.


How to set font from url programmatically in Swift?

Question: How to set font from url programmatically? I have font url which I am getting from API response, like this : "https://phoenixlab.in/uploads/font/Poppins-Medium.ttf". I need to set this font in UIlabel text in Swift.
Comment: Duplicated - https://stackoverflow.com/questions/4942449/ios-programmatically-add-custom-font-during-runtime
Comment: Download the file, first?
Comment: @ElTomato After download what i need to do?
Comment: @CloudBalancing I am talking about from server url.
Answer: Your app cannot download an arbitrary font and start using it. On the contrary, all nonstandard fonts except Apple's must be included / listed in the app at review time.


Normed vector spaces and operator norm

Question: Let $T \colon V \to W$ be a linear map between normed vector spaces $(V, \parallel \cdot \parallel_V)$ and $(W,\parallel \cdot \parallel_W)$ as $$\parallel T \parallel :={\rm sup}\ \{ \parallel T(x) \parallel_W : x \in V,\ \parallel x \parallel_V = 1\}.$$

I need to show that the definitions
  $$\parallel T \parallel :={\rm sup}\ \{ \parallel T(x) \parallel_W : x \in V,\ \parallel x \parallel_V = 1\}$$
  and
  $$\parallel T \parallel :={\rm sup}\ \{ \frac{\parallel T(x) \parallel_W }{\parallel x\parallel_V} : x \in V,\ \parallel x \parallel_V \neq 0\}
$$ are equivalent.

I'm not really sure how to approach this either than to try and manipulate the $\parallel x\parallel_V$ to show that its equal to $1$ (in the case when $\parallel x\parallel_V\neq 0$)
Answer: Hint   Note that $$\| cx\|_V = |c| \| x\|_V$$
Hence $$\frac{\| Tx\|_W}{ \| x\|_V}= \left\| T\left(\frac{1}{\| x\|_V}x\right)\right\|_W$$
and $$ \left\|\frac{1}{\| x\|_V}x\right\|_V=1$$
Update
$${\rm sup} \{ \|T(x)\| |\ \| x\|=1\} \geq \| T(\frac{y}{\| y\|}) \|=\frac{\|T(y)\|}{\|y\|}$$ for any $y$.
So norm in first definition is larger than that in second
And   $${\rm sup} \{ \frac{\|T(x)\|}{\|x\|} |\ \| x\|\neq 0\} \geq {\rm sup} \{ \frac{\|T(x)\|}{\|x\|} |\ \| x\|=1\} = {\rm sup} \{ \|T(x)\| |\ \| x\|=1\} $$
So norm in second definition is larger than that in first
Comment: Thank you for your response. So from here I assume that you use this hint in the second definition of $||T||$ to show that $ ||x||_V = 1$ hence we have shown what is required?
Comment: I add some. Please check it.

Normed vector spaces and operator norm


Drupal 8 does not create path alias' valid for all languages

Question: I have a Drupal 8 multi lingual site setup using the module Pathauto to generate path alias for taxonomy terms. The alias are created form the name of the tags, which are not translated but rather are in all languages the same. So I want all those alias be valid  for all languages.
The settings page of the module Pathauto lets me either leaving all languages unselected or choose specific languages for which the created path should be valid for. But unfortunately the pathes are created only for English and do not work if a user has a different language selected.
Is that a bug, or am I not doing it correctly?
Answer: That's currently not supported.
Partially blocked by core, which also doesn't allow to create language-neutral aliases while editing nodes and then also wouldn't show them anymore. See https://www.drupal.org/node/2511968 and https://www.drupal.org/node/2689459. Once those are resolved, pathauto could follow those definitions.
Comment: Thanks for pointing this out. But this is bad news. That means you can use alias on English sites only. Or is there any work around?
Comment: You could implement some custom code to generate the aliases. And you could test my patch in the first issue, it should be ready to be committed and was already RTBC once.


Recommended resources for finding nth partial sums of series

Question: I'm working a lot with series these days, and I would like to know if there are any texts, papers, articles that might suggest a general outline for finding $n$th partial sums of convergent series.  Most of my searching turns up methods for finding the sums of geometric/telescoping/power series etc., but I'd like to know if there are any general guidelines that are followed for finding partial sums for something like $$\sum_{k=1}^{\infty}\frac{1}{k^2}$$ or $$\sum_{k=1}^{\infty}\frac{6^k}{(3^{k+1}-2^{k+1})(3^k-2^k)}$$.
I've seen solutions to both of these, and they're beautiful and unintuitive.  So I wonder what, if any, methods might be used to get an edge on finding their $n$th sums.
Aside from listing partial sums and looking for patterns, what approaches do mathematicians commonly use to solve problems like this?  Or, if listing partial sums is the best route to take, what can or should be done to improve pattern recognition?
Answer: An excellent resource for learning how do do such things is Concrete Mathematics, by Graham, Knuth and Patashnik.  Section 5.8, on Mechanical SUmmation and Gosper's method, gives a very general way to attack such problems.
However, be aware that many such partial sums have no nice closed form, even when the infinite sum does have a nice closed form.  For example, while $$\sum_1^\infty \frac1{n^2} = \frac{\pi^2}6$$ I know of no nice form for $$H_{2,k} = \sum_1^k\frac1{n^2} $$ (other than the fact that people have named this function the harmonic number of order 2).
Answer: You might like to explore (if you haven't already) the topic of Generating Functions as there is this neat result:
Given a sequence {a} with a known generating function, $GF$, then the sequence of partial sums of sequence {a} is given by;
$$GF \times \frac{1}{1-x}$$
So, for example, the Fibonacci Sequence has the the generating function,
$$\frac{x}{1-x-x^2}=0+1x+1x^2+2x^3+3x^4+5x^5+8x^6+...$$
And the partial sums of the Fibonacci Sequence has the generating function,
$$\frac{x}{(1-x)(1-x-x^2)}=0+1x+2x^2+4x^3+7x^4+12x^5+20x^6+...$$
A lot of the time, as you are only dealing with a formal power series, you do not need to worry about convergence issues. Also, you can continue to work with the sequence even when there is no closed form formula for the $n^{th}$ term, via the generating function.
In response to Mark Fischler's comment below the closed form formula for the partial sums of the Fibonacci Sequence are not that difficult to get via generating functions. To begin, use partial fractions to obtain,
$$\frac{x}{(1-x)(1-x-x^2)}=\frac{1+x}{1-x-x^2}-\frac{1}{1-x}$$
The $-\frac{1}{1-x}$ is the $-1$ on the end of Mark's formula so we can now focus on forcing the other fraction to factorise further,
$$\frac{1+x}{(1-x-x^2)}=\frac{1+x}{\big(1-\frac{1-\sqrt{5}}{2}x\big)\big(1-\frac{1+\sqrt{5}}{2}x\big)}$$
Another dose of partial fractions gets us to,
$$\frac{1+x}{(1-x-x^2)}=\frac{5+3\sqrt{5}}{10} \times \frac{1}{\big(1-\frac{1+\sqrt{5}}{2}x\big)}+\frac{5-3\sqrt{5}}{10} \times \frac{1}{\big(1-\frac{1-\sqrt{5}}{2}x\big)}$$
These are all standard bits which translate directly into the formula that Mark gives, not forgetting to add that $-1$ back in on the end.
Comment: Nice! +1 for presenting a useful approach I had not thought of!
Comment: Fine, but nowhere does the GF for the partial sum sequence $S_n = \{0,1,2,4,7,12,20,33,\ldots\}$ make it easy to see the closed form $$S_n = \left(\frac12+\frac3{10}\sqrt{5}\right)\left(\frac12(1+\sqrt{5})\right)^n + \left(\frac12-\frac3{10}\sqrt{5}\right)\left(\frac12(1-\sqrt{5})\right)^n -1$$
Comment: @Mark Fischler : It's not too bad, and all standard techniques provided care is taken with the algebra. Rather than just 'talk the talk' I've added how to get the closed form formula you give with generating functions to the bottom of my posted answer (as it was too long to go in a comment). I enjoyed writing it out and will use it as an exercise question next time I teach this topic.


The limit as $n$ approaches infinity of $n\left(a^{1/n}-1\right)$

Question: I need to know how to calculate this without using l'hospitals rule:
limit as $x$ approaches infinity of: $$x\left(a^{1/x}-1\right)$$
I saw that the answer is $\log(a)$, but I want to know how they got it.
The book implies that I should be able to find it by just using algebraic manipulation and substitution.
Comment: Perhaps [this](http://math.stackexchange.com/revisions/904484/2) link might prove itself helpful...
Answer: Notice that this is the same limit as
$$\lim_{x \to 0^+} \frac{a^x - 1}{x - 0}$$
This is one side of the definition of the derivative of $f(x) = a^x$ evaluated at $x = 0$. As $f'(x) = \ln a . a^x$ and thus $f'(0) = \ln a$, it follows that
$$\lim_{x \to 0^+} \frac{a^x - 1}{x - 0} = \ln a$$
I am all but certain there is not an evaluation of that limit using only 'algebraic manipulation and substitution', given standard definitions of the function involved.
Answer: METHOD 1:
$$\begin{align}
\lim_{x\to \infty}x(a^{1/x}-1)&=\lim_{x\to 0^{+}}\frac{a^{x}-1}{x}\tag 1\\\\
&=\lim_{x\to 0^{+}}\frac{e^{x\log a}-1}{x}\\\\
&=\lim_{x\to 0^{+}}\frac{\left(1+(\log a)x+O( x^2)\right)-1}{x}\\\\
&=\lim_{x\to 0^{+}}\left(\log a+O(x)\right)\\\\
&=\log a
\end{align}$$

METHOD 2:
Another way to do this is to substitute $y=a^x$ in $(1)$.  Then
$$\begin{align}
\lim_{x\to \infty}x(a^{1/x}-1)&=\lim_{x\to 0^{+}}\frac{a^{x}-1}{x}\\\\
&=\lim_{y\to 1^{+}}\frac{y-1}{\log y/\log a}\\\\
&=\log a\,\lim_{y\to 1^{+}}\frac{y-1}{\log y}
\end{align}$$
Noting that for $y>1$, $\frac{y-1}{y}\le\log y\le y-1$.  Then,
$$1\le\frac{y-1}{\log y}\le y$$
and the squeeze theorem does the rest!
Comment: @codeisgood I added a second method that uses substitution and standard inequalities along with the squeeze theorem.  Please let me know how I can improve my answer. I just want to give you the best answer I can.
Answer: The exponential function is a convex function, hence $x<y$ gives:
$$ e^x \leq \frac{e^y-e^x}{y-x} \leq e^{y} \tag{1}$$
and assuming $a>1$ we have:
$$ e^{0}\leq \frac{e^{x\log a}-e^0}{x\log a-0}\leq e^{x\log a}\tag{2}$$
or:
$$ \log a \leq \frac{a^x-1}{x}\leq a^x \log a \tag{3}$$
hence the claim follows by squeezing.
Answer: $\newcommand{\d}{\,\mathrm{d}}$We know: $$\log a=\int_1^a\frac{1}{x}\d x$$And the RHS is / can be defined to be a Riemann integral, which is a limit of Riemann sums over tagged partitions as the mesh of these partitions tends to zero. In particular, since the integrand is integrable, we can use any partition. Let $a>1$ - the proof is the same for $a<1$, essentially.
For every $N\in\Bbb N$ partition $[1;a]$ into $1=t_0<t_1<\cdots<t_N=a$ through $t_i:=a^{i/N}$ (similarly to this) for $0\le i\le N$. "Tag" this partition by $\xi_i:=t_{i-1}$ for $1\le i\le N$. Since the "mesh" $\max_{1\le i\le N}(t_i-t_{i-1})=a(1-a^{-1/N})\to0,\,N\to\infty$, we can say: $$\begin{align}\log a&=\lim_{N\to\infty}\sum_{i=1}^N(t_i-t_{i-1})\cdot\frac{1}{\xi_i}\\&=\lim_{N\to\infty}\sum_{i=1}^N\frac{a^{(i-1)/N}(a^{1/N}-1)}{a^{(i-1)/N}}\\&=\lim_{N\to\infty}\sum_{i=1}^N(a^{1/N}-1)\\&=\lim_{N\to\infty}N(a^{1/N}-1)\end{align}$$
Which shows the result in a nice way (I think), at least if you only care about the limit over integers. You could extend this to a result about the limit over the reals fairly straightforwardly, given the fact that $x\mapsto x(a^{1/x}-1)$ decreases in $x$ if $a>1$ (and mimic the proof in the opposite way, if $a<1$).


Sample size calculation for estimating 0 probability in finite sample binary data

Question: Nuclear storage containers were deposited some 20 years ago. Some may have a special plastisol coating left in place in areas which are to be welded. The plastisol was used for temporary storage/protection and was intended to be completely removed prior to welding. We don't have any confirmation that it was completely removed.
We have a population of 29 containers. What sample size will we need to determine (yes or no) was any platisol left in-place on any of the 29?
Comment: This looks to me to be a situation where you would really want to take a Bayesian approach. The prior will be fairly important.
Comment: The sample size is quite small, which will make it difficult to get any real confidence, particularly since you are concerned with the probability that there is *any* coating left. The problem with dividing the problem into one of square inches is that you lose a basic assumption of independence (each square inch is very much related to its neighbours) -- you can still do something without the independence assumption but your bounds get much wider. If it's an option I would consider checking all of the containers rather than use a statistical approach.
Comment: Thanks David for your advice.  First, I think the reason we are looking at a statistical approach is because we are never going to convince the customer to look at all 29, we have better luck convincing them of looking at a smaller subset.  I think we would be happy not to merely check the probability of any coating remaining but rather the probability of a small amount of coating remaining.  In this way, we could use a statistically projected small coating surface area, we could prove no adverse aging-effects due to storage for another 20 years.  If this were the case, best method to use?
Answer: This problem is not amenable to null hypothesis significance testing because tests cannot tell you the probability that all 29 containers do not have the coating. This is an estimation problem. The way to calculate sample size for estimates is based on a margin of error. The more you sample, the tighter the margin of error is. That's the way a statistician controls the confidence of their estimates.
95% CIs, however, are going to all be 0-0 using the normal approximation to the maximum likelihood estimator. A way around this is to use a median unbiased estimator. The median unbiased estimator is any value $\tilde{p}$ such that:
\begin{equation}
Pr(Y \ge n\tilde{p}) \ge 0.5 \quad \text{and} \quad Pr(Y \le n\tilde{p}) \ge 0.5
\end{equation}
The small sample size correction for discrete data suggests using a "mid-point cumulative probability function" so that the $Pr(Y=n\tilde{p})$ is scaled by 0.5. That way a single value rather than a range of values satisfies the criterion. If you use a hypergeometric probability function, you may account for the finite population. The sample size calculation is too complex to achieve by simulation or analytically, so eyeballing is warranted. Using the code below, I generate MUEs with the following halfwidths:

As expected, rather undesirable properties of highly variable estimates are generally seen until you sample a very sizable fraction of all the repositories. It is a problem probably better suited to logistics than statistics.
<code>hyperprob <- function(y, nd, nt, p, lower.tail=T, offset=0) {
  phyper(y, nt*p, nt*(1-p), nd)/2 + #dhyper does not deal with fractional gamma well
    phyper(y-lower.tail, nt*p, nt*(1-p), nd, lower.tail=lower.tail)/2 +
    offset
}

uniroot(hyperprob, c(0,1), y=y, nd=nd, nt=nt, lower.tail=F, offset=-0.5)
uniroot(hyperprob, c(0,1), y=y, nd=nd, nt=nt, lower.tail=F, offset=-0.025)
# estimate and lower are 0 if every sample is 0
upper <- uniroot(hyperprob, c(0,1), y=y, nd=nd, nt=nt, lower.tail=T, offset=-0.025)
</code>


What is the state of the art process for finding isolated communities in graphs?

Question: Is there a state of the art process to follow for finding isolated communities in graphs?
I know there are a lot of algorithms available, but I struggle to find a set of steps for preprocessing and to provide clues as to which algorithm should be used/ is most suitable to each graph at hand.
Answer: My feeling is that the Louvain method is a classical way to detect communities.
It's a bit old be you can find in the paper of Lancichinetti and Fortunato (2009) some comparisons.
If your networks are not too large, a simple modularity optimization should works (using a simulated annealing for example).
I guess that the answer will also depends on the size of graphs
Comment: Thanks for the reference, I was mainly looking for methods that could be applicable to large graphs, where by large I mean 1000 to 10000 nodes.


Remove a specific item (index) method

Question: So I have a list of phones that I add new input lines to, and I have a remove method set, for each individual row.
This is the template:

 0">
            <input class="input" type="text" formControlName="phone">

And these are my methods that are within the respective component:
get mobiles(): FormArray {
    return this.form.get("mobiles") as FormArray;
}

get stations(): FormArray {
    return this.form.get("stations") as FormArray;
}

addMobile() {
    this.mobiles.push(this.fb.group(new PhoneFormGroup()));
}

addStation() {
    this.stations.push(this.fb.group(new PhoneFormGroup()));
}

removeMobile(index: number) {
    this.mobiles.removeAt(index);
    if (this.mobiles.controls.length == 0) {
        this.addMobile();
    }
}

removeStation(index: number) {
    this.stations.removeAt(index);
    if (this.mobiles.controls.length == 0) {
        this.addStation();
    }
}

The problem here is, that whenever I click on the delete button, it deletes the first item(index[0]) from the list, and I want it to delete the specific item I have selected for deletion.
What am I doing wrong?
Answer: You don't pass index param to removeMobile function from your HTML template.

Comment: @jo1storm , there was a 10 minute restriction on that one at the specific moment, as you already know. Now it's done. :)
Comment: Yes, that was the problem there. I should pay more attention, but you know how big projects go sometimes.

Thank You!
Comment: Yes, sometimes a snippet need a quick peek from another! Welcome!
Comment: @Zooly , as you can see, from a slight read it looks like it has the `i` inside it, because of the closing `` tag. `(click)="removeMobile()">`
Comment: Indeed! Maybe not name your iterator with simple letters, but maybe something more explicit
Comment: sorry about that, didn't see the 10 minute restriction.

Remove a specific item (index) method


Grails performance test error : org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction

Question: I'm preparing for performance tests and creating new test cases.
So I was just testing one test case, running it on a server I can only access and I just got:
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction
Application I want to test is a backend. There's no view, no sessions, it's REST-like [every request contains everything needed to perform the task].
I was testing single API over and over for a single user. Request comes, service does it's work, response is sent back, I analyze the response and send another request to the same API for the same user.
As I mentioned - objects are not stored in session. Every time request comes I'm doing User.get(id from params).
Currently I'm running this app on Postgres 8.4.4. Server is quite powerful and currently has no load at all on it.
It seems to me, that I'm able to receive response from the app [server is remote], analyze it and send another request back before transaction is saved. This is quite odd.
Is there anything I'm missing here? What should I do about it?
Answer: In the end we figured out it was caused by our test tool - SoapUI. This damn thing can send 2 requests one after another. It is a documented bug, lot of talk on their forums about it.
We dumped soapui and wrote ourselves a small testing tool. Now it works like a charm.


SMB Latency Issue with Multiple Users

Question: We have a program that works by being shared over the network as a normal Windows Mapped Drive. You run the program from the mapped drive and it stores its files in flat file databases in that mapped drive and everything is supposed to work fine. In fact it used to. We ran it for many years on old hardware running Windows XP. About a year and a half ago we upgraded our machines to newer Windows 8 machines and the server to a quad core Windows 8 server with the files on an SSD. However, since then, performance has been terrible. There is noticeable multi-second latency while the program accesses the files.
To work around this I've taken the old Windows XP licenses and installed them into virtual machines on the server, and to run this one program all the new Windows 8 desktops RemoteApp into that server. It works and there's no latency.
Obviously Windows XP is retired now and I'm not happy with this system in general, even though it works, because its complicated and prone to failure every few months for cryptic reasons.
So, the question is, what could possibly be causes this latency?
Answer: I deal with a similar application, and also encountered some sites with severe performance issues after upgrading from old XP hardware to new Windows 7 hardware, especially in the early days of Windows 7.
The two things that have alleviated this in almost all cases are:

NIC settings. Make sure all client workstations NIC drivers are up to date and have interrupt moderation turned OFF if the driver offers it.
Ensure that all Windows 7 workstations are service-packed up. Then apply the   Microsoft Enterprise Hotfix Rollup to the workstations and server if applicable. This has various fixes for SMB.
Comment: I'll give that a shot as soon as I can and see what happens. It will be a few days.
Answer: Was this application coded for Windows XP?
We experienced compatibility issues with a software we use on XP after we upgraded machines to Win 7. After a newer version everything was fine.
Maybe that's what's happening with your application.
Comment: This isn't an answer. It's a question and a statement.
Comment: It was actually coded for Windows 95 (or possibly earlier), but has been continually maintained by the vendor who now claims and supports compatibility specifically with Windows 8 and 8.1.

SMB Latency Issue with Multiple Users


Auto create has_many :through record without session

Question: I can't seem to figure out how to automatically create a has_many through record without an active session.
I have two models related through a family_association model:
class Tree < ActiveRecord::Base
has_many :family_associations
has_many :families, through: :family_associations
end

class Family < ActiveRecord::Base
has_many :family_associations
has_many :trees, through: :family_associations
end

On my Show Tree view there is a button to create a new Family and passes the Tree's id as a url parameter
<%= link_to "Add Family to Tree", new_family_path(:tree_id=>@tree.id), :class => "btn btn-default" %>

FYI: I can't have a Family belongs_to Tree model because in theory a family my elect to belong to more than one tree in the future. So there is no tree_id field to pre-populate on the new Family form.
The goal is to create the Family Association record after the Family record has saved. So far I have created the associate_family helper method:
 def associate_family(tree, family)
    FamilyAssociation.create(:tree_id => tree, :family_id => family)
 end

And included the following logic in my Family controller's Create method:
    if @family.save
       associate_family(params[:tree_id], @family.id)

The association record is created but not surprisingly, the tree_id is missing. Am I going about this the right way? Is there any way to temporarily carry the tree_id url parameter from New to Create?
Answer: According to your models, I think you are trying to make a tree of families. If that is the case then I suggest you to use Ancestry gem and for more information you can see its railscast.
If you want to stick through has_many :through association and want to pass it temporarily from new to create, I have done the way you have done. I don't know other options too.


Application object recycling

Question: I have a question about application object recycling.
I do not have any access to the server configuration that i'm using (uni. server), for my project.
Every time that i'm logging to the url, an application object is created. After 20 mins if i reload it again, it appears that the object is re-constructed.
is there a way without having access to the serve iis configuration to elongate this time?
the thing is, that its loading a big index to this object, and it takes time. I want to reduce the number of times constructing the object.
cheers
Answer: Your Session or AppDomain may be idling out or the App pool is recycling.  Both can be configured but you may want to leverage a service layer instead of hosting your object in the ASP side.

Application object recycling


Extract Google Analytics UA code with Javascript

Question: How do you extract the Google Analytics UA code on a page with Javascript. Could this be done manipulating the ga function or scraping the site for the code?
Comment: Not sure what you mean by "extract the code".  How is this different from normal use of GA?
Comment: I have a number of website that I need to audit. So I'd like to collect the UA code from each.
Answer: If you are referring to the property ID, then you can access the tracking object to get the tracking ID by calling this:
ga.getAll()[0].get('trackingId')

This returns the GA property ID ("UA-XXXXX-Y").
Comment: This is great! Any idea on how to do it with the old GA?
Comment: it is better to use the snippet with callback provided by @Jakub Kriz.
Answer: I have to warn you that this way:
ga.getAll()[0].get('trackingId')

is not correct and using this is not safe. The right way is to use callback as is described here. https://stackoverflow.com/a/29150831/3489362
ga(function(tracker) {
  // very similar to internal method like ga.getAll()[0].get('clientId');
  var clientId = tracker.get('trackingId');
  // now you can pass client id to your internal system
  myInternalMeasurementProtocolSetter(clientId);
});


Attribute Error at/ 'str' object has no attribute 'makefile'

Question: I'm learning Django and got this error in my first code itself.

I was trying for just Hello world type of program using Django, everything was perfect but got this error 'str' object has no attribute 'makefile'
Comment: Post your code as text and not as images.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: You are importing HTTPResponse from somewhere (http.client?) (I guess on line 1 of your script)
django.http has only HttpResponse. Try:
def home(request):
    return HttpResponse("Hello world")


Multiple Variadic Parameter Pack for Template Class

Question: I am using variadic parameter packs for policy based class design.
template <APITypes APIType, class... Policies>
class IShader : public Policies... {

};

Policies are defined when called or with defaults if none are specified. The problem comes when I need to add another variadic parameter pack:
template <AttributeType... Attributes, APITypes APIType, class... Policies>
class IShader : public Policies... {

};

This results in the error "Template parameter pack must be the last template parameter". I am planning to use the attribute pack to change the behaviour of at least one of the policies. But I can't work out how to get two variadic parameter packs in one template class.
Comment: You could always consider something like `IShader, APIType, Policies>`
Comment: You can't. You need to rethink your template/class design.
Comment: Not even with some kind of indirection? Say a wrapper of some kind for the attribute list. Or templates of templates?
Comment: Sort of like how you can't define `void foo(int numAttributes, ..., int numPolicies, ...);`
Comment: @chris Is that how it would look when called? I tried something similar using a wrapper around the attributes but could not work out how to then either put said wrapper in the template or make the list accessible to the policy that needs it.
Comment: @James, Yes, similar to the now-provided answer
Comment: Possible duplicate of [Parameter pack must be at the end of the parameter list... When and why?](http://stackoverflow.com/questions/34940875/parameter-pack-must-be-at-the-end-of-the-parameter-list-when-and-why)
Answer: I think the simplest answer is to create template type wrappers for your parameter packs.  For example:
template <AttributeType... T>
struct Attributes {};

template <typename... T>
struct Policies {};

Then you can declare your IShader type:
template <typename... T>
class IShader;

Create your implementation as a specialization.  Note that in a specialization, you can have multiple parameter pack arguments.
template <AttributeType... AttributeList, ApiTypes APIType, typename... PolicyList>
class IShader<Attributes<AttributeList...>, ApiType, Policies<PolicyList...>>
    : public PolicyList...
{
    ...
};

Then you can even allow the user to specify the arguments in different orders (make sure you forward the constructors if doing it this way via inheritance):
template <AttributeType... AttributeList, ApiTypes APIType, typename... PolicyList>
struct IShader<ApiType, Policies<PolicyList...>, Attributes<AttributeList...>
    : public IShader<Attributes<AttributeList...>, ApiType, Policies<PolicyList...>>
{
    using IShader<Attributes<AttributeList...>, ApiType, Policies<PolicyList...>>::IShader;
};

If you're being really fancy, you can even use metaprogramming tricks to allow the arguments in any order without enumerating all orders.  This is left as an exercise to the reader.  :)
Answer: In the discussion comments you expressed a willingness to consider some kind of indirection, or "a wrapper of some kind for the attribute list".
A lightweight std::tuple-based wrapper, together with specialization, might work here:
template <typename attribute_tuple, APITypes APIType,
          typename policy_tuple> class IShader;

template <AttributeType... Attributes, APITypes APIType,
          class... Policies>
class IShader<std::tuple<Attributes...>, APIType,
              std::tuple<Policies...>> : public Policies... {

// ...

};

The goal here is to use a template instance along the lines of:
IShared<std::tuple<Attribute1, Attribute2>, APITypeFoo,
        std::tuple<Policy1, Policy2>> ishared_instance;

And cross your fingers that this is going to match the specialized template declaration, at which point both parameter packs are available for the template specialization to use, individually.
Comment: Are the tuples needed when declaring objects of the IShader class?
Comment: @James The tuples are needed, but only as a type.  No tuples are actually instantiated.
Comment: Even here `IShared, APITypeFoo,
        std::tuple> ishared_instance;`? Won't it then not use the specialization that provides the implementation, but rather the default. Could you not use the class like this `IShared ishared_instance;`?
Comment: @James Your first succeeds because the implementation is the most-specialized matching specialization.  Your latter example would fail.  The template is of three arguments.  attribute_tuple gets the first, APIType gets the second, policy_tuple gets the third.  If you don't like the look of the tuples, create your own type wrappers like in my solution in the other answer.
Comment: So the specialization does not pattern match on the template argument, i.e. `template ` but rather matches this part `class IShader, APIType,
              std::tuple>`.
Answer: Make a nested class, with each layer having one variadic pack. In essence:
template<class... ArgsA> class Wrapper {
public:
    template<class... ArgsB> class Type {
        //Here you have access to both template packs
        //...
    }
}
//Use like this:
Wrapper<int, char, long unsigned int>::Type<float, double> a;
//...

Define any function of Type outside both classes, but inside the header, or gcc will get confused.
For a more complete use case, see my answer here


What's the best way in Javascript to delete row from html table?

Question: What's the best way in Javascript to delete row from html table?
Elements  contain colspan and rowspan more 1.
Function deleteRow() in DOM doesn't take into account colspans and rowspans.
Comment: Can you clarify? How does it not take into account colspan and rowspan? http://www.jsfiddle.net/guTgd/ <-- give us an example
Comment: http://www.jsfiddle.net/guTgd/3/
Answer: It sounds like your table is collapsing because it no longer has an equal number of cells in each row. This is to be expected. You need to replace the missing cells in the affected rows.
Colspan shouldn't be an issue because its all on one row which is being deleted.  Rowspan however will impact other rows, so:
1) using getElementsByTagName, get all your td elements from your tr node (not your document), then loop through them to check for the rowspan attribute with getAttribute
2) if one of the attributes comes back as a number, you need to go through that many rows minus 1 and insert a td at the point where there would have been a rowspan accounting for the td.
If there are also colspans going on, you will need to keep a track of these to determine which column the td really is in.  You'll also have to look out for colspans in your following rows when you come to insert the new td.
3) You may need to grab the innerHTML or children nodes of the original td and store them in memory if you want to re-add the contents in the following rows, once the row is deleted the contents will also be gone.
4) once you've done that, it is now finally safe to delete the row.
Answer: If you have loaded jQuery
$('tr#id_of_the_row').remove();


How does a list in a for loop work in Python?

Question: So I have this code:
def function(b):
   a = []
   for i in range(0,len(b),2)
       a.append(b[i])
   return a

def main():
   a = [0,1,2,3,4,5,6,7,8,9,10,11]
   for i in[51,"a", 3.2]
      a = function(a)
   print a
main()

I don't understand how the for loop works with the list [51, "a", 3.2], and why with that list it prints [0, 8], but with the list[51, "a"] prints [0,4,8].
Comment: python [for loop documentation](https://docs.python.org/3/tutorial/controlflow.html)
Comment: The `[51,"a", 3.2]` is having no effect on the loop other than the fact it has 3 elements and is causing it to loop 3 times.
Comment: To learn the code step-by-step like this example, you could try this site - http://pythontutor.com/
Comment: use better variable names and do not call anythin `a` - that gets confusing very fast. You also never do anything with our outer _i_
Comment: BTW, the whole content of `function` could be replaced with `return b[::2]`
Comment: Are you aware that end of life for Python 2 was in the beginning of 2020 (and that was announced 10 years ago)? You really should switch to a recent version of Python 3.
Answer: essentially every time you call the function it will return you only the elements form the even indexes.
you then store them back into a So each time your calling the function and storing the result your halfing the list storing only those from the even indexes. That values in your list [52, "a", 3.2] are only essentially tellin ghow many times to call the function.
when you call it 3 times, you will have less results than when you call it 2 times. you can see this if you put the print in side the loop
def function(b):
   a = []
   for i in range(0,len(b),2):
       a.append(b[i])
   return a

def main():
   a = [0,1,2,3,4,5,6,7,8,9,10,11]
   for i in[51,"a", 3.2]:
      a = function(a)
      print(a)

main()

OUTPUT
[0, 2, 4, 6, 8, 10]
[0, 4, 8]
[0, 8]


Likelihood of the product of a normal cdf and pdf

Question: Suppose you had a random sample of r.vs X_i , i= 1....n . What is the likelihood of 2 * pdf(x) * cdf(x) , with pdf and cdf of the standard normal distribution?
Answer: If by likelihood you mean
$$L(\theta;x_1,\ldots,x_n) = \prod_{i=1}^n \{2 F(x_i;\theta) f(x_i;\theta)\}$$
it means that the $X_i$'s are distributed as $\max\{Y_{1i},Y_{2i}\}$, when the $Y_{ji}$'s are iid with density (pdf) $f(\cdot;\theta)$ and cumulative distribution function (cdf) $F(\cdot;\theta)$.
Comment: Thanks for the answer! Yes thats what I meant by likelihood, but when you do the expansion of it for standard normal pdf and cdf, do you obtain max{y_1i,y_2i}, if so, how did you get this?
Comment: I did not obtain the result from the likelihood itself, but from the fact that the cdf associated with the density $2 F(x;\theta) f(x;\theta)$ is $$F(x;\theta)^2=\mathbb{P}(X<x)^2=\mathbb{P}(X_1<x,X_2<x)=\mathbb{P}(\max\{X_1,X_2,\}<x)$$


Status code of HTTP response of server in Android phone is printed in the body of response

Question: I am using http://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java  for Android.
I set the response using the following code:
HttpResponse getResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
getResponse.setEntity(new StringEntity(new String("The requested resource " + target + " could not be found due to mismatch!!")));
conn.sendResponseHeader(getResponse);
conn.sendResponseEntity(getResponse);

My response in Mozilla Poster or browser has the header 404 and the response body as:
The requested resource  could not be found due to mismatch!!HTTP/1.1 200 OK

How can I get only the HTTP body String? Why am I getting HTTP/1.1 200 OK in response. I dont set this in my code. Any help is appreciated.
Comment: Please provide a link to Apache CORE.
Answer: this might help you...
 i think response  is what you need
HttpClient client = new DefaultHttpClient();

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }

        } catch (ClientProtocolException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }

Comment: I want to remove the response headers and print only the HTTP body in the browser. @ashish.n
Comment: headers = new ArrayList();
headers.add(new BasicNameValuePair("FirstName", "myName"));
you can send blank header here instead of myName you can send a blank value...
Answer: there was a problem in my defined handle() method. I was creating a new HttpResponse for each request instead of using the response passed in the
public void handle(HttpRequest request, HttpResponse response, HttpContext context)


Probability concept that distinguishes likelihood of sequences 0110101011101... and 000000000000...?

Question: Say we have a coin and want to decide if it is fair or not. We flip it many times. Consider two cases.

Say the result is a sequence like 0110101011101...
The result is 000000000000...

In the first case the assumption that the coin is fair sounds reasonable, while in the the second the coin is obviously completely biased. However, for a truly fair coin the probabilities of the two sequences are the identical. What is then the concept that distinguishes the first one as more likely? How does one quantify that?

Consider also the third case

The result is 010101010101010...

This actually does not look like a coin at all, but it seems to pass naive tests which boil down to comparing number of zeros to number of ones. Is there a sense in which it is less random then (1)? Or I have to invent a new rule if somebody gives me a more cleverly crafted sequence?
Comment: [Kolmogorov complexity](https://en.wikipedia.org/wiki/Kolmogorov_complexity) perhaps? It is the length of the smallest program that will output your result.  For something "simple" like $000000\ldots$ you can just print $0$ and loop, but for most random bit sequences you can do no better than just storing the sequence in the program and printing it.
Comment: The concept is entropy.
Comment: If you flip a coin three times, and the outcome is $000$, is the coin "obviously completely biased"?
Comment: https://www.google.com/url?sa=t&source=web&rct=j&url=https://youtube.com/watch%3Fv%3DtP-Ipsat90c&ved=2ahUKEwjEg42xkafnAhWjl-AKHQYxAJYQwqsBMAB6BAgFEAQ&usg=AOvVaw1CjqSZa6OK8DI-jcbCvxMz
Comment: Use Bayesian interference to generate a predictive model. In other words, there are two possible outcomes for any flip. You start with the assumption that the coin is fair. Then, each flip alters the predictive model for the following flip.
Comment: @JairTaylor The Wikipedia article you've linked is excellently written. The fact that the naive program computing Kolmogorov's complexity by probing all programs of a given size will not work (because some programs will involve infinite loops) is maybe standard for computer theorists, but it blew me away! I'm glad I've asked the question:)
Comment: You have to change your perspective a little. If you instead count the number of heads, then the first outcome was much more likely than the second outcome. A way to take this further is to then do something called a hypothesis test, doing some calculations with a binomially distributed random variable.
Comment: @IzaakvanDongen's pointing you to the sequences' p-values.
Comment: There are many many sequences "like" the first. But only one "like" the second
Comment: @JairTaylor I like your suggestion the best, especially in view of the additional case. However this measure seems much trickier to quantify then other ideas. I'll try to look into this. Also it's interesting how many different proposals I've got already:)
Comment: @WeatherReport Yes, the downside is that it's impossible in general to know what the Kolmogorov complexity is - it is uncomputable! But it is still a theoretically useful concept.
Comment: @weather with the 3rd sequence, the difficulty I see is that it doesn't seem to fit the set up with the coin flips, i.e. you pick a coin that you throw independent flips. As there appears to be colleration between the different flips.
Comment: @clark Sure I get your point. But on the other hand. Assuming that the coin is fair, there is identical probability for all 1-3. Why am I then so suspicious of (2) and (3). Is there a general rule? General type of correlation I should consider?
Comment: I agree that Kolmogorov complexity is something OP would be interested in. There is a rich history of attempts to define the "randomness" of a sequence of 0s and 1s.
Comment: @Weather Report Regarding correlation, if we use the autocorrelation as defined in https://en.wikipedia.org/wiki/Linear_prediction, we find that in your third sequence, R(1) is the expected value of products 0·1 and 1·0, so it is 0. R(2) is the expected value of 0·0 and 1·1, so it is $\frac{1}{2}$. In the random sequence, assuming products 0·0, 0·1, 1·0 and 1·1 are equiprobable, R(1) and R(2) are both $\frac{1}{4}$.
Answer: The sequences themselves do have the same probability. However, what makes the first seem more likely to you is the fact that it has a more even number of ones and zeros. Instead of testing the likelihood of the exact sequences, you can test the likelihood of the number of ones and the number of zeros.
For a fair coin, this is binomial with $p = \frac{1}{2}$, meaning that the probability that the number of ones in a sequence of length $n$ is $k$ is
$P_{\frac{1}{2}}(k) = {n\choose{k}}\frac{1}{2}^n$
The only thing that differentiates the sequences is essentially ${n\choose{k}}$, which represents the number of sequences of length n with k ones. This would indeed give a higher probability to your first sequence.
Another way of looking at it, is treating $p$ as unknown. For a given $p$, such that $P(x_i = 1) = p = 1 - P(x_i = 0) \forall i$, the probability of a sequence $x_1, ... x_n$ is
$P(x_1, ... x_n | p) = p^{ |\{i : x_i = 1\}|}\cdot (1 - p)^{|\{i : x_i = 0\}|}$
Now, which $p$ maximizes the likelihood for each sequence? How far is it from the true $p = \frac{1}{2}$ for a fair coin?
Comment: Great thank you, this is helpful. I've edited the question adding one more case. Both your tests seem to fail on that one. Any comments?
Comment: I see.. But then you are asking about whether or not there is a pattern in the sequence.. I don't know if I can help you with that. You can count the appearance of specific pairs - how many (11), (01) and so on are in the sequence, instead of single digit numbers, but of course you will be able to find an example where that also does not work.
Answer: You can distinguish your three sequences in terms of their period.
The constant sequence $00000000...$, as well as $1111111111...$ have period $1$ and can be generated by the difference equation $a(n)=a(n-1)$. Closed forms for the sequence are $a(n)=0$ and $a(n)=1$
Sequences $010101...$ and $1010101...$ have period 2 and follow the recurrence $a(n)=a(n-2)$. The corresponding closed forms are $a(n)=\frac{1-(-1)^n}{2}$ and $a(n)=\frac{1+(-1)^n}{2}$. These are simple deterministic formulas, so these sequences are seen to be less random than the first (not random at all).
The patterns can be predicted linearly with zero prediction error after the initial values. One single value is enough for predicting sequence (2) and two values are needed for sequence (3), corresponding to the order of the linear models (first and second order).
The first sequence suggests no period. If it was periodic, the period would be at least $11$, eleven (the last two bits $01$ echoing the first two bits).

From another point of view, let us map your sequences to numbers. Interpret each bit in a positional system, each bit having weight $2^{-n}$, where $n$ is its position.
Your second sequence maps to the integer number $0$.
Your third sequence maps to the rational number $$\sum_{k=0}^\infty \frac{1}{2^{2k+1}}=\frac{2}{3}$$
The first sequence would likely map to an irrational number, unless some periodicity appeared later on.
Since most numbers are irrational (Probability of Getting a Rational Number), sequences like the first one are more likely.
Comment: What would your benchmark say about the sequence of 100 coin flips where the first 50 are zeroes and the last 50 are ones?
Comment: If this is repeated periodically, you get $a(n)=a(n-100)$.
But when trying to predict it with a simple first order system, even $a(n)=a(n-1)$ gets 98% bits right. This result is very different from the 50% one would get from a fair coin.
Comment: Your third sequence extended to 100 bits may be represented by
$(01)^{50}$
This one in your comment above is quite similar, but
$0^{50}1^{50}$
Comment: I think you've switched gears when said that $a(n)=a(n-1)$ gets 98% right. Formally this is a sequence with period 1, while $0^{50}1^{50}$ has no period. But I see what you mean: there is a simple way to reliably predict the next flip given previous one. However, in my view this is closer in spirit to string complexity answers than to your original "period" test. What about $0^11^90^21^8\dots0^91^1$?
Comment: I did not estimate autocorrelations for all lags, but maybe a good one is a(n)=a(n-10), which gets 90% values correct.
Answer: As mentioned in the comment by Spencer, essentially the intuition comes from entropy and what you might call the micro-state/macro-state distinction. You actually have the answer in your question. I've highlighted it

Say the result is a sequence like 0110101011101...
The result is 000000000000...

A sequence like 0110101011101 is way, way more likely than 000000000000. There's loads of sequences like that. 1011011101001 is one of them, 0101101010110 is another, and so on. My guess is that for well over 90% of sequences that long we'd both easily classify it as like your first sequence.
Now it could be that you chose your first sequence very carefully. It could be the precise launch sequence of a missile, for all I know, and you're sitting in a bunker bored out your mind at the moment. Now, if that is the case, you would say it's very, very unlikely to happen by a coin toss, right? What are the chances of that.
Similarly, for all you know, I'm the one sitting in the bunker and I've just spotted that you've written my launch code and I'm on the phone to the secret police to say someone's written our launch code on the internet. I mean, they say it's about tossing a coin but what are the chances of them choosing that randomly?
(Or it could be the digits of Pi, or "You Suck" in ASCII, or the name of an obscure Merzbow album, or ...).
So, the first thing you need to do when you're thinking about things is to group all of the precise sequences (the micro-state) into broad categories that you care about, know about, can know about, etc (the macro-states). Then you can assign a probability to each macro state.
The other answer suggest counting ones and zeros, that's a good start. But sequences like 0101010101010101010101 would be pretty freaky, too.
Underneath all this the space of detectable patterns to humans is much smaller than the configuration space of coin tosses and that in almost all cases the vast majority of configurations map to a pattern we call "random". So the probability of each pattern is very different. Exactly which depends a lot on the person but, you're right 0000000 probably goes to a pattern other than "random" with a small number of other configurations (and so a low probability) and 0110101011101 firmly into random (and so very likely).
As an aside, another way of looking at the pattern issue is to think of the sequences in terms of an approximation to their "Kolmogorov complexity". Think of how long computer code or a description of how to generate the sequence would be (in characters). The code or description for 00000000.. is going to be pretty short. Some (most!) are going to be so "random" that the only real way to describe them is just to write it down and say "print that". In that way you can put a precise figure on how "patterny" a sequence is. Because some sequences have incredibly short descriptions, by the pigeon-hole principle, most are going to end up in this "I give up" set. This isn't actually much more formally powerful than the former above, though, because it depends heavily on the definition of your instruciton set and the oracle of data it has available: it would easily capture any "mathsy" patterns we might spot (including most simple patterns) but probably not that your sequence is the opening lines to the declaration of independence in morse code or last week's lottery numbers. But it's a more precise definition for compuatation-oriented patterns.
Comment: I have a problem with entropy considerations because I see no canonical way of grouping "microstates" into "macrostates" here. For any "unlikely" sequence there will be some split of all the states into macrostates, so that this unlikely sequence belongs to the biggest macrostate.
Comment: But the complexity benchmark I really like, we touched on that in the OP comments. This seems to suggest that there is some relation between complexity and randomness. On the surface this seems obvious, but perhaps the precise mathematical formulation could be very non-trivial. Something like "most random sequences of n bits have complexity of order n" could be a cool statement to study quantitatively.
Comment: The mapping of entropy to macrostates is simple in the statistical mechanics case because it's just those states that are macroscopically distinguishable with thermodynamic quantities (probably bounded below by QM uncertainty / Maxwell's daemon, but I'm no expert on that). But these days "entropy" has very much escaped those confines!
Comment: Fortunately, if you're only interested in computationally distinguishable sequences, you do get a bit of a break with Kologorov-like ideas of complexity: if you are Turing complete, you can show that your measure is within an additive constant of any other Turing Complete measure as you can just implement a VM in the other language as a fixed header. That goes some way to helping intuit that your quantities aren't completely predicated on your choice of coding.


How to display multiple Lists of data with different properties

Question: I have an App that displays lists of data (Random selections from XML files, meant as Inspiration for Authors and Gamers)
When a category is selected, a "Datablock" is Instantiated, holding 50 randomly-created HashMaps, each describing an Entry in that Category. Each HashMap has Key/Value pairs relating to the Category chosen.
e.g. "Names" has keys: Forename and Surname.
 "Treasures" has keys: Style, Item and Value,
"Shop" has keys: Name, Descriptor, Type and Quality.
For each Key, a random Value is selected from the appropriate XML String_Array.
I am planning to display these in a RecyclerView, using an Adapter.
Is it possible to account for the varying amount and type of data in one Adapter, or should I conditionally call a different Adapter for each Category?
Answer: You can implement getItemViewType() in your RecyclerView.Adapter and return a different ViewHolder based on the category of the item.
See also: How to create RecyclerView with multiple view type?


How to create a rule to send email to users of a role that belongs to a country?

Question: I'm using Profile2 module to assign a Country to a Role. For example I have:

User1 | Role: "International Members" | Country: "UK"
User2 | Role: "International Members" | Country: "Poland"
User3 | Role: "International Members" | Country: "Japan"
User4 | Role: "International Members" | Country: "US"

My content also has a field Country.
I have this Rule:
Events:

After saving new content
After updating existing content

Conditions:

Content is published

Actions:

Send mail to all users of a role (International Members)

That is sending email to all users in Role "International Members".
I would like to:

Lookup the Country of the content
Send email to only those "International Members" whose profile Country matches the one of the content.

So If I publish a content with Country set as "US" it should only send an email to User4.
Any idea?
Comment: All I can think of is making a custom rules actions. let see if we can get something from contrib.
Comment: I think I could accomplish it easily by overwriting TO field in the Rule action "Send Email". But don't know which hook allows to do that.
Comment: that would be http://www.drupalcontrib.org/api/drupal/contributions%21rules%21rules.api.php/function/hook_rules_action_info_alter/7
Comment: Still need to lookup the Country of the content first.
Answer: You need to use the action "fetch entity by property" and then use the country field and supply the country.
That will create a list to loop through so you can send mails.
Comment: Hey Niall, not to hijack your answer, but am I correct that you mean "Send a separated eMail to each of the selected users (so NOT just 1 eMail with in the 'to' all selected users)"? If my assumption is correct: can you think of any technique in rules actions to send only 1 eMail, but "to" multiple eMail IDs? Or do you think I should post that as a brand new question?
Comment: To be honest, I've never done too much with emails so I don't know but few sites would ever want multiple users in the to: of one email unless they were bcc'd. It's a breach of privacy if done wrong.
Comment: Merci Niall, never thought about that privacy issue, good point!
Answer: To make this work you may want to give it a try to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

Load the VBO list that you want to be processed.
Add a loop to perform a Rules Action, for each row contained in your Views results.

some more details about the VBO-view you'd have to create for this:

It should include an appropriate filter of the Country.
It should have exactly 1 result (row) for each user to be eMailed.
One of the columns should be the eMail Id (I don't see other columns needed for this to work).

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".
Comment: @KlaatuVerataNecto : merci beaucoup for sharing your own solution just now (via your extra answer)! I'd say "depends what you call ***easier***, but that's the beuty of Drupal of course. Though I must admit your own solution/answer is a great illustration of writing custom rules! so therefor also +1 from me!
Comment: Thanks for reply, ended up doing custom action for Rules. it just seemed easier to implement.
Answer: In the end I ended up doing custom Action for Rules module

<code>function rulesemailsamecountry_rules_action_info() {
$actions = array(
    'rulesemailsamecountry_action_sendemailroleandcountry' => array(
        'label' => t('Send mail to all users of a role that match country node'),
        'group' => t('Custom'),
          'parameter' => array(
            'roles' => array(
              'type' => 'list<integer>',
              'label' => t('Roles'),
              'options list' => 'entity_metadata_user_roles',
              'description' => t('Select the roles whose users should receive the mail.'),
            ),
            'subject' => array(
              'type' => 'text',
              'label' => t('Subject'),
              'description' => t("The mail's subject."),
            ),
            'message' => array(
              'type' => 'text',
              'label' => t('Message'),
              'description' => t("The mail's message body."),
            ),
            'from' => array(
              'type' => 'text',
              'label' => t('From'),
              'description' => t("The mail's from address. Leave it empty to use the site-wide configured address."),
              'optional' => TRUE,
            ),
          ),
      'base' => 'rules_action_mail_to_users_of_role_by_country',
      'access callback' => 'rules_system_integration_access',
    ),
);

return $actions;
}

function rules_action_mail_to_users_of_role_by_country($roles, $subject, $message, $from = NULL, $settings, RulesState $state, RulesPlugin $element) {

  $from = !empty($from) ? str_replace(array("\r", "\n"), '', $from) : NULL;

  // All authenticated users, which is everybody.
  if (in_array(DRUPAL_AUTHENTICATED_RID, $roles)) {
    $result = db_query('SELECT mail FROM {users} WHERE uid > 0');
  }
  else {
    $rids = implode(',', $roles);
    $country_code = $state->get('node')->value()->field_country['und'][0]['iso2'];
    // Avoid sending emails to members of two or more target role groups.
    $query = "
    SELECT
    DISTINCT u.mail
    FROM {users} u
    INNER JOIN {users_roles} r ON u.uid = r.uid
    INNER JOIN profile p ON p.uid = u.uid
    INNER JOIN field_data_field_profile_country c ON c.entity_id = p.pid
    WHERE r.rid IN ('".$rids."')
    AND c.field_profile_country_iso2 = '".$country_code."'";

    $result = db_query($query);
  }

  // Now, actually send the mails.
  $params = array(
    'subject' => $subject,
    'message' => $message,
  );
  // Set a unique key for this mail.
  $name = isset($element->root()->name) ? $element->root()->name : 'unnamed';
  $key = 'rules_action_mail_to_users_of_role_' . $name . '_' . $element->elementId();  $languages = language_list();

  $message = array('result' => TRUE);
  foreach ($result as $row) {
    $message = drupal_mail('rules', $key, $row->mail, language_default(), $params, $from);
    // If $message['result'] is FALSE, then it's likely that email sending is
    // failing at the moment, and we should just abort sending any more. If
    // however, $mesage['result'] is NULL, then it's likely that a module has
    // aborted sending this particular email to this particular user, and we
    // should just keep on sending emails to the other users.
    // For more information on the result value, see drupal_mail().
    if ($message['result'] === FALSE) {
      break;
    }
  }
  if ($message['result'] !== FALSE) {
    $role_names = array_intersect_key(user_roles(TRUE), array_flip($roles));
    watchdog('rules', 'Successfully sent email to the role(s) %roles.', array('%roles' => implode(', ', $role_names)));
  }
}
</code>


Código funciona no console, mas quando chamo ele no documento não funciona corretamente

Question: Eu tenho um código que funciona perfeitamente executando no console, mas não funciona quando chamo ele clicando em um botão do documento.
Função do meu código: Ler um arquivo .csv e separar palavras entre ponto e vírgula.
Retorno testando no console: Todas as frases separadas em um array: produto[0,15:"Referencia", 0,16:"Modelagem",...]
Retorno clicando no botão: produto[0,15:undefined, 0,16:undefined,...]
Para fins de teste, no documento .csv que estou subindo contém estes dados (estes 15 ponto e vírgula no começo é porque a separação no for inicia no index 15):

;;;;;;;;;;;;;;;REFERÊNCIA;MODELAGEM;GRADE;grade1;grade2;grade3;grade4;grade5;grade6;grade7;grade8;grade9;grade10;ATACADO R$;VAREJO

Meu código:

function ImportarProdutos()
{

//Pega elemento <input>
var file = document.getElementById("DadosCsv");

///Variavel para ler arquivo (.csv)
var reader = new FileReader();
//Lê o arquivo
reader.readAsBinaryString(file.files[0]);

//adiciona o que foi lido em uma variavel
var produtos = reader.result;

var produto = [];

//Aqui apenas separa cada palavra
var pos =30;
var j = 15;

for( i = 0; i < 3; i++)
{

  for( ; j < pos; j++){

    produto[[i,j]] = produtos.split(";")[j];

  }
pos = pos+15;

}

console.log(produto);
}
     <input type="file" id="DadosCsv" />
     <button onclick="ImportarProdutos()">Importar Produtos</button>

Comment: Colando o código que está dentro da função, e removendo a palavra 'var' antes das variáveis
Answer: O problema é que você está querendo manipular o conteúdo do arquivo antes dele ter sido lido devido isso ser um processo assíncrono. No console você consegue porque já deu tempo do arquivo ser lido.
Use o evento onload para só tratar o conteúdo após o arquivo ter sido lido:
function ImportarProdutos(){
   //Pega elemento <input>
   var file = document.getElementById("DadosCsv");
   ///Variavel para ler arquivo (.csv)
   var reader = new FileReader();
   //Lê o arquivo
   reader.readAsBinaryString(file.files[0]);
   reader.onload = function () {
      var produtos = reader.result;

      //adiciona o que foi lido em uma variavel
      var produto = [];

      //Aqui apenas separa cada palavra
      var pos =30;
      var j = 15;

      teste = produtos.split(";")

      for( i = 0; i < 3; i++){

         for( ; j < pos; j++){
            produto[[i,j]] = produtos.split(";")[j];
         }
         pos = pos+15;
      }

      console.log(produto);
   }
}

Comment: Obrigado, isso me ajudou muito, funcionou perfeitamente! Seguindo sua solução, usei o 'Onloadend'.


How to create and parse Tag, Length, Value (TLV) in JavaScript or java and encode it in Base64

Question: The QR code fields shall be encoded in Tag-Length-Value (TLV) format with the tag values specified in the "Tag" column of the adjacent table in the image below.
The TLV encoding shall be as follows:
Tag: the tag value as mentioned above is stored in one byte
Length: the length of the byte array resulted from the UTF8 encoding of the field value. The length shall be stored in one byte.
Value: the byte array resulting from the UTF8 encoding of the field value.
This image describe my problem:
Comment: We don't need that image as long as you describe things well enough in your post. On that note: look at your post after you submit it because it needs to follow [the posting guidelines](/help/how-to-ask), and definitely needs to use [the correct formatting](/markdown). With that said: what's your actual problem? Nothing in your post talks about what you've written so far, and where you got stuck in that process, so there isn't anything [for SO to help you with](/help/on-topic) yet?
Answer: You can generate the required hashes by using this library here.
<code>String qrBarcodeHash = QRBarcodeEncoder.encode(
    new Seller("شركة تجريبية"),
    new TaxNumber("312345678901233"),
    new InvoiceDate("2021-11-18T18:40:34+03:00"),
    new InvoiceTotalAmount("2.30"),
    new InvoiceTaxAmount("0.30")
);
</code>
Comment: Thanks @Bu Saeed


Equivalence of statements about bounded linear maps on a Hilbert space

Question: Assume $H$ is a Hilbert space and $V \in L_b(H)$.
I want to show, that the following propositions are equivalent:

V is an isometry.
For every orthonormal system $\{u_{\alpha}: \alpha \in A \}$ the set $\{Vu_{\alpha}: \alpha \in A \}$ is also an orthonormal system.
There is an orthonormal basis $\{u_{\alpha}: \alpha \in A \}$ such that $\{Vu_{\alpha}: \alpha \in A \}$ is also an orthonormal system.

I have already proven that $(1) \Rightarrow (2)$:
$\forall x,y \in H:~~(x-y,x-y)=(x,x)-2(x,y)+(y,y)$
$\forall \alpha, \beta \in A:~~2(Vu_\alpha,Vu_\beta)=\Vert Vu_\alpha\Vert^2 -\Vert Vu_\alpha-Vu_\beta\Vert^2-\Vert Vu_\beta\Vert^2 = \Vert u_\alpha\Vert^2 -\Vert u_\alpha-u_\beta\Vert^2-\Vert u_\beta\Vert^2 = 2(u_\alpha,u_\beta)$
Therefore $V$ preserves the scalar product, which yields the claim.
I think $(2) \Rightarrow (3)$ is trivial because every orthonormal basis is an orthonormal system.
This exercise seems a bit odd to me because in my mind the third proposition should read: "There is an orthonormal basis $\{u_{\alpha}: \alpha \in A \}$ such that $\{Vu_{\alpha}: \alpha \in A \}$ is also an orthonormal basis."
In either way, can someone help me with this proof?
Comment: An isometry is usually also assumed to be *surjective* which seems not been posted in your definition, as neither 2. nor 3. implies it. And also answers why the image of a basis needs not be basis.
Answer: It is enough to assume that for some orthonormal basis $(u_{\alpha})$ the set $(Vu_{\alpha})$ is orthonormal. It is not necessary to assume that the latter is complete. Proof of 3) implies 1): any $v \in V$ can be expanded as $\sum c_{\alpha} u_{\alpha}$. Since $V$ is assumed to be a bounded operator we have $Vx=\sum c_{\alpha} Vv_{\alpha}$. Now I leave it to you to verify that $\|Vv\|^{2}=\sum |a_{\alpha}|^{2}$ which is also equal to $\|v\|^{2}$. Hence $V$ is an isometry.


Maven dependency not getting resolved in Intellij

Question: I have Maven setup and updated settings.xml with proxy settings. While working on project it is unable to load any dependency in IntelliJ.
I verified all the config with one of my friend and its working in his machine correctly. Please help.
Answer: Ensure that you are pointing to correct settings.xml in the configuration of intellij
Go to-->File-->Settings-->Build,Execution,Deployment-->Mavan
and validate user settings file and local repository file, if its having different details update the path or replace the file.


clang ignoring attribute noinline

Question: I expected __attribute__((noinline)), when added to a function, to make sure that that function gets emitted. This works with gcc, but clang still seems to inline it.
Here is an example, which you can also open on Godbolt:
namespace {

__attribute__((noinline))
int inner_noinline() {
    return 3;
}

int inner_inline() {
    return 4;
}

int outer() {
    return inner_noinline() + inner_inline();
}

}

int main() {
    return outer();
}

When build with -O3, gcc emits inner_noinline, but not inner_inline:
(anonymous namespace)::inner_noinline():
        mov     eax, 3
        ret
main:
        call    (anonymous namespace)::inner_noinline()
        add     eax, 4
        ret

Clang insists on inlining it:
main: # @main
  mov eax, 7
  ret

If adding a parameter to the functions and letting them perform some trivial work, clang respects the noinline attribute: https://godbolt.org/z/NNSVab
Shouldn't noinline be independent of how complex the function is? What am I missing?
Comment: related: https://github.com/emscripten-core/emscripten/issues/3409
Comment: Does clang support `noinline` attribute?
Comment: It doesn't have its own category in the [list of attributes](https://clang.llvm.org/docs/AttributeReference.html), but if you search for noinline there, you will find it mentioned several times.
Comment: Also, looking at the version with parameters, if I remove it there, both functions are inlined. So clang seems to at least know it.
Answer: __attribute__((noinline)) prevents the compiler from inlining the function. It doesn't prevent it from doing constant folding. In this case, the compiler was able to recognize that there was no need to call inner_noinline, either as an inline insertion or an out-of-line call. It could just replace the function call with the constant 3.
It sounds like you want to use the optnone attribute instead, to prevent the compiler from applying even the most obvious of optimizations (as this one is).
Comment: This, together with @YSC's comment, makes sense. It's interesting that clang and gcc seem to have different opinion of what constitutes inlining.

clang ignoring attribute noinline


How to change backGround color in Xamarin forms NavigationPage

Question: I'm trying to change the background color of navigationBar in navigationPage I'm using this code:
using System;
using System;
using Xamarin.Forms;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
namespace P
{
public class App : Application
{
    public App ()
    {
 MainPage = new NavigationPage(new LoginPage());
    }
    protected override void OnStart ()
    {
    }
    protected override void OnSleep ()
    {
    }
    protected override void OnResume ()
    {
        // Handle when your app resumes
    }
   }
  }

how can I do it?
Answer: Just set the BarBackgroundColor property of the NavigationPage instance:
new NavigationPage(new LoginPage()) { BarBackgroundColor = Color.Green };

Answer: If you want to setup a global style in xaml, you could something similar to this:
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="Sample.App">
    <Application.Resources>

        <ResourceDictionary>

        </ResourceDictionary>

    </Application.Resources>
</Application>

Comment: @x-rw Difficult to say without much information.  Did you include this in your app.xml file?  If still a problem, I suggest opening a separate question.
Comment: Awesome! This works without all kinds of customizations
Answer: <Application.Resources>

    <ResourceDictionary>

        <Color x:Key="NavigationPrimary">Green</Color>

    </ResourceDictionary>
</Application.Resources>

basically go to App.xaml
paste this code there
change the colour however u want in this part
Green
Answer: If you want to change the NavigationBar BackgroundColor on each page with a different color. You can do the following on the Codebehinds of each page/view.
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace NewApp.Cross.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class NewView : ContentPage
    {
        public NewView()
        {
            InitializeComponent();
            Title = "PageTitle"

            NavigationPage.SetHasBackButton(this, false);

            ((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            ((NavigationPage)Application.Current.MainPage).BarTextColor = Color.OrangeRed;
        }
    }
}

It works on Android and iOS.


Taylor series of $[\log(1-z)]^2 $

Question: I'm having some trouble proving that the Taylor series about the origin of the function $[Log(1-z)]^2$ to be $$\sum_{n=1}^\infty \frac{2H_n}{n+1}z^{n+1}$$ where $$H_n = \sum_{j=1}^n \frac{1}{j}$$
So far, I've been trying to use the definition of Log(1-z) = log|1-z| + iArg(1-z).
I've also noted that the Taylor expansion for log|1-z| = $\sum_{k=0}^\infty \frac{-z^{k+1}}{k+1}$ from integrating the geometric series $\sum_{k=0}^\infty z^k$ given |z|<1.
Because log|1-z| = $\sum_{k=0}^\infty \frac{-z^{k+1}}{k+1}$ converges for |z|<1, I've tried to use this for the Cauchy product of [Log(1-z)]^2
$$[Log(1-z)]^2 = Log(1-z) Log(1-z)$$
$$=\left(\sum_{i=0}^\infty \frac{-z^{i+1}}{i+1}\right)\left(\sum_{j=0}^\infty \frac{-z^{j+1}}{j+1}\right)$$
$$=\sum_{n=0}^\infty \sum_{k=0}^n\frac{-z^{k+1}}{k+1} \frac{-z^{n-k+1}}{n-k+1}$$ $$= \sum_{n=0}^\infty \sum_{k=0}^n\frac{z^{n+2}}{(k+1)(n-k+1)}$$
Really lost here, so any clues would be helpful! Thank you in advance.
Answer: Outline: I would attack the problem somewhat differently. First multiply the power series for $\ln(1-t)$ by the series for $\frac{2}{1-t}$. The $2H_k$ will come up naturally as coefficients.
Then integrate term by term from $0$ to $z$. That will produce the right denominator.
Finally, calculate $\int_0^z\frac{2}{1-t}\ln(1-t)\,dt$.
Answer: The next step might be to
use partial fractions:
$\dfrac1{k+1}+\dfrac1{n-k+1}
=\dfrac{(n-k+1)+(k+1)}{(k+1)(n-k+1)}
=\dfrac{n+2}{(k+1)(n-k+1)}
$
so
$\dfrac{1}{(k+1)(n-k+1)}
=\dfrac1{n+2}\left(\dfrac1{k+1}+\dfrac1{n-k+1}\right)
$.
Therefore
$\begin{array}\\
\sum \limits_{n=0}^\infty \sum \limits_{k=0}^n\dfrac{z^{n+2}}{(k+1)(n-k+1)}
&=\sum \limits_{n=0}^\infty \sum \limits_{k=0}^nz^{n+2}\dfrac1{n+2}\left(\dfrac1{k+1}+\dfrac1{n-k+1}\right)\\
&=\sum \limits_{n=0}^\infty \dfrac{z^{n+2}}{n+2}\sum \limits_{k=0}^n\left(\dfrac1{k+1}+\dfrac1{n-k+1}\right)\\
&=\sum \limits_{n=0}^\infty \dfrac{z^{n+2}}{n+2}\left(\sum \limits_{k=1}^{n+1}\dfrac1{k}+\sum \limits_{k=0}^{n}\dfrac1{n-k+1}\right)\\
&=\sum \limits_{n=0}^\infty \dfrac{z^{n+2}}{n+2}\left(H_{n+1}+\sum \limits_{k=1}^{n+1}\dfrac1{k}\right)\\
&=\sum \limits_{n=0}^\infty \dfrac{z^{n+2}}{n+2}2H_{n+1}\\
&=\sum \limits_{n=1}^\infty \dfrac{z^{n+1}}{n+1}2H_{n}\\
\end{array}
$

Taylor series of $[\log(1-z)]^2 $


Display a custom checkout field value in Woocommerce pdf invoice

Question: I am trying to get some custom fields attached to my order in Woocommerce.
I have succeeded previously in getting some new fields entered by the user in the checkout based on this official documentation.
What I am trying to achieve is passing a set string value to a custom field based on some other product checking logic I have working. Basically if product of a certain category:

is in cart, display message one:  (shipping_instructions_delivery_field_update_order_meta)
otherwise display message two (shipping_instructions_pickup_field_update_order_meta).

My code:
// adds order note at checkout page for the RRNC to pickup at home
add_action( 'woocommerce_before_checkout_form', 'specific_checkout_content', 12 );
function specific_checkout_content() {
    // set your special category name, slug or ID here:
    $special_cat = 'randwick-rugby-netball-club';
    $bool = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( has_term( $special_cat, 'product_cat', $item->id ) )
            $bool = true;
    }
    // If the special category is detected in one items of the cart
    // It displays the message
    if ($bool)
    {
      echo '

PLEASE PICK UP ORDER FROM THE CLUB.

';
      add_filter( 'woocommerce_cart_needs_shipping_address', '__return_false');     //Removes the ship to different address for club store items
      add_filter( 'woocommerce_enable_order_notes_field', 'remove_wc_order_notes' );    //Removes the order notes
      add_action( 'woocommerce_checkout_update_order_meta', 'shipping_instructions_pickup_field_update_order_meta' );   //Adds the pick up note for the pdf slip
      add_action( 'woocommerce_checkout_process', 'my_custom_checkout_field_process_pickup' );
    }
  else
  {
     echo '
Orders are dispatched within 2 business days and shipping times are estimated at between 3-7 business days depending on your location within Australia.
';
    add_action( 'woocommerce_before_order_notes', 'delivery_instructions_field', 10 );  //Adds the Delivery Instructions fields to the checkout
    add_action( 'woocommerce_checkout_update_order_meta', 'shipping_instructions_delivery_field_update_order_meta' );   //Adds the delivery note for the pdf slip
    add_action( 'woocommerce_checkout_process', 'my_custom_checkout_field_process_delivery' );
  }
}

function my_custom_checkout_field_process_delivery( ) {
                global $woocommerce;
                // Check if set, if its not set add an error.
                if ( !$_POST[ 'delivery_instructions' ] )
                                wc_add_notice( __( 'Please select from the delivery options.' ), 'error' );
                                 /*$woocommerce->add_error( __( 'Please select from the delivery options.' ) );*/
                if ( !$_POST[ 'sport_instructions' ] )
                                wc_add_notice( __( 'Please select the sport of the order' ), 'error' );
                                /*$woocommerce->add_error( __( 'Please select the sport of the order' ) );*/
}

function my_custom_checkout_field_process_pickup( ) {
                global $woocommerce;
                // Check if set, if its not set add an error.
                if ( !$_POST[ 'sport_instructions' ] )
                                wc_add_notice( __( 'Please select the sport of the order' ), 'error' );
                                /*$woocommerce->add_error( __( 'Please select the sport of the order' ) );*/
}

// remove Order Notes from checkout field in Woocommerce
function remove_wc_order_notes() {
    return false;
}

function shipping_instructions_delivery_field_update_order_meta( $order_id ) {
            update_post_meta( $order_id, 'shipping_instructions', 'IF YOU HAVE NOT RECEIVED YOUR ORDER WITHIN 7 DAYS, PLEASE CONTACT US TO FOLLOW UP' );
}

function shipping_instructions_pickup_field_update_order_meta( $order_id ) {
            update_post_meta( $order_id, 'shipping_instructions', 'PLEASE PICK UP FROM THE CLUB SHOP' );
}

//Admin side
/**
 * Update the order meta with field value
 **/
add_action( 'woocommerce_checkout_update_order_meta', 'delivery_instructions_field_update_order_meta' );
function delivery_instructions_field_update_order_meta( $order_id ) {
                if ( $_POST[ 'delivery_instructions' ] )
                                update_post_meta( $order_id, 'delivery_instructions', esc_attr( $_POST[ 'delivery_instructions' ] ) );
}

add_action('woocommerce_admin_order_data_after_billing_address', 'my_custom_shipping_fields_display_admin_order_meta', 10, 1);

function my_custom_shipping_fields_display_admin_order_meta($order) {
echo '
' . __('Shipping Note') . ':
 ' . get_post_meta($order->id, 'shipping_instructions', true) . '
';
}

$shipping_instructions = get_post_meta($wpo_wcpdf->export->order->id,'shipping_instructions',true);
if (isset($shipping_instructions)) {
    echo $shipping_instructions;
    }

/**
 * Add the delivery instructions field to the checkout
 **/

function delivery_instructions_field( $checkout ) {
                 echo '

' . __('Delivery Instructions') . '
';
                woocommerce_form_field_radio( 'delivery_instructions', array(
                                 'type' => 'select',
                                'class' => array(
                                                 'delivery_instructions form-row-wide'
                                ),
                                'label' => __( '' ),
                                'placeholder' => __( '' ),
                                'required' => true,
                                'options' => array(
                                  'Signature Required' => ' Signature Required
A signature is required for the goods to be left at the intended address. If there is no one to sign for your delivery, a card will be left and it is then your responsibility to collect the items from the nearest depot or arrange for the courier to return. This will be at your expense

',
                                  'Leave Unattended' => ' Authority to leave unattended
Courier will leave your goods at the intended address. You can give directions in the "Order Notes" below for the best place to leave your delivery',

                                )
                ), $checkout->get_value( 'delivery_instructions' ) );
                echo '
';
}

add_action('woocommerce_admin_order_data_after_billing_address', 'my_custom_billing_fields_display_admin_order_meta', 10, 1);

function my_custom_billing_fields_display_admin_order_meta($order) {
echo '
' . __('Delivery Instructions') . ':
 ' . get_post_meta($order->id, 'delivery_instructions', true) . '
';
}

$delivery_instructions = get_post_meta($wpo_wcpdf->export->order->id,'_delivery_instructions',true);
if (isset($delivery_instructions)) {
    echo $delivery_instructions;
    }

/**
 * Add the field to the checkout to get the sport of what the customer orders
 **/
add_action( 'woocommerce_after_order_notes', 'sport_instructions_field', 20 );
function sport_instructions_field( $checkout ) {
                 echo '

' . __('Which sport is this order in relation to?') . '
';
                woocommerce_form_field_radio( 'sport_instructions', array(
                                 'type' => 'select',
                                'class' => array(
                                                 'sport_instructions form-row-wide'
                                ),
                                'label' => __( '' ),
                                'placeholder' => __( '' ),
                                'required' => true,
                                'options' => array(
                                  'Rugby Union' => 'Rugby Union
',
                                  'Rugby League' => 'Rugby League
',
                                   'Netball' => 'Netball
',
                                   'Football' => 'Football
',
                                   'AFL' => 'AFL
',
                                   'Touch Tag' => 'Touch & Tag',

                                )
                ), $checkout->get_value( 'sport_instructions' ) );
                echo '
';
}

/**
 * Update the order meta with field value
 **/
add_action( 'woocommerce_checkout_update_order_meta', 'sport_instructions_field_update_order_meta' );
function sport_instructions_field_update_order_meta( $order_id ) {
                if ( $_POST[ 'sport_instructions' ] )
                                update_post_meta( $order_id, 'sport_instructions', esc_attr( $_POST[ 'sport_instructions' ] ) );
}

add_action('woocommerce_admin_order_data_after_billing_address', 'my_custom_sports_fields_display_admin_order_meta', 20, 1);

function my_custom_sports_fields_display_admin_order_meta($order) {
echo '
' . __('Sport in relation to') . ':
 ' . get_post_meta($order->id, 'sport_instructions', true) . '
';
}

$sport_instructions = get_post_meta($wpo_wcpdf->export->order->id,'_sport_instructions',true);
if (isset($sport_instructions)) {
    echo $sport_instructions;
}

I would think that the update_post_meta() with a string at the end should set it but it does not appear to do anything. Or perhaps I don't have the proper fuctionality with:
function my_custom_checkout_field($checkout).
Any help is appreciated.
Comment: You should better add all your related code (even the code that displays your custom checkout fields) as without it is not possible to handle your issue.
Comment: Ok, I have updated the code to show all the other functionality that does work. Tried a few more things and still no luck.
Answer: Try this code. _shipping_instructions replace this with shipping_instructions
$shipping_instructions = get_post_meta($wpo_wcpdf->export->order >id,'shipping_instructions',true);
if (isset($shipping_instructions)) {
    echo $shipping_instructions;
}

Comment: I used the underscore because the other custom fields I have on the form work and have the underscore at the beginning even though it does not anywhere else in the code. I have edited the original post with all the code.


Rollback on ItemProcessor and still call ItemWriter

Question: I have an ItemProcessor that writes to the database and an ItemWriter that writes to a file. I want to be able to rollback in the ItemProcessor and still be able to pass by the ItemWriter.
To be more specific, my logic takes the object received from a FlatFileItemReader and uses it to do some maintenance to the database, if every thing goes good some properties are set in the object and if I face any database problem, I catch the exception and I set some other properties in the object. The processed object is later written to a file through a FlatFileItemWriter. I tried to extend the FlatFileItemWriter to throw an Exception after writing to trigger a rollback but doing so stops the things from going to the file.
Comment: `I have an ItemProcessor that writes to the database`: an item processor is not meant to write data. It feels like your issue is rather a job design issue than a problem in spring batch. What about splitting your job in two steps?
Comment: Exactly, it is a bad design but it is not mine and I am not allowed to make substantial changes to the Job designed by my superior
Answer: I have found that the FlatFileItemWriter is working with a TransactionAwareBufferedWriter, so there is no way to rollback the transaction and still write to the file on the disk as the TransactionAwareBufferedWriter will only flush to the disk if the transaction accomplishes without problems. So I did implement a pure Writer that implements the ItemWriter interface and I just throw an Exception just after writing to the file, flushing and closing the stream and it's working, it does rollback the transaction and in the same time it writes to the file on the disk.
I will not accept my answer for the moment to see if someone can come up with a better approach, maybe without loosing the benefits of having a FlatFileItemWriter.


Cisco RV110W: Use LAN port as WAN?

Question: I have Cisco RV110W Wireless router. WAN port was burned after a storm. Can I use one of LAN ports as WAN?
Looking under "Switch Settings" I can't find solution. In the Cisco documentation, I could not find a solution either.
Comment: It may no longer work as a router. But it might still work as an access point. Many wireless routers can be used as access point if you simply disable the DHCP server and then leave the WAN port disconnected.
Comment: (put scotch tape over the WAN port)
Answer: Nope.
The Cisco RV110W device you have contains a dedicated WAN port. This is a physical hardware port intended for this purpose. You will not be able to reassign WAN functions to one of the four switch ports.

More importantly, equipment damaged in an electrical storm really should not be trusted. You're going to have to replace this router.
Comment: Just to illustrate the separation... Versus something like a Cisco ASA 5505, whose ports *can* be reconfigured.
Comment: Well, technically, all five ports are on a single switch, and it has the WAN port on a separate VLAN (VLAN 1, untagged), which is why it's reserved. And of course the firmware does not let you reassign the port to another VLAN. Third party firmware might allow it though.
Comment: I never type quick enough lol...but your answer has a picture...so +1 :)
Comment: And +1 from me for linking to our canonical lightning-strike-mitigation question - smoooothly done!
Comment: I guess, too bad( Thx for reply
Comment: But... Storm damage.
Answer: I believe DD-WRT will  this, e.g. to set up the other LAN ports under separate, NATted subnets, and other neat tricks.  DD-WRT is a complete firmware replacement, that installs a very small version of Linux, and the tools necessary to manage it. You can find it at dd-wrt.org, with probably a better explanation, instructions, and so forth.
dd-wrt is probably a 4 out of 5 on a technical scale to get installed, but if you find this intriguing, i might be worth it at least to try since it's not a router otherwise.
this forum indicates the hardware is the same is a Cisco E2000, so that image is known to work:
http://www.dd-wrt.com/phpBB2/viewtopic.php?t=141699&postdays=0&postorder=asc&start=15&sid=8056260fc95a2b055afde005b32eee7d
01/06/15 edited for grammar/clarity
Comment: I wouldn't recommend doing this in a professional environment... but it's a good idea for home use/small offices.
Comment: I'd much sooner use OpenWrt, as DD-WRT's future is questionable, but the general advice is sound.
Comment: good idea, i try this, thx

Cisco RV110W: Use LAN port as WAN?


How to use the Yahoo OpenID authentication for a windows store application?

Question: Am working on a windows store javascript application(html/javascript) and have used windows azure for the backend. Azure supports facebook, microsoft, twitter and google authentication.
Is there a way to perform Yahoo authentication for a windows store app?
Answer: Please be more descriptive in your question. What exact service for backend and authentication have you used? Azure Mobile Services or Azure Active Directory Access Control (a.k.a ACS)?
If you've used Azure Mobile Services - there is no out-of-the-box support for Yahoo! authentication. If this is the case, you have to add Yahoo manually and handle everything in your app (which is not AZURE related, but more handling OpenId/OAuth in Windows Store Apps).
If you used ACS, it has direct support for Yahoo Identity Provider.
But since you ask, my guess is you are using Azure Mobile Services. And the answer is that you cannot use the Azure Mobile Services SDK/Backend to authenticate against Yahoo. You have to handle this with custom code in your app.
Comment: Even for the custom code I couldn't find any javascript based yahoo authentication resources. It would be great if you could atleast point me to the right set of resource. Thanks!
Comment: My expertise ends here. And this is not Azure related anymore. You shall seek help with WinJS tag combined with Yahoo and probably OpenId or OAuth.


Headless Web Browser During Cron?

Question: I need a headless web browser with JS support to use during cron. It seems like the simpletest module does what I need, but how could one initiate a browser and hand it a DOM?
Outside the context of Drupal cron, it would go like this:
<code>require_once('simpletest/browser.php');

$browser = &new SimpleBrowser();
$browser->get('http://php.net/');
</code>
But, is there a way I can use the code that the simpletest module already provides?
Comment: Do you really need js during cron?  Seems needlessly complicated; couldn't you just provide equivalent functions to the js code in php?  Without js, you can easily call cron via Drush.  See: http://drupalcode.org/project/drush.git/blob_plain/HEAD:/docs/cron.html
Comment: The only point of my comment was that you should seriously consider whether you need js during cron. From your updated example, it looks like you do. I think this is an interesting question, and voted to re-open it.
Comment: @Joe I voted to close as off topic because the question was essentially _"I need a headless web browser with JS support to use during cron"_ which in itself can be answered without any reference to Drupal. Your edit makes it clearer that you wish to do this using Drupal modules so I've voted to re-open :)
Comment: Why was my question closed? It relates directly to Drupal development, using a popular module, for a real problem and can be clearly answered. greg_1_anderson's comment ignores the question.
Answer: If you want a PHP headless web browser, you might look at Mink.
Gherkin/Behat seem to be getting some traction in the Drupal community and in the PHP community more broadly for Behavioral Driven Development.  Mink also supports browser emulation systems (like Selenium), which you typically need in order to interact with Javascript.
Answer: SimpleBrowser does not support Javascript. I'll have to use a headless browser like Phantom or Zombie or script something to execute the JS more directly with a given DOM.

Headless Web Browser During Cron?