Got error from devise user and wicked rails gem

Question: I got error from browser after sign up with email and password.
class UserStepsController < ApplicationController
 steps :personal

 def show
  @user = current_user
  render_wizard
 end

def update
  @user = current_user
  @user.update_attributes(user_params)
  render_wizard @user
end

def finish_wizard_path
 flash[:notice] = "You have successfully Registered With The Wizard."
 user_path(current_user)
end

private

 def user_params
  params.require(:user).permit(:first_name, :last_name, :degree_level, :role, :email,  :password )
 end

end

On RegistrationsController < Devise::RegistrationsController
class RegistrationsController < Devise::RegistrationsController
 def new
  super
 end

 def create
  super
 end

 protected
    def after_sign_up_path_for(resource)
        '/user_steps'
    end
end

I allready added routes resources :user_steps, devise_for :users, :controllers => { :registrations => "registrations" }
my devise/registrations/new
  <%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>

  <%= f.input :email, required: true, autofocus: true %>
  <%= f.input :password, required: true %>
  <%= f.input :password_confirmation, required: true %>

 <%= f.button :submit, "Sign up" %>

 <% end %>
 <%= render "devise/shared/links" %>

Added personal.html.erb first name, last name and degree_level
<%= form_for(@user, :url => wizard_path, :method => :put) do |f|%>
 <%= f.text_field :first_name  %>
 <%= f.text_field :last_name %>
 <%= f.text_field :degree_level %>
<%= f.submit 'submit', :class => "btn btn-primary" %>
<%end%>

user model added validates presence.
This error show after sign up with email and password
error message is Please review the problems below:
Comment: error msg is what?, I can see `index` action in `UserStepsController` do you have `index` view?
Comment: Did you get your code working? where did you create personal.html.erb? I mean in which folder.
Answer: Sorry i want add include Wicked::Wizard


How to correctly configure Fivestar module with a node reference?

Question: I have a content type "review" with a node reference to "product".
I want to be able to have users rate the product while writing a detailed review.
I added a Fivestar "rating" field in "review" and selected as "voting targed" the "node reference field".
Users can enter the review and rate it at the same time. I created a view to show all the reviews for a product and it pulls the ratings nicely from the "rating" field.
However I can't get a view configured correctly to show an average rating for a product.
I setup a relation with "Content: Vote results", left the "required" box unchecked, "value type" = percent, "vote tag" = "vote", "aggregation function" = "average vote".
All the vote results fields come up empty.
What am I doing wrong?
thank you
Answer: You first need to go to path admin/structure/types/manage/product/fivestar and click the Enable Fivestar rating for the "vote" tag. For Full node display I choose Static display above node body because the voting widget will be on the Review form.
At admin/structure/types/manage/review/fields create a Node reference called Reference with a machine name field_review_reference. Add a field for Fivestar voting. Set the Voting target to Node Reference: field_review_reference. Under Reference Field Settings check the Product content type. At admin/structure/types/manage/review/fivestar the widget should NOT be enabled.
(edit: paragraph removed per suggestion of ericduran)
Now you can create another View with field to make a list of products that show fields from the product such as title, price, and image. Add the relationship Content: Vote results. Set Value type as percent, Vote tag as vote and Aggregations function as Average vote. Add the field Vote results: Value, set Relationship to Vote results, set Appearance to Fivestar Stars (display only).
That should be it.
Comment: I don't see why he needs to use Eva, or even views for that matter. I think that part should be remove from the answer since this one is accepted and just leave the other part of the answer intact. Eva is just going to confused people.
Comment: thanks so much. Not enabling the Fivestar on the product type was the main problem. I tried to follow the EVA instructions including the patch but ran into a "out of memory error". Do you know of any  EVA documentation or screencasts? Thanks again!
Comment: @uwe999 You can try creating a variable to be printed in the node.tpl.php file using template_preprocess_node and some code like this `  if ($vars['type'] == 'annotation') {
    $vars['photos'] = views_embed_view('business_photos');
  }`
Comment: @ericduran I didn't know what step he was hung up so I just went through them all.
Comment: thats fine. Thanks for editing the answer. It'll save on suport request on the project page. + 1
Answer: In Drupal 7, there really is no reason to use a different content type for reviews. Unless you really want too.
In drupal 7 comments are now field-able which will allow your comments to use the fivestar rating field. Also when you use the fivestar field in a comment, there is now an option to use the "Parent Node" as the target which is exactly what you want.
After you have your comment set up to use the Parent Node as the target you still need to enable rating on the Product. The reason for this is that the vote will not be cast is the Tag being voted on isn't enabled.
Also makes sure you're using the latest -dev version. Fivestar doesn't currently have any release out yet. But it will really soon and the latest -dev version is pretty stable.
Comment: With the drupal 7 version of fivestar you can pretty much make any entity have stars and also make any entity allow votes, so there is no need to make everything a node just because of that. If a review is a completely different thing then comments it makes perfect sense. If not is just better to use comments.
Comment: @adam s. Yes you can have a product and have rating from a review and/or comments. As long as they all use the same tag you can pretty much make any entity vote agains any other entity.
Comment: What are some of the reasons of using comments over node references? Are there any benefits to use a node reference? Is it possible to make a construction that show a Product, a node reference Review and comments on a Review.
Comment: thanks for the answer. I actually started modifying the "comments" to be used as reviews. Then I realized that I still want regular comments on the product and I would like to have regular comments for the reviews.


Is Complex Numbers the biggest field? If yes, is there any easy proof to understand it?

Question:
Is the Complex Numbers the biggest field?
If yes, does anyone have a "simple"/"easy to understand" proof?
Comment: The field of rational functions $\mathbb{C}(t)$ contains $\mathbb{C}$.
Comment: How do you define "size"?
Answer: It depends on your notion of "biggest". The complex numbers aren't the biggest field in the sense that you could adjoin a new variable to them, say $\mathbb{C}(x)$, and obtain a new field into which $\mathbb{C}$ sits embedded as a subfield. They also aren't the biggest field in terms of cardinality, since you could probably put field structures on sets of arbitrarily large cardinalities.
But they are biggest, in the sense they are algebraically closed. This means that if you try to adjoin a new element to them that satisfies some polynomial relation, you... can't. The variable $x$ in $\mathbb{C}[x]$ doesn't satisfy any relations, so this extension isn't algebraic. But something like $\mathbb{C}[x]/{(3x^2 + 1)}$, where we add in a "new" thing $\alpha$ satisfying the polynomial equation $3\alpha^2 + 1 = 0$, is an algebraic extension. But you know that every complex polynomial has a root, so we can't add in this $\alpha$ to $\mathbb{C}$ - it's already there. On the other hand, $\mathbb{R}[x]/{(3x^2 + 1)}$ is "bigger" than $\mathbb{R}$ since we added in a new thing - a solution to $3\alpha^2 + 1 = 0$. This didn't already live in $\mathbb{R}$, so adding this thing actually extends the field.
Comment: Perhaps you might like to explain the importance of polynomials and polynomial relations. Why can't the OP consider solving non-polynomial equations, and why can't the OP consider quotients like $\mathbb{C}[x]/(\operatorname{e}^x)$? In short, why do we confine ourselves to polynomials when working with fields?
Answer: It depends on the interpretation of the word 'biggest'. There are certainly fields of larger cardinality than $\mathbb C$ that contain $\mathbb C$ (for instance, take any set $S$ and consider the field $\mathbb C(S)$ where the elements of $S$ are adjoined as independent transcendental elements). So, if you measure size by cardinality, then for every field $\mathbb F$ there is a larger field containing it, and thus, in particular, $\mathbb C$ is not largest.
However, if by biggest you mean that every polynomial over it has a root in it, in other words being algebraically closed, then $\mathbb C$ is well-known to be algebraic closed and thus in that sense $\mathbb C$ is the largest algebraic extension of $\mathbb R$.
Comment: @FlybyNight I don't find that your comments (here and to the other answer) are constructive. Any answer would have to omit some details since this is not a textbook. Both Zach and myself in our answers used very standard terminology and our answers are correct and to the point. Your comments feel argumentative, as if you were looking for some detail that we left out and said "oh, but it would be even better to include that detail in the answer". If you find a missing detail a problem, then you can add short comment filling the gap yourself.
Comment: You're welcome to ignore my suggestions. They weren't intended to be argumentative and, having re-read them, they don't seem argumentative to me. Comments are intended to "*...ask for more information or suggest improvements.*" That's exactly what I did. Your quote "oh, but it would be even better to include that detail in the answer" is exactly what I thought, and that is exactly the purpose of the comments section. Hover your mouse over where it says "*add comment*" and read the pop-up.
Comment: Perhaps you could use the chain icon to include some hyperlinks to help the OP understand this very detailed reply. There are many technical terms used here, and I think that hyperlinks would make this answer more accessible.


How to compare row entries in a sparse table with lots of missing values?

Question: I have a dataset with ~1000 laptops and performance results across ~100 different benchmarks. Using the benchmark results, I want to give each laptop a single composite performance score, and rank the laptops according to it.
Now, the problem is, the table is very "sparse" – each laptop is tested against at most about ~50 benchmarks.
The benchmarks are weakly correlated – laptop performance in real-world tasks is difficult to model, and is balanced by lots of different components: CPU Single-core & Multi-core performance, number of hardware and software threads in a CPU, GPU, RAM & storage speed, software optimizations at the level of OS, graphics APIs, and even benchmarks themselves. Plotting a regression trendline I get an R^2 value of 0.3-0.6.
The values within 1 benchmark are linearly comparable with each other.
Let's simplify the dataset down to a dozen laptops with only 2 benchmark results:
+-------+------+
| Alpha | Beta |
+-------+------+
| 1673  | -    |
| 9858  | -    |
| -     | 588  |
| 1212  | 420  |
| 442   | -    |
| -     | 521  |
| 3612  | 425  |
| 6529  | 437  |
| 3179  | -    |
| 3474  | 440  |
| -     | 424  |
| 9779  | -    |
+-------+------+

How would I go about comparing the rows with each other, without dropping any rows or columns?
One solution I've came up with is to:

Calculate the percentage ranking of each entry in its column:
$\frac{value-min}{max-min}$

Do a weighed sum of each column's score

Normalize the weights
Answer: I would treat this as a matrix-completion problem.  After your sparse matrix is completed (or "imputed"), you can just score by means over the benchmarks.
There is a good itroduction to matrix completion at Wikipedia, and your problem is very similar to the Netflix problem (cinema film ratings) used as an example there. I would start with the Alternating least squares minimization (discussed at the link above).  An interesting paper treating this (and more) is Matrix Completion and Low-Rank SVD via Fast Alternating
Least Squares.  An R implementation is in the CRAN package rsparse.
We can illustrate this with the dataset movielens100kincluded with rsparse:
library(rsparse)

res <- rsparse::soft_impute(movielens100k)

res now contains the completed matrix as an SVD-like object, so can be used directly as such, or multiplied out to get the completed matrix.  Let us look at the diagonal matrix of singular values:
 res$d
 [1] 1735.6704  583.3921  470.9729  382.8521  361.6902  281.2488  255.0091
 [8]  250.2438  222.5691  199.6807


Is there some theory that suggests that sequences may be formed by "sampling" earlier sequences?

Question: Is there some theory that suggests that sequences may be formed by "sampling" earlier sequences?
Often music theory seems to suggest progression as "where to go next", but I've been playing around and wondered about, whether it's also possible that one may progress by doing e.g.
say we have four notes in a bar
[n1 n2 n3 n4]
write next bar as an union of samples from previous bar, e.g.
[n1 n2 n3 n4] [[n3 n4] U [[n4] U [n4]]]
can this produce sensible melody progressions?

This kind of technique is very often used in sample-based music, but I've not thought about it in the context of notational music.
This approach would suggest that it would be possible to e.g. produce 8 or 16 bar progressions, if you give just 4 bars.
Since they're samples from the same key, then they should be sensible?
Comment: When you say "write next bar as an union of samples from previous bar", do you mean that the next bar consists literally of n3 n4 n4 n4, or do you mean that both n3 n4 n3 n4 and n4 n4 n4 n4 are acceptable?
Answer: MOTIV-ABSPALTUNG
we call this "a split off" from a motif -  very common in Baroque, Classic, Romantic and 20th century: e.g. Bach, Beethoven, Bruckner (developping a new theme or phrase), Bartok (especial in the endings of his short piano pieces).

In my concern theories (especially of music) shouldn't teach rules but describe what in praxis is done - and give some suggestions). But longtime before theories are built some practices are copied by other musicians.
Hauptthema = main subject
Zwischensatzthema = subordinated theme, or secondary theme, literally the theme between the head theme and the side theme.
Comment: Couldn't find the term for Zwischensatz. Sometimes the *transition* could be considered as such a thing.
Comment: Amen—"Theory follows practice."
Answer: I'm thinking of the works of Steve Reich and other minimalists, who were influenced by and exerted significant influence on, DJ genres. "It's Gonna Rain" literally takes a sample and chops it up. And "Clapping Music," while it doesn't actually rearrange its pattern at all, takes a strategy of shifting the sample to start one note later on each repetition to create new patterns (n1 n2 n3 n4 -> n2 n3 n4 n1 -> n3 n4 n1 n2).

I'm not thinking of any examples off the top of my head that actually rearrange melodic material, but I bet there are some that fit your example.
But there are plenty earlier examples, too. In Bach's Partita no 3 for solo violin, the first movement (Preludio) is full of echo effects. Even if there isn't much rearranging of the parts going on, there's a lot of "chopping." Starting from the beginning...

The first 6 pitches get repeated an octave lower in the next measure. Then mm 3 and 4 get a note-for-note echo in mm 5 and 6. But then later we get this effect:

In the first measure pictured, the four-note group "E F# G# B" first starts with an interrupted attempt, getting only the first two notes out before restarting. Then we get the whole set, then it's repeated, then only three notes are repeated (the last one of which counts as the first note of the next pattern as well).
You also see "chopping up" in the development sections of good old sonata-allegro form. For instance, Dvorak's "American" quartet starts with a simple theme:

We've got several elements there: the first three, syncopated notes; the next two beats, with the dotted figure, the continued dotted figures in the mm 4, leading to dotted figures plus interrupted 8th notes in m 5, and finally the up-and-down arpeggio in m 6.
Later, in the development, we find things like this:

The viola part in mm 64-5 is rhythmically identical to its first two measures back in mm 3-4. But then it "stutters," repeating m 65, then one more time with altered notes to modulate to C#m. Next, in m 68, the violins get the opening-measure material, but in m 69 violin 2 puts the syncopation in the second half of the measure. A few measures later...

The "dotted figure with interrupted 16ths" is repeated so many times it disintegrates into just the 16th notes. Still later...

... the second violin in m 89 (actually unpictured 88 as well) quotes the arpeggiated figure that ended the original viola theme. Then the cello picks it up in m 91, then second violin and viola in m 92 just insist on nothing but back-to-back arpeggios, until they finally talk the first violin into joining in in m 93.
The point of all this is that the "development" section of a sonata-allegro movement is a time when the bits and pieces of the previous themes get chopped into bits, "put through the wash" of tonal modulation, and allowed to bleed onto each other.
Don't let me mislead you, these historical examples are not quite the same mindset as a sampling strategy of "A B C D | A C B D"; the main point is the changing keys rather than the recombinations of melodic material. But they certainly come from the same human impulse, "How can I take what I've already done and do something new with it? How can I reuse the familiar in a way that makes us hear something new in it?"
Also, you can detect (or imagine?) some granular construction of melodies where maybe it was never conscious in the composer's mind. Consider what might be the most famous melody in classical music, the theme from the last movement of Beethoven's 9th symphony. It's such a famous melody now that we take it for granted, but what makes it so memorable? How could one imagine creating it from its constituent pitches? (Disclaimer: I make no representation that Beethoven thought consciously about its structure this way. Also, if what's notated below makes no sense, do a "hard refresh" (add shift to the keyboard shortcut) to reload):
Well, I might start with three notes, ascending stepwise:
X: 1
K: C
L: 1/4
EFG

Ok, that's a start. Hm, I need four beats, so... maybe I'll just repeat the first note.
X: 1
K: C
L: 1/4
EEFG

Cool, cool. Now what? ... uhhhh, I came up, so I guess I'll go down. I'll reverse my three notes, and oh hey, that repeats the G in a way that mirrors the repeated E:
X: 1
K: C
L: 1/4
M:4/4
EEFG | GFE

Hey, let's just keep going downward. I could flip my original three notes upside down:
X: 1
K: C
L: 1/4
M:4/4
EDC

... and just glue that onto what I've already got, using the existing E instead of repeating it:
X: 1
K: C
L: 1/4
M:4/4
EEFG | GFED | C

Now I'm all the way down here at C. I thiiiiink I'll just do exactly what the first measure did, but three notes lower:
X: 1
K: C
L: 1/4
M:4/4
EEFG | GFED | CCDE

Oh crap, it's been three bars, I'd better get a half cadence ready. Uh, how about just an E and a D? Maybe dress it up with a dotted rhythm:
X: 1
K: C
L: 1/4
M:4/4
EEFG | GFED | CCDE | E>D D2

Yay, I've got my first phrase! Now I'll just copy and paste it for the next four bars, except I've gotta end on the tonic this time, so I'll change the last two notes:
X: 1
K: C
L: 1/4
M:4/4
EEFG | GFED | CCDE | E>D D2 | EEFG | GFED | CCDE | D>C C2

... So, as I said, there's no way Beethoven thought as arbitrarily as that. But it doesn't change the fact that you can find these 2-4 note patterns, their reversals, and their inversions even in such a short and simple melody.
Comment: @mavavilj I guess my postscript should be "There's more influence than you might be aware of in the earliest days of electronic music from minimalist/experimental composers like Steve Reich, Terry Riley, and Philip Glass." Steve Reich connects straight to DJ Spooky (who in fact remixed him in tribute).
Answer: Yes. You can work with fragments (samples) of what has come before to build continuations of a musical passage.
There is an adage describing music form as "repetition with variation." In part that describes your "sampling earlier sequences" idea. Obviously such sampling would involve repetition, and reassembling various sampled fragments is a kind of variation.
When you write "notational music" I assume you mean the "common practice" style music that is the topic of typical theory books. In that case the succession of pitches, progression of chords follows a certain syntax and is fairly restricted. Breaking up a musical passage into samples and reassembling it will surely destroy the common practice syntax. So, it becomes very important to know what you mean in your example when you give notes n1 n2 n3 n4.
If the notes are pitches, reassembling sequences will probably be problematic. If the notes are rhythms, you will have an easier time of sampling/reassembling. In common practice music theory the primary topic dealing with this kind of thing is motif development. Repetition, fragmentation, etc. are some of the terms involved.

say we have four notes in a bar
[n1 n2 n3 n4]
write next bar as an union of samples from previous bar, e.g.
[n1 n2 n3 n4] [[n3 n4] U [[n4] U [n4]]]
can this produce sensible melody progressions?

Again, pitch-wise this could be problematic. Like this...

...the passage is a bit short, but just following the process it devolves into a single repeating tone. Pitch-wise this process is likely to produce a lot of gibberish.
But, if we treat the notes as just rhythm values, we could have something like this...

We could give that pitch by overlaying it on a harmonic pattern, a pre-existing pattern that will follow common practice syntax...

I tacked on an ending to complete the chord progression, but notice that I "re-sampled" the opening n1 n2 n3 n4 rhythm.
Also, notice how I shortened n4 from quarter note to dotted eighth note for the concatenation of n1 n2 n3 n4 with n3 n4. I tried to preserve the metrical values of n3 n4 where n3 is a weak pick up note to a downbeat n4. Little adjustments like that would be typical for putting together fragments in a common practice style.
I don't mean to say it's impossible to "sample" pitch/harmonic material. There is something called a harmonic sequence that does exactly that. But the process is very simple. Normally a harmonic sequence just transposes two chord pairs, two or three times. They are very predictable patterns rather than novel rearrangements of harmonic material. The syntax of chord progression is what limits the arbitrary rearrangement of harmonic material.
Perhaps a language comparison will help. The syntax of parts of speech is like harmony: subject verb object is like predominant dominant tonic. You don't get to change that. But, rhythms are like the specific words chosen for a sentence and those can be varied. For example, let's build a sentence monosyllabically: "The young man ate food." Then, keep the syntax, but apply a new short, short, long rhythm: "The hungry man savored lunch." We can rearrange word/rhythms with a lot of freedom, but we can't arbitrarily rearrange syntactic elements. "The young man food ate" doesn't work... except for Yoda. :-)

It wasn't until I listened to the It's Gonna Rain clip that @AndyBonner posted that I realized I overlooked the obvious example of reusing material already presented: the canon, and other similar devices of imitation.
The Steve Reich stuff isn't just resampling, it overlaps the samples, it time shifts when the samples start. His music does that in irregular periods. Canon and other imitative procedures does the overlapping in regular periods to reinforce the meter. Although sometimes the imitation start points can move from a strong to weak beat - like a fugue stretto - which is contrary to the meter and creates an echo/dissolving meter effect that on a basic level is working with the same phenomena as the time shifting in minimalism.
Strictly speaking musical imitation isn't the process you described with n1 n2 n3 n4, n3 n4, n4, n4 which is a simple linear process of fragmentation and concatenation. But of course fragmentation and imitation are both types of reuse of stated material. Invertible counterpoint is a particular type of imitation and reuse that puts musical segments into several voices. That can be represented in a grid similar to your linear process n1 n2 n3.... Triple counterpoint would be three musical segments that can be variously placed in three different voices. Theoretically, the grid would look like...

A A B B C C
B C A C A B
C B C A B A

If each vertical unit were two bars, then ABC and all its possible inversions will produce horizontally 12 bars of music. That's 12 bars "for the price of" only 2 in the starting material.


Conditional independence in bayesian network

Question: I am referring a Bayesian Net Example from here.

<code>Prob(A=T) = 0.3
Prob(B=T) = 0.6
Prob(C=T|A=T) = 0.8
Prob(C=T|A=F) = 0.4
Prob(D=T|A=T,B=T) = 0.7
Prob(D=T|A=T,B=F) = 0.8
Prob(D=T|A=F,B=T) = 0.1
Prob(D=T|A=F,B=F) = 0.2
Prob(E=T|C=T) = 0.7
Prob(E=T|C=F) = 0.2
</code>
In this case how do you solve for P(E=T|A=T) ?
Because C is not known E and A are not independent events.
Comment: @gung sorry that was a typo. I meant E and A.
Answer: A few things.

The Chain Rule:
$$
P(E, C | A) = P(E|C,A) \cdot P(C | A)
$$
Conditional Independence:  The notation of a Bayes Network implies
$$
P(E|C,A) = P(E|C)
$$
The idea is, if you know that $C$ did or did not happen, it doesn't matter whether or not $A$ happened.  So at this point we have:
$$
P(E,C|A) = P(E|C) \cdot P(C|A)
$$
Marginalization: Removing a variable from a joint distribution (only variables on the left side of the "|") by summing over the possible values they can take.
$$
P(E|A) = P(E,C=T|A) + P(E,C=F|A).
$$

So now you should be able to answer this question.  Please let me know if you don't understand any of the steps, or don't see how this applies to your question.
Answer: It seems to me that you would need to compute the probability that E = T for each possible value of C, multiply each by the probability of C being that value given A = T, and add everything up.  That is
$$\sum_{X}P(E=T|C=X)P(C=X)$$
If every node can be either T or F, that would be
$$P(E=T|C=T)P(C=T|A=T) + P(E=T|C=F)P(C=F|A=T) $$
If I am reading jlimahaverford's answer correctly, I think they end up being the same thing.
Let me know if I am incorrect.
Comment: Yes, my answer is just a justification of this all.  You're using the conditional independence implied by the graph structure.


Will some integer power of $exp(\frac{a2i\pi}{p^n})$ generate $exp(\frac{b2i\pi}{p^m})$ if m is large enough?

Question: I'm trying to figure out if given a rational number $\frac{a}{p^n}$ with $0 < a \leq p^n$ if you will always be able to find an integer multiple of the rational $\frac{b}{p^m}$ with $0 < b \leq p^m$ give that $n <<< m$ . I know it would be number theory but am unsure exactly what to search. I feel like knowing more about  $\mathbb{Z}/p\mathbb{Z}$ and  $\mathbb{Z}/p^n\mathbb{Z}$, with $n \in \mathbb{Z}^{+}$ will help but I'm not 100% sure. What should I be reading through and searching for?
For clarity the exact problem is as follows.
Let $p$ be a prime. Given $x = exp(\frac{a2i\pi}{p^n})$ and $y = exp(\frac{b2i\pi}{p^m})$ with $n, m, a, b \in \mathbb{Z}^{+}$, ($n < m$), and $ 0 < a < p^{n}$ and $ 0 < b < p^{m}$. Will some integer power of $y$ generate $x$ if $m$ is large enough (but we can't know exactly what $m$ is)?
Answer: For $p$ prime and $p \nmid a, p \nmid b$ then $$\exists k,\quad \exp(2i \pi a/p^n)^k=\exp(2i \pi b/p^m)$$ iff $m \le n$.
Proof : take $ac\equiv 1 \bmod p^n$ (for example $c = a^{(p-1)p^{n-1}-1}$) and $k =cb p^{n-m} $.
Comment: If we have the condition that $\frac{a2i\pi}{p^n}$ and $\frac{a2i\pi}{p^m}$ are in their reduced forms that guarantees gcd(p,a) = gcd(p,b) = 1 correct?


jQuery HTML problem

Question: I wrote this:

Whatever.

And it didn't work?.
Thanks.
Answer: your element hasn't been rendered when your script runs... try this:

Comment: It worked but some of my images removed I have no clue why? Thanks
Comment: I'm guessing that your "productDetails" div should also have a "productInfo" class so that it inherits the same styles and doesn't affect your layout
Answer: Looks like you've left out document.ready:

Comment: It worked but some of my images removed I have no clue why? Thanks
Answer: Place the SCRIPT elements at the bottom of the page and use a ready handler:
<!DOCTYPE html>

    <title>A valid page</title>

Whatever.

Comment: It worked but some of my images removed I have no clue why? Thanks

jQuery HTML problem


How to add to object array pointer c++

Question: I'm trying to add an object to an object array passed as an argument. Specifically, I have an array of buttons and I am adding a back button to the button array. How can I correctly do this? When I try the code below I get some weird glitches with the buttons passed from the original pointer array.
int createMenu(Button buttons[], int size)
{
    //Stuff here
}

int menu(Button buttons[], int size, bool back)
{
    Button * newButtons[size + 1];
    for (int i = 1; i <= size; i++)
        *newButtons[i] = buttons[i];
    Button back(25, 19, "Back"); //Creates back button object
    *newButtons[0] = back;
    return createMenu(*newButtons, size + 1);
    //Makes menu with the back button
}

Any help is appreciated.
Comment: Is it necessary to use arrays? In general avoid them and use vectors.
Comment: BTW arrays must have size known at compile-time. `Button *newButtons[size+1];` is illegal (although some compilers offer this as an extension). Also, it is not possible to resize them at runtime.
Comment: I never looked in to them. Would they be more or less memory-heavy? I am running this on a device with 3MB of RAM.
Comment: Yes, they would consume more memory than arrays. Probably in your situation it makes sense to use Arrays I guess.
Comment: Show the declaration of `createMenu`
Comment: This code dereferences an uninitialized pointer (when you wrote `*newButtons[i]`) . Also you never do anything with `newButtons` once you set it up.
Comment: @Anon : why does it make sense? It will consume a few bytes more, does it has any impact nowadays with GB of RAM? Makes no sense imho.
Comment: @galinette, he is using 3MB of RAM.
Answer: In your loop you reference buttons[size], which is ouside of its bounds. You also dereference members of newButtons without initializing them. And you try to pass createMenu an array of pointers, when it expects an array of buttons. Should be something like this:
int menu(Button buttons[], int size, bool back)
{
    Button * newButtons = new Button[size + 1];
    for (int i = 0; i < size; i++)
        newButtons[i + 1] = buttons[i];
    newButtons[0] = Button(25, 19, "Back");
    int result = createMenu(newButtons, size + 1);
    delete [] newButtons;
    return result;
}

Comment: `delete newButtons;` should be `delete [] newButtons;`
Answer: For reference, here's how it would look if you were using vectors:
int menu( std::vector<Button> buttons )
{
    buttons.push_back( Button(25, 19, "Back") );
    return createMenu( buttons );
}

If the button really needs to be pushed at the front then there are various options (e.g. actually push it at the front; or use a deque instead of a vector).
Answer: Try this. You are using Button*, so pass address of the Button object.
int menu(Button buttons[], int size, bool back)
{

    Button ** newButtons = new Button*[size + 1];
for (int i = 1; i <= size; i++)
        newButtons[i] = &buttons[i];
    Button * back = new Button(9,11,"fdf"); //Creates back button object
    newButtons[0] = back;

    //Makes menu with the back button
createMenu(*newButtons, size+1);
}

void createMenu(Button buttons[], int size)
{
    (buttons[0]).foo();

    //Stuff here
}

Also, you are using the same variable name "back" both as bool and as object of Button class. Change that.
Comment: I still get strange results with this. Maybe it's something related to my compiler.
Comment: This stores the address of a local variable
Comment: @MattMcNabb, thanks for that! That was unforgivable.
Comment: I still don't get the expected results. But it looks like your answer should work.
Comment: Are you able to compile now? What is the error you get?
Comment: It compiles. Just when I access the objects of the array (using ->) something isn't communicating correctly; the buttons don't respond.
Comment: @RandomPerson323, I updated my answer. I tried with a dummy class I wrote and I get the expected answer. This should work.
Comment: As currently showing, this still only exposes the first button to `createMenu` - presumably OP wants `createMenu` to be able to see all buttons

How to add to object array pointer c++


How to get an easier form of this convolution?

Question: What would be right approach to evaluate the convolution (integral):
$\int f(\tau')\delta(a\tau + b\tau') d\tau'$
I am not sure if I can rearrange something in this convolution to get an easier representation.
Thanks for any help!
Answer: It is
$$
   \int f(\tau')\delta(a\tau+b\tau')d\tau'=
\frac{1}{b}\int f(\tau')\delta\left(\tau'+\frac{a}{b}\tau\right)d\tau'=\frac{1}{b}f\left(-\frac{a}{b}\tau\right).
$$
Comment: You are welcome. It is a property of the Dirac distribution. Indeed, $\int f(x)\delta(ax)dx$ then change variable to $y=ax$ and get $(1/a)\int f(y/a)\delta(y)dy=(1/a)f(0)$. So, the property follows.
Comment: Firstfully thanks for the answer. Shouldn't it be $b$ instead of $1/b$? Or why is $\delta(a\tau) = \frac{\delta(\tau)}{a}$?
Comment: Ok makes sense now. Thanks! :)


laravel: taking a json data from a column of a table

Question: in Laravel I have a table named 'doors', this table has a column names 'darha'. I put json data by serialize() in this column.
So I have many rows that each 'darha' column cell have data as:
a:2:{i:0;s:72:"[{ "image": "301-Door-T-N", "code": "main-1527586576301-Door-T-N.jpg" }]";i:1;s:72:"[{ "image": "402-Door-T-N", "code": "main-1527586875402-Door-T-N.jpg" }]";}

the question is How I can get the data of cell data ('image' and 'code') by clicking a button. Here is my ajax code:
function doorData(id) {
    $.ajax({
        url: '/api/apiProducts/' + id,
        method: 'get',
        dataType: 'json',
        success: function (data) {
            $.each(data, function (index, value) {
$.each(value, function (i, v) {
console.log(v.darha);
});
            });
        }
    });
}

By clicking a button I got the list of all column data, but I want to append in a div the json data inserted in a cell of 'darha' column;
Comment: For starters, that is no json data. [`serialize`](http://php.net/manual/en/function.serialize.php) returns a serialized string representation from an object, but it is not json.
Answer: You are missing data parameter.Also maybe do it like this.
$('form').on('submit',function(e){
    e.preventDefault();
    $.ajax({
        url: '/api/apiProducts/' + id,
        method: 'get',
        dataType: 'json',
        data: $('form').serialize(),
        success: function (data) {
            $.each(data, function (index, value) {
               $.each(value, function (i, v) {
                   console.log(v.darha);
               });
            });
        }
    });
});

Also a note. Maybe you should use named routes for better maintenance.
Comment: I use: $('button').on('click', 'doorData()');
Comment: Just add the line from my code "data" with form serialize and try


Jtable row sorter causes IndexOutOfBoundsException

Question: In my PhoneBook applcation after sorting by a column , when i remove a row and cal updateUI() i got a java.lang.IndexOutOfBoundsException in my model  . But if not sorting there is no exeption
I guess the object has removed but in updateUI procedure it doesnt know that and somewhere return old getRowCount() ,according to stacktrace.
    private void delete(int[] selectedIndexes) {
            ArrayList<Contact> arlDeleting = new ArrayList<Contact>();
            for (int i = selectedIndexes.length - 1; i >= 0; i--) {
                int realIndex = tblPhonebook.convertRowIndexToModel(selectedIndexes[i]);
                tblMdlAllContacts.getData().remove(realIndex);
            }

            tblPhonebook.updateUI();
        }

here is stacktrace:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 6, Size: 6
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.TableModelPhoneBook.getValueAt(TableModelPhoneBook.java:73)     ***
at javax.swing.JTable.getValueAt(Unknown Source)
at javax.swing.JTable.prepareRenderer(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)           *** i think getRowCount called here
at javax.swing.plaf.ComponentUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JViewport.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$700(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

and model.getvalueat:
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    Contact temp = data.get(rowIndex);                 // here is where error occurs
    switch (columnIndex) {
    case 0:
        return temp.getFirstName();
    case 1:
        return temp.getLastName();
    case 2:
        return temp.getMobile();
    case 3:
        return temp.getHome();
    case 4:
        return temp.getAddress();
    default:
        break;
    }
    return null;
}

Answer: Don't call updateUI() as this should only be called when L&F is changed. Your delete row method is part of your model right? Are you firing the model's fireXXX() notification methods after deleting? You should be. Also, I wonder if you should be using an iterator to do your deleting.

Edit
You state:

No delet method is part of my controller (is it wrong?).

Wrong. The method should be part of your table model, and controller can call this method on the model, but shouldn't have this method. The table model should extend AbstractTableModel and should call the proper fireXXX method when data is removed, added, or changed. For delete, call fireTableRowsDeleted method, and definitely check the AbstractTableModel API for the details on all such available notification methods.

I removed 'updateUI()' line ,its ok until i click on a cell of table ,when i do this he exeption thrwon . means that actually 'firexxx()' cuase it ,right?

No. I have no idea what your code is doing or the cause of your exceptions right now. Consider creating and posting an sscce.

Oh youre right . but Why when i call 'table.getModel()' i dont see fireXXX()'but by with a refernce to model instance it will be seen. 'mymodel.fireTableDataChanged()'

Outside classes should not call the fire methods. The model itself should be the only object calling its own notification methods.
If you haven't gone through the JTable tutorial, I suggest that you consider doing this without delay. It will help you a great deal.
Comment: No delet method is part of my controller (is it wrong?).I removed 'updateUI()' line ,its ok until i click on a cell of table ,when i do this he exeption thrwon . means that actually 'firexxx()' cuase it ,right?
Comment: Oh youre right . but Why when i call 'table.getModel()' i dont see fireXXX()'but  by with a refernce to model instance it will be seen. 'mymodel.fireTableDataChanged()'
Comment: do you know a good tutorial except of oracle docs- such a short and pactical!?


Is it a good idea to make an destructor protected to disable delete calls via a base class with virtual functions

Question: I work within an environment where I know that all child classes of an abstract base class will never be deleted via a pointer to this abstract base class. So I don't see the need to have this base class to provide with an virtual destructor. Therefore I make the destructor protected, which seems to do what I want.
Here is a simplified example of this:
#include <iostream>

struct Base
{
    virtual void x() = 0;
protected:
    ~Base() =default;
};

struct Child: Base
{
    void x() override
    {
        std::cout << "Child\n";
    }
};

int main()
{
    // new and delete are here to make a simple example,
    // the platform does not provide them
    Child *c = new Child{};
    Base *b=c;

    b->x();
    // delete b; // does not compile, as requested
    delete c;
    return 0;
}

Is it sufficient to make the destructor protected to be save against unwanted base class deletions, or do I miss something important here?
Comment: Given that your code dynamically creates and destroys the object, can you explain *why* you don't want a "base class deletion" to work?   Apart from a diagnostic on `delete b` in the code you have shown,  what does such a thing allow you to achieve?   Avoiding undefined behaviour due to lack of a virtual destructor doesn't count - since your class is abstract, having a virtual destructor costs nothing.
Comment: What makes you think that a derived class will not be deleted via a pointer to its abstract base ? This is exactly what virtual destructors are meant to. [Both gcc and clang](https://godbolt.org/z/VtnhDD) prove that it works fine (unless I have misunderstood the question).
Comment: @Geoffroy Closely related, but not exacly a duplicate. Question asks if we should generally introduce virtual destructors even in classes otherwise not being virtual – whereas this question wants to avoid a virtual destructor even though the class already *has* other virtual functions...
Comment: At a very first glance, this seems to look safe. But if children might be inherited from, then you might have to re-introduce the virtual destructor from within these anyway – or get into danger again. So better to have a virtual destructor right from the start already in `Base`. How many deletions will you have? I cannot imagine that bit of overhead for a virtual function call being worth the loss of safety...
Comment: `Child *c = new Child{};` should be `Child *c = new Child();` no ?
Comment: @Landstalker Uniform object initialisation since C++11... I consider it flawed for a bunch of design errors and recommend to avoid it whenever possible, but at least it's valid C++...
Comment: Does this answer your question? [Should every class have a virtual destructor?](https://stackoverflow.com/questions/353817/should-every-class-have-a-virtual-destructor) and answer says clearly that the destructor could be protected
Comment: @Peter @Fareanor This is an overly simplified example, the real environment is an embedded system where new and delete are not available, and the memory management is manually done. I put the new and delete calls in here to have an example where a random `delete  b` is not entirely alien.
Comment: @Rudi Well, in *that* scenario (µC) even more: *Do* make the destructor of base virtual! In case of ` { Child c; /* do something with c */ }`, there's no pointer involved anyway, thus there won't be a virtual destructor call at all even though it was virtual in base class, as the concrete type is known at compile time already!
Comment: @Rudi Oh, thanks for the clarification, I missed the point then.
Answer:
Is it a good idea to [...]

From a safety point of view I answer with a clear 'no':
Consider the case that the child class is inherited again – maybe someone else than you does that. That person might overlook that you violated good practice in Base and assume that the destructor of Child already is virtual – and delete GrandChild via pointer to Child...
To avoid that situation, you could

make the destructor virtual in Child again – so in the end, nothing gained anyway.
or declare Child final, imposing quite some limits that most likely are meaningless from any other point of view.

And you'd have to opt for one of these for any derived class. All for avoiding a single virtual function call on object deletion?
How often would you do that at all? If frequency of object deletion really is an issue, then consider the overhead of allocating and freeing the memory again. In such a case, it's most likely more efficient to allocate memory just once (sufficently large and appropriately aligned to hold any of the objects you consider to create), do placement new and explicit destructor calls instead and finally free the memory again just once when you are done completely and don't need it any more. That will compensate the virtual function call by much...


Are there infinitely many natural numbers $n$ such that $\mu(n)=\mu(n+1)=\pm 1$?

Question: A while ago, I answered this question here on StackExchange which asks if for any given integer $k$, whether there exists infinitely many natural numbers $n$ such that
$$ \mu(n+1)=\mu(n+2)=\mu(n+3)=\cdots=\mu(n+k) $$
This is indeed the case, and can be shown using the Chinese Remainder Theorem, as in my answer to the linked question. We find infinitely many $n$ such that the common value of $\mu$ evaluated at these points is $0$.
If $k \geq 4$, then one of the values $n+1, n+2, n+3, n+4$ is a multiple of $4$, and hence the common value must, in fact, actually be $0$. For $n<4$, this argument doesn't work, and we can't rule out the possibility that
$$ \mu(n+1)=\cdots=\mu(n+k)=\pm 1 $$
My question concerns the case of $k=2$. Are there infinitely many natural numbers $n$ such that either
$$\mu(n) = \mu(n+1) = 1$$
or
$$\mu(n) = \mu(n+1) = -1?$$
Comment: This MO post seems related, too: [Are there infinitely many triples of consecutive square-free integers?](http://mathoverflow.net/questions/59741/are-there-infinitely-many-triples-of-consecutive-square-free-integers)
Comment: Related: http://math.stackexchange.com/questions/564581/m%C3%B6bius-function-of-consecutive-numbers?rq=1
Comment: Surely this happens because square free numbers have asymptotic density.I don't have a proof right now but I can imagine it is possible to find one.
Comment: @KonstantinosGaitanas The fact that some set has density does not necessarily mean that there are consecutive numbers from that set. (Consider even numbers.) However, we know that for the square-free numbers density is $6/pi^2$.
Comment: It is almost certain that the primorials $p$#$\pm 1$ are squarefree. If this is actually true, there are infinite many triples $(n,n+1,n+2)$, such that $n,n+1,n+2$ are all squarefree. It would be even enough to show that sufficiently large primorials are squarefree.
Comment: Numbers $n$ such that $\mu(n)=\mu(n+1)=\mu(n+2)=1$ are tabulated at https://oeis.org/A063838. If $p=2r+1$ and $q=3r+1$ are both prime, then $2q$ and $3p$ are consecutive numbers with $\mu=1$, and by standard conjectures there are infinitely many such $r$.
Answer: It is a standard conjecture in Number Theory that there exist infinitely many $s$ such that $p=10s+1$, $q=15s+2$, and $r=6s+1$ are all prime. Then $3p=30s+3$, $2q=30s+4$, and $5r=30s+5$ are consecutive integers, each a product of two primes, so $\mu(3p)=\mu(2q)=\mu(5r)=1$.
Answer: This is not an answer, just a different perspective to the problem.
Let's look at the following Diophantine equation:
$$3\cdot x=2\cdot y + 1$$
It has one solution $(1,1)$ and as a result infinitely many $x=1+2\cdot t$, $y=1+3\cdot t$, $t \in \mathbb{N}$.
Both these arithmetic progressions will generate infinitely many primes (https://en.wikipedia.org/wiki/Dirichlet%27s_theorem_on_arithmetic_progressions). Question is, will they both generate infinitely pairs of primes for the same $t$?
And, Green-Tao extension (https://en.wikipedia.org/wiki/Green%E2%80%93Tao_theorem#Extensions_and_generalizations) says that $k+2\cdot t$, $k+3\cdot t$ will be simultaneously primes for infinitely many $k$ and $t$, but we need $k=1$.
Obviously, any prime pair $(p_1, p_2)$ (e.g. $(5, 7)$), solution of this equation, satisfies:
$$1=\mu(2\cdot p_2)=\mu(3\cdot p_1)=\mu(2\cdot p_2+1)$$
Some related materials:
http://arxiv.org/pdf/1310.8140.pdf - Primes Solutions Of Linear Diophantine Equations
http://arxiv.org/pdf/math/0404188v6.pdf - The Primes Contain Arbitrarily Long Arithmetic Progressions


How to show ::after content on the same line as an  element?

Question: Have the following CSS that underlines a URL as desired:
.underline {
  text-decoration: none;
  position: relative;
}

.underline:after {
  position: absolute;
  content: '';
  height: 2px;
  bottom: -4px;
  margin: 0 auto;
  left: 0;
  right: 0;
  width: 50%;
  background: green;
  -o-transition: .5s;
  -ms-transition: .5s;
  -moz-transition: .5s;
  -webkit-transition: .5s;
  transition: .5s;
}

.underline:hover:after {
  width: 80%;
  background: orange;
}

On my page, some URLs are intra-page links, and the above works fine.
Other URLs are external links and, when selected, leave the page.
To signal the user that selecting the link will leave the page, I want to put a symbol after an anchor statement.
For example Wikipedia
So, have created an additional statement for URLs that are external links and include target="_blank"
a[target="_blank"]::after {
  content: "\279A";
}

But in that implementation, the symbol "\279A" appears on a new line, which is not what I want.
The follow fails:
a[target="_blank"]::after {
  content: "\279A";
  display: inline-block;
}

My question is: for a statement that looks like this:
Wikipedia

how to modify the CSS to remove the resulting line-break and keep the leave-page symbol adjacent to the link?
Answer: You have two separate selectors that apply styles to the same ::after pseudo-element. Both a[target="_blank"]::after and .underline:after are targeting the same thing. You can remove the positioning properties from .underline:after and the icon will be inline, or you can move the first styles to ::before:

.underline {
  text-decoration: none;
  position: relative;
}

.underline::before { /* I changed this to ::before from :after */
  position: absolute;
  content: '';
  height: 2px;
  bottom: -4px;
  margin: 0 auto;
  left: 0;
  right: 0;
  width: 50%;
  background: green;
  -o-transition: .5s;
  -ms-transition: .5s;
  -moz-transition: .5s;
  -webkit-transition: .5s;
  transition: .5s;
}

.underline:hover::before {
  width: 80%;
  background: orange;
}

a[target="_blank"]::after {
  content: "\279A";
}
Wikipedia
Comment: @JayGray Sorry, I forgot I removed as part of reducing the code to a [mcve]. One sec. Edit: OK, it's back in now.
Comment: the transition has stopped (i added back from my original but it is no longer animated). Would you update your answer to incorporate that original feature? (unless i'm missing something)
Comment: would you check your answer one more time for me please? In my question, the underline changes color and width. But I'm not getting that in your answer. I tried the inline `Run code snippet` and also copied your answer to my target code - same result.
Comment: @JayGray Sorry, forgot to update the second `::after` to `::before` to match the pre-transitioned CSS. Run the snippet now and check
Comment: OK, i see that it does work correctly in `Run code snippet` but i'm getting a new line in my source code. Have tested in both Chrome and Mozilla. Gimme a sec to make sure I have not done something stupid on my side.


How to get attachments out of a twig file

Question: How do I get the attachments out a twig file and add them to a build array?
If there is a twig file with
<code>{{ attach_library('mytheme/pullquote') }}
</code>
And because it's in an ajax response, I need to get the attachments out without rendering the page, how do I get a new build array with that library attached?
In my controller:
<code>   $build['pullquote'] = [
      '#theme' => 'pullquote',
      '#quote_text' => $quote_text,
      '#attribution_name' => $attribution_name,
      '#attribution_title' => $attribution_title,
      '#size' => $size,
    ];

    $response = new AjaxResponse();
    $response->addCommand(new EmbedInsertCommand($build));
    return $response;
</code>
Because the library is added in twig and not in the build array, it's not coming through in the response.
The EmbedInsertCommand is from the embed module, which entity_embed inherits from, at embed/src/Ajax/EmbedInsertCommand.php
which uses the CommandWithAttachedAssetsTrait, with this function:
<code> /**
   * Processes the content for output.
   *
   * If content is a render array, it may contain attached assets to be
   * processed.
   *
   * @return string|\Drupal\Component\Render\MarkupInterface
   *   HTML rendered content.
   */
  protected function getRenderedContent() {
    $this->attachedAssets = new AttachedAssets();
    if (is_array($this->content)) {
      $html = \Drupal::service('renderer')->renderRoot($this->content);
      $this->attachedAssets = AttachedAssets::createFromRenderArray($this->content);
      return $html;
    }
    else {
      return $this->content;
    }
  }
</code>
Unfortunately, AttachedAssets::createFromRenderArray misses libraries added within twig.
Answer: Usually ajax commands which add html are able to catch attachments bubbling up when they render the content. Don't know EmbedInsertCommand(). The name clearly says it is an command inserting html, so it should be able to do it.
For commands not able to handle attachments you can render the content already in the controller and add the attachments to the response here:
<code>  $response = new AjaxResponse();
  $html = \Drupal::service('renderer')->renderRoot($build);
  $response->addCommand(new EmbedInsertCommand($html));
  $response->setAttachments($build['#attached']);
  return $response;
</code>
This is only a workaround, not the recommend way, because Ajax does some more processing of the attachments before adding them to the response, but for a single command this should be OK.
Comment: renderRoot() bubbles all attachments to `$build['#attached']`, no matter how deep they are nested inside of `$build`. So if the attachment is missing already at this point then it is not an Ajax issue.
Comment: Thanks for the answer, but $build['#attached'] lacks the libraries added through twig, so I could just attach the library outside the twig to the build array, but I was hoping there was a way to render the twig enough to extract the library attached within the twig.


Contar o total de casas decimais, em Delphi

Question: Preciso contar a quantidade de casas decimais em Delphi (10.1) em uma string, irei usar Edit, validando valores monetários ao digitar, antes de inserir no edit.
Consigo validar se é um Currency válido, mas ao comparar ele entende 1,23 igual 1,230. Claro, é válido.
Sei que existe a opção de arredondar, mas não é meu objetivo nesta etapa, e sim, meramente, contar a quantidade de casas decimais numa string, para, combinando com outras functions, impedir a digitação de mais casas, ou caracteres que não façam parte de um currency válido, incluindo mais zeros após 1,23.
Pesquisei bastante, e no momento cheguei a formula abaixo mas não creio ser a melhor (pog) ideia.
function ContarDecimaisTESTE(S: string):string;
//necessita verificar se é um (float,currency) valido antes.
var
  Saida: boolean;
  i,j, k: word;
  w: string;
  n: Integer;
begin
  k:= 0;
  Saida:= false;
  n:= length(s);
  i:= n;
  j:= 0;

  for I := 1 to n do
      begin
        w:=Copy(S,i,1);
        j:=j+1;
        if (w = ',') then
          begin
            Saida:=True;
            Break;
          end;
      end;

  if (Saida=True) then
    begin
      k:=(n-j);
    end else
      begin
        k:=0;
      end;
  Result:=IntToStr(k);

end;

Cheguei em algo melhor, bem parecido com a ideia do Junior, mas usei mais códigos:
function TamanhoCasasDec(S:string):Int64;//Teste
var
  a,b:integer;
  c:string;
begin
  a:=length(S);
  b:=pos(',',S);

  try
    c:=Copy(FilterChars(S,[',']),1,1);//copiar a primeira virgula, se houver
  except
    //
  end;

  if (c = ',') then
    begin
      Result:=Length(Trim(copy(S, b + 1, a - b)));
    end else
      begin
        Result:=0;
      end;

end;

Answer: No caso não seria apenas contar do separador ate o final da string?
Algo como:
function Obter_QtdCasasDecimais(aValor: String): Integer;
begin
  Result := Length(Copy(aValor, Pos(',', aValor)+1, Length(aValor)));
end;

Se for isto é simples
Comment: Nao podia ser só Length(aValor)-Pos(',', aValor) ? Nao percebo o uso do Copy :)
Comment: Pode sim, o lance de mostrar uma solução de modo vamos dizer procedural é que o cara acompanhe a evolução do que esta sendo feito. Ali eu ate abreviei alguns rsrsrsrs, eu costumo passar para variável etc...
Comment: Obrigado Júnior Moreira, cheguei em algo bem parecido com o que você postou. eu também quando a cabeça está o limite uso bastantes variáveis sugestivas (vrAntes,vrDepois), coloco até showmessage no meio para ir acompanhando. Depois, simplifico. A que você fez para 12,345 retorna 3, mas para "12" retorna 2. Tirando o tanto de firulas no meu código, consegui retornar 0 para "12" ou "12," , 1 para "12,1" e etc. Creio que vai funcionar.


How to rewrite link to taxonomy term in Views when using Pathauto?

Question: The default language of my site is English.  Taxonomy terms are translated using Entity Translation.  I have created a view that uses aggregation to show Japanese terms (name provided by the Title module).
However, the Japanese terms do not have a path alias, so I need to rewrite the link provided by the view to point to the English term.  The URL aliases of the English terms are generated by Pathauto, which strips some words ("to" in "Things I like to do").
Example:

English term: Listening to Music
Pathauto alias: listening-music
Japanese term: 音楽鑑賞
Desired output: 音楽鑑賞 (link pointing to listening-music)

I tried rewriting the link to [name] (the English term) with conversion to lowercase and spaces converted to dashes, but this causes the link to be listening-to-music, not listening-music.  Ideally, I would like to keep pathauto settings as they are and somehow grab the URL of the term within views.  Is this possible?
Answer: To get path of taxonomy term in default language (in your case it is English) you can use url() function, example:
<code>$term_url = url('taxonomy/term/'. $term->tid, array('language' => language_default()));
</code>
Answer: I solved this by removing all the prepositions from the "Words to exclude from paths" on the Pathauto configuration page and then deleting and bulk updating all taxonomy aliases.  For those aliases with () or other symbols in their names, I manually added redirects using the Redirect module.  Not pretty but it works.


Consulta com vários Ids e data com JPA e Spring via RESTApi

Question: Bom dia, estou tentando montar um consulta com Spring JPA e Rest onde posso inserir diversos IDs e datainicial e datafinal. A consulta funciona se eu colocar somente um ID com as datas. O código está dessa forma:
@GetMapping("/search")
public List<TagsDay> pesquisar(@RequestParam(value = "ids") List<Long> ids, TagsDayFilter tagsDayFilter){
    return tagsDayRepository.filtrar(ids, tagsDayFilter);
}

Interface:
public interface TagsDayRepositoryQuery {

    public List<TagsDay> filtrar(List<Long> ids, TagsDayFilter tagsDayFilter);

}

e a classe de implementação:
public class TagsDayRepositoryImpl implements TagsDayRepositoryQuery{

    @PersistenceContext
    private EntityManager manager;

    @Override
    public List<TagsDay> filtrar(List<Long> ids, TagsDayFilter tagsDayFilter) {

        CriteriaBuilder builder = manager.getCriteriaBuilder();
        CriteriaQuery<TagsDay> criteria = builder.createQuery(TagsDay.class);

        Root<TagsDay> root = criteria.from(TagsDay.class);

        //criar as restrições
        Predicate[] predicates = criarRestricoes(ids, tagsDayFilter, builder, root);
        criteria.where(predicates);

        TypedQuery<TagsDay> query = manager.createQuery(criteria);
        return query.getResultList();
    }

    private Predicate[] criarRestricoes(List<Long> ids, TagsDayFilter tagsDayFilter, CriteriaBuilder builder, Root<TagsDay> root) {

        List<Predicate> predicates = new ArrayList<>();

        if(ids.size() > 0) {

            for(int i = 0; i < ids.size(); i++) {
                predicates.add(builder.equal(root.get("id"), ids.get(i)));  //adiciona vários ids para consulta
            }

        }
        if(tagsDayFilter.getDataInicial() != null) {
            predicates.add(builder.greaterThanOrEqualTo(root.get("data_coleta"), tagsDayFilter.getDataInicial()));
        }
        if(tagsDayFilter.getDataFinal() != null) {
            predicates.add(builder.lessThanOrEqualTo(root.get("data_coleta"), tagsDayFilter.getDataFinal()));
        }

        return predicates.toArray(new Predicate[predicates.size()]);
    }

}

e na URL faço: localhost:8080/tagsday/search?ids=1,2&dataInicial=2018-09-27&dataFinal=2018-09-28
Comment: Qual o erro? Coloca na descrição da pergunta.
Comment: Não gera nenhum erro, apenas não retorna nada. A query foi gerada dessa forma: select tagsday0_.id as id1_2_, tagsday0_.data_coleta as data_col2_2_, tagsday0_.tags_id as tags_id4_2_, tagsday0_.valor as valor3_2_ from tags_day tagsday0_ where tagsday0_.id=1 and tagsday0_.id=2 and tagsday0_.data_coleta>=? and tagsday0_.data_coleta<=?
Comment: Já tentou usar `@Query`, montando uma consulta personalizada? Algo como `@Query("SELECT t FROM TagsDay t WHERE t.id IN (?1) AND (t.data BETWEEN ?2 AND ?3)")`, em que 1 é a lista, 2 seria a data inicial e 3 a data final. Dê uma olhada [aqui](https://stackoverflow.com/questions/49422953/spring-data-jpa-query-arraylist-as-param)
Comment: Bom dia, então, eu gostaria de manter dessa forma pois preciso entender como funciona, via SQL normal seria bem fácil. Uma coisa que percebi é que se ao invés da consulta gerar um AND, a mesma fosse por OR funcionaria. É possível fazer essa mudança?
Answer: Para passar vários ids
Simplesmente acrescente ao query param aquele atributo várias vezes !
// Exemplo passando um queryParam com vários ids
localhost:8080/tagsday/search?ids=1&ids=2&dataInicial=2018-09-27&dataFinal=2018-09-28

Perceba que aparece "?ids=1&ids=2" essa repetição é entendida como um array(ou Lista) pelo método !
Sobre a duvida de acrescentar OR a chamada do Criteria
Há uma forma de fazer um OR sim !!
Aqui eu criei um método para retornar os predicados em forma de OR :
protected Predicate[] orPredicates(CriteriaBuilder builder, List<Predicate> predicates) {
    List<Predicate> returnPredicate = new ArrayList<>();

    if(predicates.size() > 0) {
        Predicate orPredicate = builder.or(predicates.toArray(new Predicate[predicates.size()]));
        returnPredicate.add(orPredicate);
    }

    return returnPredicate.toArray(new Predicate[returnPredicate.size()]);
}

e uso da seguinte forma, ao invés de retornar:
return predicates.toArray(new Predicate[predicates.size()]);

eu retorno o método:
return orPredicates(builder, predicates);

.
Mas, e se precisar ter alguns predicados com AND e outros com o OR ?
Você deve ter percebido que a solução anterior fará com que TODOS os predicates fiquem com OR !!
Por causa disso, quando eu quero incluir uma parte da querie com OR e outra com AND eu faço uma "List de Predicate local" e adiciono o retorno do método de OR no predicates mandatório da seguinte forma :
...
// Predicados locais que devem ser do tipo OR
List<Predicate> predicatesLocal = new ArrayList<>();

if(tagsDayFilter.getDataInicial() != null) {
    predicatesLocal.add(
        builder.greaterThanOrEqualTo(root.get("data_coleta"), tagsDayFilter.getDataInicial())
    );
}

if(tagsDayFilter.getDataFinal() != null) {
    predicatesLocal.add(
        builder.lessThanOrEqualTo(root.get("data_coleta"), tagsDayFilter.getDataFinal())
    );
}

Predicate pred = builder.or( orPredicates(builder, predicatesLocal) );
predicates.add(pred);
...

No final ele montá o predicado como deve ser montado !
Código final do método de restrições:
private Predicate[] criarRestricoes(List<Long> ids, TagsDayFilter tagsDayFilter,
                                    CriteriaBuilder builder, Root<TagsDay> root) {
    List<Predicate> predicates = new ArrayList<>();

    if(ids.size() > 0) {
        for(int i = 0; i < ids.size(); i++) {
            //adiciona vários ids para consulta
            predicates.add(builder.equal(root.get("id"), ids.get(i)));
        }
    }

    // ----------------- PREDICADOS COM OR -----------------
    // Predicados locais que devem ser do tipo OR
    List<Predicate> predicatesLocal = new ArrayList<>();

    if(tagsDayFilter.getDataInicial() != null) {
        predicatesLocal.add(
            builder.greaterThanOrEqualTo(root.get("data_coleta"), tagsDayFilter.getDataInicial())
        );
    }

    if(tagsDayFilter.getDataFinal() != null) {
        predicatesLocal.add(
            builder.lessThanOrEqualTo(root.get("data_coleta"), tagsDayFilter.getDataFinal())
        );
    }

    Predicate pred = builder.or( orPredicates(builder, predicatesLocal) );
    predicates.add(pred);
    // -----------------------------------------------------

    return predicates.toArray(new Predicate[predicates.size()]);
}

Esse método irá retornar um SQL parecido com :
SELECT TAG.id, TAG.data_coleta, TAG.tags_id, TAG.valor
  FROM tags_day TAG
 WHERE TAG.id = 1
   AND TAG.id = 2
   AND (TAG.data_coleta >= ? OR TAG.data_coleta <= ?)


How to show tooltip on legend hover?

Question: I am using chart.js in React.
I have read and implemented:
Chart.js - show tooltip when hovering on legend
Unfortunately, this is not providing the desired results. I believe this is because this is being implemented in javascript, and I am implementing react. Not sure if that is impacting anything.
const data = {
    labels: ['One', 'Two', 'Three'],
    datasets: [{
      data: [4, 5, 3],
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(54, 162, 235, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(54, 162, 235)'],
      hoverBackgroundColor: ['rgba(255, 99, 132, 0.4)', 'rgba(255, 159, 64, 0.4)', 'rgba(54, 162, 235, 0.4)'],
      borderWidth: 1,
      hoverBorderWidth: 3
    }]
  };

  const options = {
    plugins: {
      legend: {
        onHover: (evt: any, legendItem: any, legend: any) => {
          const index = legend.chart.data.labels.indexOf(legendItem.text);
          const activeSegment = legend.chart.getDatasetMeta(0).data[index];
          // console.log(activeSegment);
          // activeSegment.options.backgroundColor = activeSegment._options.hoverBackgroundColor;
          // activeSegment.options.borderWidth = activeSegment._options.hoverBorderWidth;
          legend.chart.tooltip._active = [activeSegment];
          legend.chart.update();
          legend.chart.draw();
        },
        onLeave: (evt: any, legendItem: any, legend: any) => {
          const index = legend.chart.data.labels.indexOf(legendItem.text);
          // const activeSegment = legend.chart.getDatasetMeta(0).data[index];
          // activeSegment.options.backgroundColor = activeSegment._options.backgroundColor;
          // activeSegment.options.borderWidth = activeSegment._options.borderWidth;
          legend.chart.tooltip._active = [];
          legend.chart.update();
          legend.chart.draw();
        }
      },
    },

  }

with the end of this component returning the following:
return <Doughnut data={data} options={options} />;

This produces the chart that is shown in the stackoverflow post that I linked.
Comment: what library / package did you use to render chart react-chartjs-2 or chart.js ?
Comment: react-chart-js-2 @monesul haque
Answer: For v3 you can use an method to set the tooltip programatically
 onHover: (evt, item, legend) => {
          const chart = legend.chart;
          const tooltip = chart.tooltip;

          const chartArea = chart.chartArea;
          tooltip.setActiveElements([{
            datasetIndex: 0,
            index: item.index,
          }], {
            x: (chartArea.left + chartArea.right) / 2,
            y: (chartArea.top + chartArea.bottom) / 2,
          });

          chart.update();
        },

Comment: this solves the problem of displaying the tooltip when I hover over a legend label, however I cannot hover over between labels quickly. Do you know a possible solution to this?

For instance, hovering over One and quickly switching to Two in the legend will cause the Two tooltip not to appear.

How to show tooltip on legend hover?


Capturing video from a MJPEG stream using C++

Question: I would like to capture a MJPEG stream using C++. Which options do I have? I have tried OpenCV with FFMPEG support but icvCreateFileCapture_FFMPEG_p is always returning null (after a few seconds of timeout). May I program a HTTP client by myself?
Regards,
Answer: M-JPEG is easy to capture. You send one HTTP request to the server and read back infinite response in multipart/x-mixed-replace format (Content-Type). Then you split it into frames, which are self-contained JPEG files... Subheaders might or moight not contain additional information such as timestamps.
You might find this relevant and useful as well: How to parse MJPEG HTTP Stream within C++?


Why do many franchises sign long-term TV deals

Question: Many teams sign long-term local TV deals of 10 years or more. Many times these deals end up being poor and below market-value after a few years. The Pittsburg Pirates deal being a good example (only about 40 million USD per year). It seems that teams that don't have their own networks, like NESN or YES get a bit screwed.
Why do teams keep signing these deals? What is the benefit to them if they typically end up being bad.
Answer: Many times these long term contracts come with large amounts of cash up front, as is the case with the Texas rangers new 20 year $3billion deal with Fox Sports.

It doesn't take effect until 2015, but the Rangers received $160 million cash up front and an equity stake in Fox Sports Southwest.

http://www.usatoday.com/sports/baseball/story/2012-02-06/MLB-teams-using-lucrative-TV-deals-to-sign-talent/53032284/1
That article also goes on to state the viewership of a team like the Yankees on the YES network (318,000 average) vs a smaller market team like the Royals (32,000).  Taken in that context, the Pittsburgh deal may not be all that bad.
It may not be the best thing for parity in the league, but considering many teams are getting large front loaded contracts, equity stakes in TV networks that can be worth more than their franchises, and predictable cash flow, these deals can be a huge win for organizations.
Answer: A naive guess would be the charm of guaranteed income over hypothetical income. Don't know how the finances are run in trade based sports (as in american leagues) but in transfer based leagues, teams often try and spend only the money that they know they have/will have.
Again another difference is probably in the tv coverage of teams, most European leagues have centralized TV deals, profits of which are then distributed to teams based on their estimated viewership or public interest. In a scenario where teams sign their own deals, I presume the better teams with more fans will get the majority of the deals, while lesser teams try to get the best they can find. If that's a long term deal then it might even be preferable since it means that they dont have to worry about trying to find the best deal again the coming year.
As I mentioned earlier I am not too familiar with the system in the U.S. but I tried to mention some possible motives for signing long term TV-deals.


How to call objects from a class in a function of another class

Question: I want to use an object of a class in a function of another class. I know it's a really easy thing to solve, but I still can't figure it out.
I have the following class that is an object of players
class Players():
    def __init__(self, name_player, surname, age, height, wheight):
        self.name_player= name_player
        self.surname = surname
        self.age= age
        self.height= height
        self.wheight= wheight
    def __repr__(self):
        return "{}, {}, {}, {}, {} //".format(self.name_player,self.surname,self.age,self.height,self.wheight)

Then I have this class of teams
class Teams():
    def __init__(self, name, points, goals_in_favour, goals_against):
        self.name= name
        self.points= points
        self.goals_in_favour= goals_in_favour
        self.goals_against= goals_against

    def __repr__(self):
        return "{} : {} : {}: {}".format(self.name,self.points,self.goals_in_favour,self.goals_against)

Now in the function 'ages' I want it to return a list of the players with an age less or equal to the one on the file. If I write 'i.Players.age' it sends me an error, which is the right way to spell it?
def ages(lists_teams,age):
    list_players =""
    return [list_players + i for i in list_teams if (i.Players.age <= age)]

(I have to write it in a list comprehension way).
Thanks a lot in advance.
Comment: You donot need call class.  i.Jugadores.edad, try change it to i.Jedad. i  is already an class object here. Another mistake is lista_jugadores should be a list instead of a string?
Comment: Just a small comment on style- the variable name `i` is [traditionally used to indicate an index](https://stackoverflow.com/questions/4137785/why-are-variables-i-and-j-used-for-counters), not an the object in the list, so it can be a little confusing the way you have used it.
Comment: For the function `edades`, is `lista_selectiones` supposed to be a List of `Selection` objects?
Comment: What do you mean by  list comprehension way, i is an object, while list_players is string. You cannot add object to a string......
Answer: To help you understand.
1.If list_teams is already an list of objects...you cannot call i.Players, because i here is already an object.
2.list_players="" you should change it to []...."" is not a list, you cannot add object on to it.
3.Try not use i for object, it is normally used to indicate an index..
def ages(list_teams,age):
    list_players =[]
    return [list_players + [player] for player in list_teams if (player.age <= age)]

Comment: I´ve tried it, but it says: " AttributeError: 'str' object has no attribute 'age' "
Comment: @Gonzalo Adrover, you need to create an list of object first. Like David=Players("David","Bechham",40,190,70) Tom=Players("Tom","Hanks",49,180,80) And list_teams=[David,Tom]


Call a Oracle Procedure in a Java Batch containing Insert and Update Queries (Statement)

Question: I am working on a Java based project, where things are implemented in the following way

There are some classes (A,B,C,D....) which takes Hash Map having key as an Integer and value as an array list of String. Every String element in the arraylist is a Oracle SQL Query (INSERT or UPDATE)
These methods of classes (A,B,C,D....) loops through the Map. All the SQL Queries of a particular key are added to a batch using JDBC Statement (**stmt.addBatch(String)**). For every unique key, there is a separate batch created and executed.
There are many classes (X,Y,Z...) which are working on populating this Map and arraylist of Strings to put different INSERT and UPDATE Queries

Now, I need to add an Oracle procedure call for some keys and hence should be added to the String Arraylist for the respective keys.
I tried adding the following strings to call procedures, but no one seems to work for me.
1. EXEC INSERT_AUTONUMBER_DATA(......)

2. BEGIN INSERT_AUTONUMBER_DATA(........) END;

I don't want to modify much of the code, as it might impact the other areas.
I can add a Callable Statement in the batch, but for this, I will need to modify all the methods and classes which takes responsibility for preparing the batch which are around 15 in my project (Project Design is not very good), plus I will have to write a condition identifying a procedure call, so that I will prepare a callable statement instead of a Statement.
Is there any other way of doing it, without changing the classes executing the batches?
Answer: I tried the following call statement to add in the batch.
CALL INSERT_AUTONUMBER_DATA(......)

This String is getting added in a Statement with the following logic and it works.
Statement s = conn.createStatement();
s.addBatch("CALL INSERT_AUTONUMBER_DATA(......)");
s.addBatch(.....);
.
.
.

s.executeBatch();

So, here I am able to call a procedure via java.sql.Statement in a Batch


Contraction mapping theorem/Fixed point theorem application

Question: The question is as follows:
Use the contraction mapping theorem to show that the following system of equations:

$x_1$ + $\dfrac{1}{10}\cos(2x_1 + x_2)$ = $1$

$x_2$ + $\dfrac{1}{10}\sin(x_1 + x_2)$ = $2$.

has a unique solution $(x_1, x_2)$ on $\mathbb{R^2}$.
I'm a little familiar with the contraction mapping theorem in terms of one variable, but this is a whole different beast....any push in the right direction is appreciated!
Comment: Let us try the obvious thing first. Define $x=(x_1,x_2)^T\in\mathbb{R}^2$, rearrange the given two equations gives $x=Tx$, where $T\colon\mathbb{R}^2\longrightarrow\mathbb{R}^2$ is the map defined by $Tx=(1-0.1\cos(2x_1+x_2), 2-0.1\sin(x_1+x_2))$. Now, you have to pick a metric on $\mathbb{R}^2$ and show that $T$ is a contraction. I don't know how this will end but try write out $d(Tx,Ty)$ and see what happens!
Answer: Get $x_1$ and $x_2$ into their own equations and then find the Jacobian matrix. Then apply the $\infty$-norm to find $q$ which will be between zero and one, not inclusive.
Edit (by popular demand):
I wrote this on my phone whilst picking up dinner, so please do excuse my terse response.
Here is what I mean by getting $x_1$ and $x_2$ by themselves. You want \begin{align*}x_1&=\frac{1}{10}[1-x_2-\sin(x_1+x_2)]\\x_2&=\frac{1}{10}[2+x_1+\cos(x_1-x_2)]\end{align*} and then you will find the Jacobian matrix by taking partial derivatives with respect to $x_1$ and $x_2$. Then use the $\infty$-norm of the Jacobian to find what $q$ is.
Comment: I made edits to my original response. I hope that this sheds some light on what I mean. I hope that the Jacobian part is pretty straightforward, but if not, let me know.
Comment: Maybe you can show us how this looks? Not sure what you mean: "*Get x1
 and x2
 into their own equations*"
Answer: The way to apply the contraction theorem is to write it in the form $f(\overrightarrow{X})=\overrightarrow{X}$ for $\overrightarrow{X}=(x_1, x_2).$ The form of the equations sort of gives away what $f$ should be; you then just need to show that it is a contraction. That is, show that $|f(\overrightarrow{X})-f(\overrightarrow{Y})|\leq c|\overrightarrow{X}-\overrightarrow{Y}|$ for all pairs of vectors, and for $c<1$. From there you get that $f$ has a unique fixed point, which is what you want.
Comment: So we have that $\overrightarrow{X}$ = $(x_1, x_2)$, and thus all coordinates are of the form $\overrightarrow{X}$ = $(1 - .1cos(2x_1 + x_2), 2 - .1sin(x_1 + x_2))$, no? I'm just a bit confused as to how we compare $\overrightarrow{X}$ and $\overrightarrow{Y}$ in this case....
Comment: Using the Pythagorean theorem: adding the squares of the difference of coordinates. But, you can also take the $2\times 2$ Jacobi matrix (differential of $f$: consisting of rows $\partial_1f,\ \partial_2f$) and show that its norm is always less than $1$.
Comment: @mizichael not exactly. What is $f$ in this case? And "comparing" is just done by subtracting, as in my answer.
Comment: @Berci I'm sorry if I'm being dense but I'm really not following...the contraction mapping theorem really confuses me because I never feel like I know for sure what, for example, $f(\overrightarrow{X})$ is in this case, or how I would even go about proving that |$f(\overrightarrow{X}) - f(\overrightarrow{Y})$| $\leq$ $c|\overrightarrow{X} - \overrightarrow{Y}|$....
Comment: @BobJones wait, is it such that $\overrightarrow{X}$ = $(x_1, x_2)$, and $f(\overrightarrow{x})$ = the corresponding values of $x_1$ and $x_2$, or $1 - .1cos(2x_1 + x_2)$ and $2 - .1sin(x_1 + x_2)$? I mean surely notationally this is incorrect, but is the premise that this function $f$ gives us $1 - .1cos(2x_1 + x_2)$ and $2 - .1sin(x_1 + x_2)$ when we plug in any $x_1$, $x_2$?
Comment: @mizichael If I tell you that $f(x_1, x_2)=(1-0.1\cos(2x_1+x_2), 2-0.1\sin(x_1+x_2))$, does that help? It is perfectly possible to have your output be a vector. Also, what is it that you want to prove, written out in terms of $x_1$ and $x_2$? It looks nicer than you might think.
Comment: @BobJones Okay, I think a big problem I've had is getting my head wrapped around the notion that the output could simply be a vector. We want to prove that there exists a unique $(x_1, x_2)$ which satisfies the series of equations, and we can prove this if we can prove there exists a $c$ such that the inequality mentioned earlier holds. Is this right?
Comment: @mizichael exactly. Can you continue?
Comment: @BobJones sorry, just had to think about that for a second. Okay, so we need to prove the inequality, and we have that $f(\overrightarrow{X})$ (where $\overrightarrow{X}$ = ($x_1, x_2$)) = $(1 - 0.1 cos(2x_1 + x_2), 2 - 0.1 sin(x_1 + x_2))$. How do we write out something like |$f(\overrightarrow{X}) - f(\overrightarrow{Y})$| then?
Comment: @BobJones Wait...would |$f(\overrightarrow{X}) - f(\overrightarrow{Y})$| = |$-0.2 cos(2x_1 + x_2)$, $-0.2 sin(x_1 + x_2)$|?
Comment: @mizichael Say $\overrightarrow{Y}=(y_1, y_2)$. Then what is $f(\overrightarrow{Y})$? From here, you should be able to subtract the vector outputs of $f$, right? Then the absolute value is just by Pythagorean theorem.
Comment: @BobJones then $f(\overrightarrow{Y})$ = $(1 - 0.1cos(2y_1 + y_2), 2 - 0.1 sin(y_1 + y_2))$. Hmm....I think I see. However, how do I apply the Pythagorean theorem here to move forward in the proof? I'm just a little confused about that. I think I have the notation down now, but the proof is eluding me (thank you so much for all of your help up to this point!)
Comment: @mizichael If we rewrite what you want to prove based on what we've discovered, we want to show $|(0.1\cos(2y_1+y_2)-0.1\cos(2x_1+x_2), 0.1\sin(y_1+y_2)-0.1\sin(x_1+x_2)|\leq|(x_1-y_1, x_2-y_2)|$. Do you agree? Now the question is what the absolute value of a vector is. There's many different possibilities, but the usual is that $|(a_1, a_2)|=\sqrt{a_1^2+a_2^2}$. This is where the Pythagorean Theorem comes in. And once you see this, this is where the real difficulty of the problem is. You have to show some weird inequality to do with $\sin$ and $\cos$.
Comment: @BobJones ah, I understand now. Luckily I'm fairly strong in algebraic manipulation - the whole premise of the problem was just baffling to me! But it seems fairly clear to me now. Thanks again for taking all this time to help me out - I really appreciate it.


Let $m,n \in \mathbb N^+$. Define an explicit bijection from the Cartesian product $\lceil m \rceil \times \lceil n \rceil$ to $\lceil mn \rceil$.

Question: Here's the problem:
Let $m,n \in \mathbb N^+$. Define an explicit bijection from the Cartesian product $\lceil m \rceil \times \lceil n \rceil$ to $\lceil mn \rceil$.
My Progress:
Obviously, I'm dealing with a sort of $n \times m$ matrix. So, I tried to use a few smaller numbers and generalize a "rule" (or "mapping," I suppose) from that. For example, I used the case where $m=2$ and $n=3$ and, so, the function looked like this:
$f(0,0) \to \{0\}$
$f(0,1) \to \{1\}$
$f(0,2) \to \{2\}$
$f(1,0) \to \{3\}$
$f(1,1) \to \{4\}$
$f(1,2) \to \{5\}$
That didn't seem to help very much, though. I'm thinking that I might be going about this the wrong way. Any guidance here would be appreciated. Thanks!
Comment: Map $(1,1)$, $(1,2)$, $(1,3)$, and so on up to $(1,n)$ to $1,2,3,\dots, n$ respectively. Map $(2,1)$, $(2,2)$ and so on up to $(2,n))$ to $n+1,n+2,\dots,2n$. Continue.
Comment: I am curious: what does the notation $\lceil n \rceil$ mean? Is it for $\{1,2,\dots,n\}$?
Comment: It is $\{0,1,...,n-1\}$.
Answer: If you think about it like a matrix so that $f(i, j)$ goes to the $ij^{\text{th}}$ entry of the matrix, then just fill in the values $1,...,mn$ in the matrix.  If you do it in an organized fashion, like $1,2, ..., m$ in the first row, $m+1, m+2, ..., 2m$ in the second row, etc, then the nice formula you get is: $f(i, j)=(i-1)n + j$ where your matrix has $m$ rows and $n$ columns ($1\leq i\leq m$ and $1\leq j\leq n$).
Answer: Each carton can be packed with 15 water bottles. If the number of bottles is 90 it takes 6 cartons.
Let $N\leq90$ be the number of water bottles: Instead of specifying $N$ I can alternatively specify two numbers: $q={}$how many cartons were used fully,  and $r={}$how many bottles are the in last carton that is not packed to the full.
Clearly $0<q\leq6$ and $0\leq r < 15$. On the other hand given $q'$ and $r'$ in the same range as $q$ and $r$ respectively it determines a unique $N'\leq90$.


Notation for Matrix Representation of linear Transformation

Question: Are these notations similar.
$M_{B'}^{B}$ AND $M_{B}^{B'}$ OR $T_{B'}^{B}$ AND $T_{B}^{B'}$
Where M is change of basis from B to B'.
In my university book there is no clear indication of the same. Also, I have seen people on YouTube are referring this as linear transformation with respect to bases B and B'.
So does it not matter if we write B as subscript and B' as superscript or vice-versa.
Here is the link to book: https://egyankosh.ac.in/bitstream/123456789/87789/1/Unit-9.pdf
Comment: I don't think that any of these is a standard notation so whatever is the definition in your book you should use that. If it makes your work easier than redefine it...
Answer: My preferred notation for this is that if $T: U \to V$ is a linear transformation with bases $B \subseteq U$ and $C \subseteq V$, then ${_C[T]_B}$ is the matrix of $T$ with respect to these bases. The reason for this is that you put in something in the basis $B$ on the right side of ${_C[T]_B}$, and you get something in $C$ on the left side. You also get nice rules, for example if we also have $S: V \to W$ and $D \subseteq W$ is another basis, the following equation holds over matrices:
$$   {_D[S]_C} \, {_C[T]_B} = {_D[S \circ T]_B},$$
where on the LHS we are using matrix multiplication, wheras on the RHS $S \circ T $ is the composition of linear operators. The double $C$ in the middle "cancels".
From this equation though, you can figure out that if $T: V \to V$ is an operator and $B, C \subseteq V$ are both bases, then the matrices ${_B[T]_C}$ and ${_C[T]_B}$ are not the same. In particular, if $\operatorname{id}_V: V \to V$ is the identity operator, then ${_C[\operatorname{id}_V]_B}$ is the change-of-basis matrix from $B$ into $C$, while ${_B[\operatorname{id}_V]_C}$ changes from $C$ into $B$, and by the equation above we have
$$ {_B[\operatorname{id}_V]_C} \, {_C[\operatorname{id}_V]_B} = {_B [\operatorname{id}_V]_B} = I,$$
and hence those change-of-basis matrices are inverses of each other.
Comment: Wow, that's really intuitive notation, never seen it before
Comment: @joppy Thank you so much, this really helped me to understand how this works.


How do you add a numpy.array as a new column to a pyspark.SQL DataFrame?

Question: Here is the code to create a pyspark.sql DataFrame
import numpy as np
import pandas as pd
from pyspark import SparkContext
from pyspark.sql import SQLContext
df = pd.DataFrame(np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]), columns=['a','b','c'])
sparkdf = sqlContext.createDataFrame(df, samplingRatio=0.1)

So that sparkdf looks like
a  b  c
1  2  3
4  5  6
7  8  9
10 11 12

Now I would like to add as a new column a numpy array (or even a list)
new_col = np.array([20,20,20,20])

But the standard way
sparkdf = sparkdf.withColumn('newcol', new_col)

fails.
Probably an udf is the way to go, but I don't know how to create an udf that assigns one different value per DataFrame row, i.e. that iterates through new_col.
I have looked at other pyspark and pyspark.sql but couldn't find a solution.
Also I need to stay within pyspark.sql so not a scala solution. Thanks!
Answer: Assuming that data frame is sorted to match order of values in an array you can zip RDDs and rebuild data frame as follows:
n = sparkdf.rdd.getNumPartitions()

# Parallelize and cast to plain integer (np.int64 won't work)
new_col = sc.parallelize(np.array([20,20,20,20]), n).map(int)

def process(pair):
    return dict(pair[0].asDict().items() + [("new_col", pair[1])])

rdd = (sparkdf
    .rdd # Extract RDD
    .zip(new_col) # Zip with new col
    .map(process)) # Add new column

sqlContext.createDataFrame(rdd) # Rebuild data frame

You can also use joins:
new_col = sqlContext.createDataFrame(
    zip(range(1, 5), [20] * 4),
    ("rn", "new_col"))

sparkdf.registerTempTable("df")

sparkdf_indexed = sqlContext.sql(
    # Make sure we have specific order and add row number
    "SELECT row_number() OVER (ORDER BY a, b, c) AS rn, * FROM df")

(sparkdf_indexed
    .join(new_col, new_col.rn == sparkdf_indexed.rn)
    .drop(new_col.rn))

but window function component is not scalable and should be avoided with larger datasets.
Of course if all you need is a column of a single value you can simply use lit
import pyspark.sql.functions as f
sparkdf.withColumn("new_col", f.lit(20))

but I assume it is not the case.
Comment: Thanks. It looks like (first solution) you have to go back to RDD and then convert again to DataFrame at the end, no way of staying inside pyspark.sql.
Which of the two solutions provides better performance, i.e. faster?
Comment: Well, ignoring Catalyst, data frames are just an abstraction layer over RDDs. There is certainly an overhead from `sqlContext.createDataFrame` which can be significantly reduced by manually providing a schema. `zip` by itself is much simpler operation than join and as long as order is preserved you don't need sorting. I think that an important question is why do you need to add a new column. If it comes from other data source then loading it as table and join are the natural choice.
Comment: Actually I get the error message:
`ValueError: Can only zip with RDD which has the same number of partitions`
Comment: Right. The column does not come from another table, rather it is a manipulation of existing ones. It's fast to compute in numpy and I need to introduce the result as an additional column.
Comment: Regarding error just specify number of partitions on input. When it comes to your problem is it a row level operation or do you use multiple rows?
Comment: I perform row-level operations on each of five columns and then multiply row-wise each result. It seems numpy is fast, else I think I need temporary new columns to store result before final multiplication.
Comment: Well, If every operation is local  you could simply create an `udf` to handle this. There is no reason to add columns. Although an `RDD[Vector]` looks like a better choice here than a data frame.


How to denote a note that should only be played during first repeat without voltas?

Question: Look at this:

I want to skip the note indicated with a red arrow on second repeat. I know about this solution:

But I think it looks way to messy, considering it is only just one single note.
The main problem is that using voltas affects the staffs for other instruments too. So I want a solution that only affects the current staff.
How would you notate it?
Comment: I would replace the full rest under the seconda volta bracket by two halves: this aligns better with the bracket one and fits the rhythmic structure of 3/2.
Comment: @guidot I like the creativity of this, but that would only confuse the people who will be reading it. :)
Comment: Related: [Small changes between 1st and 2nd endings](https://music.stackexchange.com/questions/97960/small-changes-between-1st-and-2nd-endings)
Answer: Your lower solution isn't messy at all, and is precisely the kind of thing 1st and 2nd time bars are used for. However, if you really don't want to use them, simply bracket the notehead of the note you only want played the first time, and write in text above it "1st time only".
Comment: @guidot  So, fine:    Instead of "First Time Only",  write "Prima Volta".  For that matter, you could put a rest under the note and label it "Secunda Volta"
Comment: If there was a volta in one staff and no voltas in the others--or vice versa--I'd get confused and think your sheet music is messy. Keep volta use consistent between all staves.
Comment: @Klutt that doesn't matter. Performers are used to reading 1st and 2nd time bars that have no different notes in their own part. They will realise that this is because of changes in another part. This is very common in songs where the vocal part changes but instrumental parts are unchanged.
Comment: @klutt to add to what Bob B. commented: putting 1st and 2nd endings in all desks has the advantage of simplifying alterations or arrangements in the future.  You might want to add the pickup note for some other players, e.g.
Comment: I think the lower one looks very messy. I often use that construct for longer phrases, but for just one note I really want another solution.
Comment: But the main issue is that these voltas will also be in the staffs for other instruments.
Comment: Textual hints lack the charm of internationality , and the text would become long if one wants to point out, that the note should be replaced by rest.
Comment: @BobBroadley With all respect, you don't know the people who will read the music.
Comment: Nope, but I have composed and arranged music for hundreds of musicians. I'm just offering my advice. You certainly don't have to accept it.
Comment: @BobBroadley I appreciate it. I upvoted your answer, but I have not accepted it yet in hope of a better solution coming up.