Short exact sequence of homotopy groups

Question:
Let $p :E \to B$ be a weak fibration with section $s:B \to E$ and $F=p^{-1}(b_0)$. Show that the sequence $$0\longrightarrow \pi_n(F,s(b_0)) \xrightarrow{\quad i_*\quad}\pi_n(E,s(b_0))\xrightarrow{\quad p_*\quad}\pi_n(B,b_0)\longrightarrow 0$$ is exact at $\pi_n(E,s(b_0))$ for $n\ge1$.

To prove that $\operatorname{im}i_* \subset \ker p_*$ we can consider $[\alpha]=i_*([\beta])$ for $[\beta] \in \pi_n(F,s(b_0))$.
Now $$p_*([\alpha]) = [p\circ i \circ \beta] = [c_{b_0}]$$ i.e. $p_*([\alpha])$ is the identity.
I'm having some trouble proving that $\ker p_*\subset \operatorname{im}i_* $.
If we pick $[\alpha]\in \ker p_*$, then $\alpha : (I^n,\partial I^n) \to (E,s(b_0))$ and $p_*([\alpha])=[c_{b_0}]$. Now I need to construct an element $[\beta] \in \pi_n(F,s(b_0))$ such that $[\alpha]=i_*([\beta])$, but I have no idea how to come up with such $[\beta]$. What properties of the homotopy groups could I use here?
Comment: Hint: Have you used the definition of weak fibration yet?
Comment: @LeeMosher Not yet. I don't know how to use it here. I think I should apply it to $I^n$ somehow.
Answer: Since $p:E\to B$ is a weak fibration, it has homotopy lifting property with respect to all CW complexes. This is not immediately applicable as we are working with homotopy relative to subspace which requires additional constraints, but we can use the following result derived from HLP:

If $p:E\to B$ is a weak fibration, then it satisfies the relative homotopy lifting property with respect to the pair $(I^n,\partial I^n)$.

The idea of relative homotopy lifting with respect to the pair $(X,A)$ is as follows. Suppose we are given a homotopy $H$ between $f,g:X\to B$, a lifting $\tilde f$ s.t. $p\circ \tilde f=f$, and a lifted homotopy $\tilde h$ defined on $A\subseteq X$ such that $\tilde h|_{A\times\{0\}}=\tilde f|_{A}$, i.e., $p\circ \tilde h=H|_{A\times I}$, then we can find a lifting $\tilde H:X\times I\to E$ s.t. $\tilde H_{X\times\{0\}}=\tilde f$ and $\tilde H|_{A\times I}=\tilde h$. In terms of diagram (It seems that it's still impossible to draw diagonal arrows), this means that there exists $\tilde H:X\times I\to E$ that fills the diagram below. (Just imagine there is a map $\tilde H$ connecting the diagonal).
$\require{AMScd}$
\begin{CD}
X\times\{0\}\cup A\times I @>{\tilde{f}\cup\  \tilde h}>> E\\
@V{i}VV @VV{p}V\\
X\times I @>{H}>> B
\end{CD}
The diagram of (the ordinary version of) HLP is essentially the special case $A=\varnothing$.

Continue from your argument. We are given $\alpha:I^n\to E$ with $\alpha(\partial I^n)=\{s(b_0)\}$ and a homotopy $H:I^n\times I\to B$ relative to $\partial I^n$ between $p\circ \alpha$ and $c_{b_0}$. Restricting to $\partial I^n\times I$, $H$ can be lifted to $\tilde h=c_{s(b_0)}$. By relative homotopy lifting property, we can find a homotopy $\tilde H:I^n\times I\to E$ such that $p\circ \tilde H=H$ and $\tilde H|_{I^n\times\{0\}}=\alpha$, and $\tilde{H}|_{\partial I^n\times I}=c_{s(b_0)}$, so $\tilde H$ gives a homotopy between $\alpha$ and $\gamma=\tilde H|_{I^n\times\{1\}}$ relative to $\partial I^n$.
Now, we have $p\circ \gamma=p\circ \tilde H|_{I^n\times\{1\}}=c_{b_0}$, meaning that $\gamma(I^n)\subseteq p^{-1}(b_0)=F$. Therefore $\gamma$ factors through $F=p^{-1}(b_0)$, that is, we can find a map $\beta:(I^n,\partial I^n)\to (F,s(b_0))$ such that $\gamma=i\circ \beta$, where $i:(F,s(b_0))\hookrightarrow (E,s(b_0))$ is the inclusion of fiber.
This shows that $i_\ast([\beta])=[\gamma]=[\alpha]$, since $\alpha\simeq\gamma$ rel $\partial I^n$.

For a detailed proof of relative homotopy lifting property with respect to $(I^n,\partial I^n)$, see here. The proof uses a special homeomorphism of pairs $h:(I^n\times I, I^n\times\{0\}\cup\partial I^n\times I)\to (I^n\times I,I^n\times \{0\})$. For more information of this map, see here and here.

Short exact sequence of homotopy groups


How to appropriately compare colony-forming units (CFUs)?

Question: In microbial research, a common way to check growth rates of bacteria is by performing a dilution of the bacterial population and then plating the resulting dilution on a petri dish. After some time, the cells on the petri dish grow into visible colonies which you can then count to arrive at an estimate of the original population size ('colony forming unit' or CFU counts). For this method, it is important to use the right dilution so that your plates contain somewhere between 30-300 cells upon plating, which ensures that your counts are not too low (so that they are too affected by the stochasticity of your dilution process), nor too high (in which case the colonies are too close together, making it difficult to count them).
My question is quite fundamental: what is an appropriate statistical method to compare CFU counts? Say I have inoculated bacterial populations in test tubes and grown them under two experimental conditions (say, 25 and 30 degrees Celcius). How do I estimate (and test) the impact of temperature on bacterial growth? I have counts, so a Poisson GLM may be appropriate. However, what I measured (CFUs) is only a proxy for ACTUAL population size, for which I have no accurate measure. Also, even though I have counts, it is not quite clear to me whether they are generated by a Poisson process, where events happens with a certain constant probability per unit time. Cell divisions do happen with some probabilty per unit time, but every division generates more cells that can again divide - it intuitively seems to me that this exponential relationship complicates things.
Any insights on whether these considerations render a Poisson GLM problematic, and if so, what a better approach might be?
Answer:
what I measured (CFUs) is only a proxy for ACTUAL population size...

That's true of almost all technical measurements. A chemical concentration might be estimated by evaluating the optical absorbance at a particular wavelength. Expression of messenger RNA (mRNA) from a gene might be estimated by reverse-transcription into complementary DNA (cDNA) followed by a real-time quantitative polymerase chain reaction that is then monitored by the fluorescence of a probe.
In that respect, CFUs might be one of the assays closest in kind to what is most directly of interest. So long as the plating doesn't kill any bacteria, it provides a count that can be back-calculated to estimate the number of bacteria in the culture from which they were plated.

it is not quite clear to me whether they are generated by a Poisson process, where events happens with a certain constant probability per unit time...

The Poisson distribution is not limited to events occurring over time. It can be applied to any event that is rare over some extensive property: for example, few animals per unit area, or few cells per milliliter of volume.
The latter (few cells per milliliter, spread out to be a few cells per unit surface area) are how you think about using a Poisson distribution to describe your CFU data. You have taken a sample of the full bacterial culture and diluted it until it has only a small number of bacteria in the volume that you apply to the Petri dish. You then quickly spread out that volume over the entire surface of the dish so that no 2 bacteria are close to each other. Compared to the hour or so typical of a bacterial cell cycle, the few seconds needed for the dilution and spreading mean that any continuing replication of cells does not substantially affect the results.
The exponential growth in numbers over time comes into play after you have spread out the individual bacteria. You can't see a micrometer-scale single bacterium with the naked eye. After overnight culture on an adequately rich medium, the exponential growth means that each individual bacterium has produced a visible colony to count, separate from other colonies if you have the right dilution.
A Poisson model is thus an appropriate choice for such data. To get estimates for the original bacterial cultures from which you sampled, you should use an appropriate log-offset to represent the effective volume of original culture that you spread over the dish. This page and its links explain offsets in the context of time as the extensive variable, but the principle applies similarly to volumes or other extensive variables.


Grab values from string

Question: I have the following string:
$string = "email@example.com";
I'd like some PHP to grab the name and email address values from this string.
I'd originally tried the following but made no progress:
$str = "firstname.lastname@example.com";
preg_match_all('#value=([^\s]+)#', $str, $matches);
echo implode(' ', $matches[1]);

I'd essentially like to say:
echo $string['No+Label+name']; // outputs name
Comment: This is basically a query string format, so https://www.php.net/manual/en/function.parse-str.php can help you with that. (You'll only have to take into account that it will perform URL decoding, so the `+` will become spaces, in your array keys and the values.)
Comment: Looks like a querystring. Use https://www.php.net/manual/en/function.parse-str.php
Comment: Really good point @CBroe - thanks for this. Resolved now :-)
Comment: Note that we prefer a technical style of writing here. We gently discourage greetings, hope-you-can-helps, thanks, advance thanks, notes of appreciation, regards, kind regards, signatures, please-can-you-helps, chatty material and abbreviated txtspk, pleading, how long you've been stuck, voting advice, meta commentary, etc. Just explain your problem, and show what you've tried, what you expected, and what actually happened.
Answer: Not a great e answer but you can use this if you have this string
$str = "firstname.lastname@example.com";
$temp = explode('+', $str);
$name = explode('=',$temp[2]);
$email = explode('=',$temp[5]);
echo ($name[1]);
echo "
";
echo ($email[1]);

Grab values from string


How to create DataGrid with ComboBoxColumn using other DataContext than Grid itself?

Question: I am pretty new to WPF and I am stuck on this one, I couldn't find anything that helped me solve my problem.
I am trying to create DataGrid where I would like to compare multpiple people from imported file to people in database. My idea of that was creating told DataGrid (of person data) with ComboboxColumn (with list of people from database). My main problem is that both people to compare and to fill combobox, may differ because of user choice in previous window. Having some database work I save both choices in Window_Loaded as:
        personList //list of Person objects to populate combobox
        pisList //list of Person objects to fill DataGrid

Now I have no idea how to get both those values to DataGrid so I populate ComboboxColumn as well. I tried do get one of those Values as DataContext od whole Window and second as datagrid ItemsSource.
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Database db = new Database();
        List<Person> personList = (...);
        List<Person> pislist = (...);
        dgPlayers.ItemsSource = impTeam.PlaysInSquad.ToList();
        wPlayers.DataContext = personList;
    }

As I failed miserably to get those 2 in one DataGrid, I created 2 separate, but still can make it work.
    <DataGrid Name="dgPlayers" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Number" Binding="{Binding Number}" IsReadOnly="True"/>
            <DataGridTextColumn Header="Name" Binding="{Binding Person.Name}" IsReadOnly="True"/>
            <DataGridTextColumn Header="Surname" Binding="{Binding Person.Surname}" IsReadOnly="True"/>
            <DataGridTextColumn Header="Role" Binding="{Binding IDRole}" IsReadOnly="True"/>
        </DataGrid.Columns>
    </DataGrid>

    <DataGrid Name="dgList" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridComboBoxColumn x:Name="List" ItemsSource="{Binding DataContext.Person}" DisplayMemberPath="Name"/>
        </DataGrid.Columns>
    </DataGrid>

First DataGrid is ok, but still, I can't properly populate ComboboxColumn + I would love to see that in one DataGrid instead of two.
EDIT
Even though I already tried it before without success, solution from this thread worked for me after like 3rd try: How to Bind data to DataGridComboBoxColumn in DataGrid using MVVM
Answer: To bind your combo box separately, just have the collection for the combo box set up as a resource. That way, your combo box doesn't need to worry about what the data grid's data context is.
<Window.Resources>
    <CollectionContainer x:Key="PeopleItemsSource" Collection="{Binding personList}" />

</Window.Resources>
<Grid>
    <DataGrid ItemsSource="{Binding pisList}">
        <DataGrid.Columns>
            <DataGridComboBoxColumn ItemsSource="{Binding Source={StaticResource PeopleItemsSource}}"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

Comment: Note that "pisList" and "personList" need to be public properties on the window's data context object (ideally a view model) for the above code sample to work. The concept is the same for programmatically setting them though.
Comment: `CollectionContainer` and `CollectionViewSource` are not valid values for `ItemsSource DP`.
Comment: You are correct, see updated answer (my binding wasn't complete)
Comment: @LordTakkera Tried to run this code and Comboboxes are still empty. Made `pisList` and `personList` public. Problem seems to be way of binding. `dgPlayers.ItemsSource = (...).ToList();` in Window_Loaded populates main datagrid corectly. `"` does not on the other hand.
Alos giving break point at the end of Window_Loaded, `Collection="{Binding personList}" />` shows up as list of 14 Person elements, no result on ComboboxColumn though.
Comment: are pisList and personList public properties of the Data Context class? Also, you need set the datacontext of the MainWindow class to whatever object has those lists as public properties. You will see binding exceptions in the output window at runtime if you don't have a piece correct.
Answer: DataGridColumns does not lies in same visual tree as that of DataGrid, so it doesn't inherit DataContext from its parent. That's why you are not able to bind it using simple binding syntax. However, there are many workarounds to achieve that.
I'll list two of them here:
First take advantage of Freezable class. Magic of Freezable objects is that it can inherit the DataContext even when they're not in the visual or logical tree. You can read more about here Bind Data when DataContext is not inherited.
Add this class in your project:
public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy),
                                     new UIPropertyMetadata(null));
}

XAML usage:
<DataGrid>
   <DataGrid.Resources>
      <local:BindingProxy x:Key="proxy" Data="{Binding}" />
   </DataGrid.Resources>
   <DataGrid.Columns>
      <DataGridComboBoxColumn ItemsSource="{Binding Source={StaticResource proxy}}"/>
   </DataGrid.Columns>
</DataGrid>

Second, if you are using WPF 4.0, you can take adavantage of x:Reference which allows you to bind to element name even if it does not exist in Visual tree.
Create TextBlock whose Visibility will be Collapsed and set its DataContext to personsList.
<TextBlock Visibility="Collapsed" x:Name="txt"/>

and in code behind
txt.DataContext = personList;

Now you can bind in DataGrid like this:
<TextBlock Visibility="Collapsed" x:Name="txt"/>
<DataGrid>
   <DataGrid.Columns>
      <DataGridComboBoxColumn ItemsSource="{Binding Source={x:Reference txt}}"/>
   </DataGrid.Columns>
</DataGrid>

Comment: I've started with second method becuase it seems easier for me. Even though I think I understand it, seems like I am missing something with implementation. Done everything exactly as stated above, but got this error:
`Object reference not set to an instance of an object.`
Textblock was added above DataGrid and I also added DataContext in code behind. Any hint?
Comment: The second method is better, but a better way of doing it would be through a resource, not a hidden UI element.
Comment: @LordTakkera - Resource doesn't inherit DataContext until it's applied on some element.
Comment: Notice in my answer I use the Windows' resources, so it would have the window's data context (which is what i am assuming he wants)
Comment: Have you tried running it? `CollectionContainer` and `CollectionViewSource` are not valid values for ItemsSource DP.
Comment: You are correct, you use that source as a source in the ItemsSouce binding. I have updated my answer, thank you for catching the problem.
Comment: @RohitVats in point 2 error goes on `ItemsSource="{Binding Source={x:Reference txt}}`

If it comes to first - I've added told class, and tried to run it, no effect on ComboboxColumn. I've only added `personList' in 'Data="{Binding personList}"'. Am I missing something, or that's all I should add to this?


What is the expected number of random choices to find a quadratic residue mod p?

Question: Say you have $x$, which is not a quadratic residue mod $p$. What is the expected number of random choices of $d \in F_p$ needed such that $x+d$ is a quadratic residue?
In a work of Maurer (page 277) it is argued that this is 2, without any explanation or citation. Therefore I suspect it is a somehow known fact, but I couldn't find anything about it.
Comment: There are $\frac12(p-1)$ quadratic residues modulo $p$.
Comment: Of course, thank you
Answer: If you pick d uniformally at random in $F_p$, then $x +d$ is also uniformally random in $F_p$. Then you just need to know how many quadratic residue there are in $F_p$, as pointed in the comments, it is $\frac{p+1}{2}$ which explains that you need on average 2 try to get a quadratic residue.
To show that fact, let's denote r the number of quadratic residues in $F_p$, for a quadratic residue $y$ the polynom $X^2 - y$ has at most 2 roots (and it has 1 if and only if y=0), which means that the number of elements of $F_p$ is equal to 2r-1 and you deduce $r =\frac{p+1}{2}$


How to create scaled scores using Likert Data with N/A options?

Question: I have 7 survey questions that I asked students about regarding their online learning experience. Each question is on a 5 point Likert scale including -1 for not applicable. Now that I have the results, how do I create a scaled score? Do I change the not applicable into missing data and then input replacements? I ran a Cronbach's alpha earlier on each variable as well as a principal component analysis. The problem is, outside of determining which components should have specific items based on item weights, I am not sure how to best create an overall advising scaled score to compare with continued enrollment (binary variable).
Also, should it be expected that any scaled score I create would have a low phi correlation with continued enrollment since each of the individual items do not have significant correlations with the continued enrollment variable? Thanks for your advice!
Answer: Let's see if I can address your different questions.
NA in a score: You have a fundamental problem in your scale - one of the items does not apply to some of the observations. That implies two data generating processes or mechanisms you need to consider: 1) What makes the question applicable; 2) What makes a person select a given response option. I can think of a nunmber of ways to treat this, one complex and the other easy.

Use equating - create a scale for individuals that answered this item which includes the item, and then create a scale for individuals that did not answer the item, which will exclude the item. Then equate the two scales using the items in common. That is fairly drawn out and I would avoid it if possible.
Create scale without the item. Create the scale with and without the item, and correlate the two for individuals that have the item, and see how they align. If they are highly aligned, and the reliability is the same or very close the two, then you do the scale without that item. You lose information there of course.
Impute the item. If you believe the "NAs" are not really not applicable, but respondents selected them for laziness or other reasons, you could try to impute them.
Use FMLE. Full information maximum likelihood in a CFA I believe can deal with this missingness. I'm not sure how this can be done in IRT, but I believe it is possible. This I think assumes missing at random, so like the imputation solution, if the mechanism is truly different, then this option may not work.
Create a separate item about applicability. Make a new binary item, 1=item applies, 0= does not apply. Use this in the factor model. This would make sense if the applicability of the item is correlated with the underlying construct. This option is probably the least informative, but you could (and perhaps should) test it.

Low correlation with outcome measure: You have a hypothesis there and want to test it. Go for it, test it. You may find that, indeed, low correlation for the individual observables equals low correlation for the construct. That is informative - in statistics we often think that no relationship is useless and not interesting. Far from it - if you find that a validated and reliable measure of a construct is not related to an outcome of interest, that is highly informative - it could debunk an entire theory. Don't give up because you are worried about low correlation. Test it and see, and then update your theory. That's the only way to get smarter - only looking for things you already are pretty sure exist is not the best research agenda.


Using an Objective-C protocol from my XPC Service in my Swift app

Question: I have an app that is written in Swift, exclusively in Swift, never had an Obj-C class, has no Obj-C files or bridging headers.
In order to add some functionality without impacting my app's entitlements, I'm trying to add an XPC service -- I created this in Xcode, and the template for XPC services in Xcode is Obj-C only.
This is fine, I wrote my service out in Obj-C, but now when I want to call my service through NSXPCConnection I've gotta set up the interface to it, and to do that I need to refer, in my Swift app code, to the Obj-C protocol I wrote for my XPC target.
How do I do this?  I can't just add the "Protocol.h" to my app target, it has no rule for a C header.  All the other commentary I've found on this only seems to apply to linking to a protocol in a framework or a common target...
Comment: I'm totally curious how you are going to manage to make this work, and can merely suggest this: add `Protocol.h` to your **Swift** app, add a `Bridging-Header` to that app (simplest way is to create then delete an Obj-C class and click *Create Bridging Header* when prompted), and `#import "Protocol.h"` in the bridging headers. You will then be able to pick a **Swift** class inheriting `NSObject`, and make it adopt the `Protocol`.
Comment: I've decided to just roll the functionality into the app for now, putting it in an XPC would have been nice but it's not obligatory.  I lack the Xcode-do necessary to build an XPC service in swift without a template, I'll wait until Apple puts one out.  I tried a couple different things and nothing works...
Comment: You know what, I just got it to build, lemmie make sure it works and I'll write it up.
Answer: Okay, so I figured out a solution.
1) Deleted the boilerplate Obj-C service class and protocol files.
2) Wrote my protocol and vended object classes in swift.  Made sure these could be exported to Obj-C.
3) Added the protocol.swift file to my app's target.  Added #import "Service-Swift.h" to my service's main.m.
So now my XPC object is implemented in Swift, my object protocol is in swift, the only non-swift file is my XPC's main.
Comment: You also could use `main.swift` to stay off from Objective-C.
Answer: As I understand you can even change your main file.
https://www.objc.io/issues/14-mac/xpc/


Multivariate integration by parts

Question: Let $f,g:\mathbb R^n \rightarrow \mathbb R^n$, $(x_1,\dots, x_n)\mapsto f,g(x_1,\dots, x_n)$ be smooth functions with compact support.
Use the following notation: for an index $\alpha = (\alpha_1,\dots, \alpha_n)$ where $\alpha_i$ is a natural number, we denote by $D^{\alpha}$ the derivative with respect to $x_1$ $\alpha_1$ times, with respect to $x_2$, $\alpha_2$ times, and so on until $x_n$, $\alpha_n$ times.
Can we then say that
$$\int_{\mathbb R^n} D^{\alpha} f(x_1,\dots, x_n) g(x_1,\dots, x_n)dx_1 \cdots dx_n = (-1)^{|\alpha|} \int_{\mathbb R^n} f(x_1,\dots, x_n) D^{\alpha} g(x_1,\dots, x_n)dx_1 \cdots dx_n$$
where $|\alpha| = \sum_{i=1}^n \alpha_i$.
Thanks you!
Comment: Yes, we can do this.
Answer: Yes. Let $[-R,R]^n$ be a cube containing the support of $f$ and $g$. The formula is the result of integrating by parts $|\alpha|$ times in the iterated integral
$$
\int_{-R}^R\Bigl(\dots\Bigl(\int_{-R}^RD^\alpha f \, g\,dx_n\Bigr)\dots\Bigr)\,dx_1.
$$

Multivariate integration by parts


Compose Email without MFMailComposeViewController popup

Question: I am trying to implement a "Send Feedback" viewcontroller where the user can automatically push to a viewcontroller and start filling out a form - a form that will then be submitted and composed to a static email address.
I am looking at the facebook app under the send feedback view and that's exactly what I would like to do.
Basically limiting the user from editing the Recipients and only able to edit the subject and body, which I will implement as UITextViews or something along those lines.
I understand there is the already implemented MFMailComposeViewController that presents a preimplemented UIViewController that easily allows the user to enter their subject, body, cc targets as well as recipients, but I would like to step away from another viewcontroller popping up and basically implement my own viewcontroller that the user can press on a UIButton and automatically send their typed in subject and body.
Refer to the facebook iOS version "Send Feedback" page.
If there are any further questions please ask.... I'll edit ASAP.
Answer: you can't do it directly but it is possible via web service. you will need to implement SMTP on server side and the server will send an email instead of you.
Comment: thank you for your quick response. So I'm working with a company who has a web service that has already implemented SMTP. Their web site has the link and everything. Is there a tutorial that shows how to access the SMTP through a objective-c and do what I would like to do?
Comment: So I was able to setup my gmail account and use their SMTP server to get emails from my app... I am only able to get emails from myself, so maybe I'll add a string object that is the users email address and have them enter their address before submitting the app so I can have a reference to who actually sent the email so I can email them back. But thank you very much @Apurv for your response. It was correct :)


Set representation of natural numbers

Question: In Wolfgang Wechler's Universal Algebra for Computer Scientists,
he says that natural numbers can be represented as finite sets:
$0$ stands for $\emptyset$, $1$ for {$\emptyset$}, $2$ for {$\emptyset$,{$\emptyset$}}, $3$ for {$\emptyset$,{$\emptyset$,{$\emptyset$}}} and so on.
Then he says that a more readable way is that $0 = \emptyset$ and $ n = \{0,1,\dots\,n-1\}$ for $n \ge 1$.
But to me this seems different: in my opinion $3$ would be coded as $ \{\emptyset,\{\emptyset\},\{\emptyset,\{\emptyset\}\}\} $.
Isn't this a mistake in the book? If it is, which construction is the "right" one?
Comment: I think the book has a typo. Your opinion is correct.
Comment: I suggest you send an e-mail to either the original author or the publisher. Sometimes they maintain a list of errata on their websites, sometimes in their next printing your name will be acknowledged for pointing out the error, and [sometimes you even get some money and bragging rights out of it](http://en.wikipedia.org/wiki/Knuth_reward_check).
Answer: The book has a typo in its description of $3$, and you are correct.
To expand a bit.
Given a set $a$, we define $s(a)$, the successor of $a$, to be the set $s(a) = a\cup \{a\}$.
A set $X$ is said to be inductive if and only if:

$\emptyset \in X$; and
If $a\in X$, then $s(a)\in X$.

The Axiom of Infinity in ZF Set Theory states that there exists at least one inductive set. Given an inductive set $X$, we define
$$\mathbb{N}_X = \bigcap\{ S\subseteq X\mid S\text{ is inductive.}\}.$$
One can then prove that if $X$ and $Y$ are inductive sets, then $\mathbb{N}_X=\mathbb{N}_Y$; we define "the natural numbers", $\mathbb{N}$, to be this (now shown to be well-defined) set.
So what is $\mathbb{N}$? It contains $\emptyset$; we call it $0$. It contains $s(0) = s(\emptyset) = \emptyset\cup\{\emptyset\} = \{\emptyset\}$, which we call $1$.
It contains $s(1)$, which we call $2$. What is $2$?
$$2 = s(1) = s(\{\emptyset\}) = \{\emptyset\} \cup \{\{\emptyset\}\} = \{\emptyset,\{\emptyset\}\}.$$
Then we have $s(2)$, called (unsurprisingly), "$3$"; and we have:
$$3 = s(2) = s(\{\emptyset,\{\emptyset\}\}) = \{\emptyset,\{\emptyset\}\}\cup\Bigl\{\{\emptyset,\{\emptyset\}\}\Bigr\} = \Bigl\{\emptyset,\{\emptyset\},\{\emptyset,\{\emptyset\}\}\Bigr\} = \{0,1,2\}.$$
And so on. The set contains exactly $\emptyset$ and its successors, and it corresponds to the naive idea of the "natural numbers:". The fact that it is the "smallest inductive set" implies that induction holds: if $S\subseteq \mathbb{N}$ is such that $0\in S$ and, whenever $n\in S$ we have $s(n)\in S$ (that is, $S$ is inductive), then $S=\mathbb{N}$.
Comment: Incidentally, a small side note on _why_ we define the successor of a set $a$ the way we do: by the Axiom of Regularity, $a$ can't contain $\{a\}$ as a member, so $s(a) = a\cup\{a\}$ is guaranteed to be a different set than $a$ is and in fact to satsify $a\subsetneq s(a)$, and it's essentially the simplest definition that offers this guarantee.
Comment: Thank you, now it makes sense to me. I would like to upvote your answer, but it says that I do not have enough reputation to do so.
Comment: @Steven: Don't you mean, $a$ can't contain $a$ as a member? (Equivalently, $a$ cannot contain $\{ a \}$ as a subset.)
Comment: Ahh yes, of course; mea culpa.

Set representation of natural numbers


Verify the identity given in textbook

Question: Need help with solving this identity.
${(\tan\alpha-\cot\alpha)^2 ={\ 3 \over \ 1-sin^6\alpha-cos^6\alpha}}$
If anyone could help I would be thankful.
Comment: Did you try rewriting $\tan$ and $\cot$ in terms of $\sin$ and $\cos$? This will be necessary at some point as the right-hand side only uses $\sin$ and $\cos$.
Comment: I tried to do this with tan and cot (tan+cot)^2 = tan^2 + 2tan*cot + cot^2 and tried to expand it but I didn't get anywhere.
Comment: Yes I did try it but the other side has sin and cos in the power of 6 and I got stuck again.
Answer: Hint:
$$(\sin^2x)^3+(\cos^2x)^3=(\sin^2x+\cos^2x)^3-3\sin^2x\cos^2x(\sin^2x+\cos^2x)=?$$
$$2\sin x\cos x=\sin2x$$
$$\cot x-\tan x=\dfrac{2\cos2x}{\sin2x}=2\cot2x$$
Comment: In my school I learned that we try to get the left side to match with the right so can you explain it to me how can I get ${(\tan\alpha-\cot\alpha)^2}$ to match with the right side ${\ 3 \over \ 1-sin^6\alpha-cos^6\alpha}$
Comment: @EndritShala, Not required to derive one from the other. Its sufficient to reach at the same expression from both sides

Verify the identity given in textbook


Linq C# com ordem

Question: Tenho uma consulta LINQ que lista os aniversariantes do mes corrente:
        Ramal[] RamalAniver = (from a in db.Ramais
                               where a.sAniversario.Contains(DiaAniversario + "/" + MesAniversario) && a.bAtivo == true
                               select a)
                               .Union(
                               from c in db.Ramais
                               where c.sAniversario.Contains("/" + MesAniversario) && c.bAtivo == true
                               orderby c.sAniversario
                               select c
                               ).ToArray();

Porém quando montei ela, a intençao era na primeira consulta trazer o aniversariante do dia como primeiro registro, e na segunda os aniversariantes do mes corrente. A consulta esta retornando os registros mas o aniversariante do dia não fica em primeiro...
Quando a lista é montada a ordem não é mantida... como fazer para ele manter a ordem que coloquei no Union?
Comment: É só pôr a ordem fora do `Union`
Answer: O Linq não garante a manutenção da ordem, então você pode usar um truque.
Ramal[] RamalAniver =
    (from a in db.Ramais
    where a.sAniversario.Contains(DiaAniversario + "/" + MesAniversario) && a.bAtivo == true
    select new { Ramal = a, Ordem = 0 })
    .Union(
    from c in db.Ramais
    where c.sAniversario.Contains("/" + MesAniversario) && c.bAtivo == true
    orderby c.sAniversario
    select new { Ramal = c, Ordem = 1 })
    .OrderBy(n => n.Ordem)
    .Select(n => n.Ramal)
    .ToArray();

Tudo bem que está adicionando um pouco mais de complexidade, mas assim você se mantém dentro do contexto do Linq, com seus benefícios.
Basicamente você estaria criando um novo tipo com 2 propriedade, uma é o Ramal e a outra é um int com a ordem imposta pelo teu modelo, e, após usá-lo para ordenar o resultado, jogando esse auxiliar fora para retornar apenas os dados que você quer.
Acredito que isto resolva o seu problema.
Answer: Pesquisei e juntando o resultado consegui a solução:
Simplifiquei a query trazendo somente o aniversariante do mês:
Ramal[] RamalAniver = (from c in db.Ramais
                                   where c.sAniversario.Contains("/" + MesAniversario) && c.bAtivo == true
                                   orderby c.sAniversario
                                   select c
                                   ).ToArray();
e usando esta expressão consegui deixa o aniversariante do dia em primeira posição e depois em ordem por dia do mês:
RamalAniver = RamalAniver.OrderByDescending(x => x.sAniversario == DiaAniversario
                + "/" + MesAniversario).ThenBy(x => x.sAniversario).ToArray();
Se alguem puder detalhar o entendimento desta expressão, agradeço.
Answer: Considerando que você pode converter as datas de aniversário em DateTime temos a seguinte solução:
var dataHoje = DateTime.Now;
var aniversariantesDoMes =  pessoas.Where(p => p.DataNascimento.Month == dataHoje.Month && p.DataNascimento.Day >= dataHoje.Day )
        .OrderBy(d => new DateTime(dataHoje.Year,d.DataNascimento.Month,d.DataNascimento.Day));

Linq C# com ordem


Is there only one analytic continuation of the Riemann zeta function?

Question: If I were to manipulate the zeta function in a 'new way' would I end up with an analytic continuation that is equal to the one know or something completely new for values less than 1 and complex numbers?
Comment: If you want a great text to begin your CA endeavors, I was in a similar situation and found this text by Flanigan http://www.amazon.com/Complex-Variables-Dover-Books-Mathematics/dp/0486613887 an excellent choice.
Comment: @Andrew Thanks for the advice, I am glad to hear I am not alone in my interest!
Answer: Analytic continuations to a specified domain are always unique (due to the identity theorem for holomorphic functions).
Comment: @zerosofthezeta If you haven't done so already, you really should start with a course in complex analysis.
Comment: Due to my mathematics knowledge so far (I am still learning), I have no idea what you just wrote, but I will look into it!
Comment: @mrf Yes. I am going to very soon. Thanks for the advice.
Comment: Roughly: Two analytic functions that are equal on an open set are equal everywhere, so if you have two different continuations of $\zeta$ that agree on $\operatorname{Re} s > 1$, they agree everywhere.
Comment: @zerosofthezeta There's something that I can't understand, you are asking about a new way to manipulate the zeta Riemann function with     some different analytic continuation and you still don't know the identity principle. What am I misunderstanding?
Comment: @GastónBurrull I am new to this field, but I have an immense interest!


How do you join a custom table to a node from a field with hook_views_data()

Question: I have a custom table that contains (for simplicity) two fields:

id
client_id

On my node content type, I have an integer type field called: field_dashboard_id.  All my nodes have the field_dashboard_id set to ids from the custom table.  I have a content view that I would like to also display the client id from the custom table. (FYI I am able to create a view if I use Dashboard Entries instead of Content but I want to use Content and join to Dashboard Entries)
I tried the following code but when I try to add a relationship, I am not seeing my custom table in Views.
<code>/**
 * Implements hook_views_data().
 */
function mydashboard_views_data() {
  $data = [];

  $data['mydashboard_site']['table']['group'] = t('Dashboard');

  $data['mydashboard_site']['table']['base'] = [
    'field' => 'id',
    'title' => t('Dashboard entries'),
    'help' => t('Contains a list of dashboard entries.'),
  ];

  $data['mydashboard_site']['table']['join'] = array(
    'node' => array(
      'left_table' => 'node__field_dashboard_id',
      'left_field' => 'entity_id',
      'field' => 'id',
    ),
  );

  $data['mydashboard_site']['id'] = [
    'title' => t('ID'),
    'help' => t('Unique Site ID.'),
    'field' => [
      'id' => 'numeric',
    ],
    'filter' => [
      'id' => 'numeric',
    ],
    'argument' => [
      'id' => 'numeric',
    ],
    'sort' => [
      'id' => 'standard',
    ],
    'relationship' => [
      'base' => 'node', // The name of the table to join with.
      'base field' => 'field_dashboard_id', // The name of the field on the joined table.
      // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
      'handler' => 'views_handler_relationship',
      'label' => t('Default label for the relationship'),
      'title' => t('Title shown when adding the relationship'),
      'help' => t('More information on this relationship'),
      'extra' => [
        [
          'field'    => 'field_dashboard_id',
          'value'    => 'value',
          'operator' => '=',
          'numeric'  => true,
        ],
      ],
    ],
  ];

  $data['mydashboard_site']['client_id'] = [
    'title' => t('Client ID'),
    'help' => t('The client id'),
    'field' => [
      'id' => 'standard',
    ],
    'filter' => [
      'id' => 'string',
    ],
    'argument' => [
      'id' => 'string',
    ],
  ];

  return $data;
}
</code>
Update
Also tried the following:
<code>$data['mydashboard_site']['table']['join'] = [
  'node__field_dashboard_id' => [
    'left_field' => 'field_dashboard_id_value',
    'field' => 'id',
  ],
];

'relationship' => [
  'base' => 'node__field_dashboard_id', // The name of the table to join with.
  'base field' => 'entity_id', // The name of the field on the joined table.
   // ID of relationship handler plugin to use.
  'id' => 'standard',
   // Default label for relationship in the UI.
  'label' => t('Example node'),
],
</code>
Comment: just a suggestion you could use hook_views_query_alter() to add your table in a condition group.
https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/function/hook_views_query_alter/8.2.x
Comment: In the past, I used query alter for altering the query but never to add fields. Do you know how I would be able to add a field?
Comment: posted an answer because this would be to long to comment.
Answer: When you have a field you have a table for it with stored values, so you just add the fields table to your query
Like
<code>/**
 * Implements hook_views_query_alter().
 */
function HOOK_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
   $query->addTable('my_fields_table');
   $query->addWhere(<condition group id>, '<table_column>', <value>, '<operator>');
   // These you can use to alter the behaviour for your condition group.
   //$query->setWhereGroup('OR/AND', <condition group id>);
   // This one is for the global group behavior.
   //$query->setGroupOperator('<OR/AND>');
  }
}
</code>


Multiple $_POST Values for One Form Object

Question: I'm working on a webpage that displays two images that have associated buttons. When one button is clicked, I want the page (once the button is clicked, the page is reloaded and posts to itself) to increment the wins field of the image whose button was clicked, and increment the loses field of the image whose button was not clicked. This requires knowing the name of both images, but only one button is posting its data, so only one piece of information can be transferred to the next page.
I haven't been successful in finding a method by which a single form object (a button in my case) can post multiple values as is required for my program. Is there a way that I can do this?
Answer: Using <input type="hidden"> will let you send you multiple values, whichever button was clicked.


Uncaught ReferenceError: $ is not defined em carrinho de compras

Question: Porque ocorre o erro Uncaught ReferenceError: $ is not defined no código abaixo?
$(function funcao(){
    $(document).on('keydown', '#busca', function(){
        console.log('I\'m working');
    });
});

HTML

        Busca Carrinho

    <form action="" method="post" enctype="multipart/form-data" id="form_busca">

            Buscar Produto
            <input type="text" name="buscar" id="busca" />

    </form>

    <form action="" method="post" enctype="multipart/form-data">

                    Produto
                    Valor
                    Qtd
                    Subtotal

                <?php
                $total = 0;
                if(count($_SESSION['carrinho']) > 0):
                foreach($_SESSION['carrinho'] as $idProd => $qtd){
                    $pegaProduto = $pdo->prepare("SELECT * FROM `produtos` WHERE `id` = ?");
                    $pegaProduto->execute(array($idProd));
                    $dadosProduto = $pegaProduto->fetchObject();
                    $subTotal = ($dadosProduto->valor*$qtd);
                    $total += $subTotal;

                    echo '
'.utf8_encode($dadosProduto->titulo).'	Valor	<input type="text" id="qtd" value="'.$qtd.'" size="3" />	';
                    echo 'R$ '.number_format($subTotal, 2, ',', '.').'
';

                }
                echo '
Total	R$ '.number_format($total, 2, ',','.').'
';
                endif;
                ?>

        <input type="submit" value="Concluir compra" class="botao" />
    </form>

Comment: Coloca esta função à volta do teu código: `(function($){/* o teu código aqui... */})(jQuery);`. Funciona?
Answer: O uso do jQuery está errado. A função $(document).ready() tem uma assinatura semelhante.
// 1º Forma completa
$( document ).ready(function() {
    $(document).on('keydown', '#busca', function(){
        console.log('I\'m working');
    });
});

// 2º Forma - Reduzida
$(function() {
    $(document).on('keydown', '#busca', function(){
        console.log('I\'m working');
    });
});

// 3º Forma - Passando uma função nomeada
function readyFn( jQuery ) {
    $(document).on('keydown', '#busca', function(){
        console.log('I\'m working');
    });
}

$( document ).ready( readyFn );

Ao rodar o seu código, sua função entra em conflito com o jQuery gerando o erro que está sendo apresentado.
Caso precise definir uma nova função para o jQuery, veja 5 maneiras de definir uma função


When my computed property is updated the linkTo attr does not get update in ember RC1

Question: Here is the linkTo helper in my handlebars template
{{#linkTo 'person.page' nextPage target="controller"}}Next{{/linkTo}}

Here is my controller
PersonApp.PersonController = Ember.ArrayController.extend(Ember.PaginationMixin, {
    itemsPerPage: 2
});

Here is the computed property in the mixin
  nextPage: function() {

    var nextPage = this.get('currentPage') + 1;
    var availablePages = this.get('availablePages');

    if (nextPage <= availablePages) {
        return Ember.Object.create({id: nextPage});
    }else{
        return Ember.Object.create({id: this.get('currentPage')});
    }

  }.property('currentPage', 'availablePages'),

when I console log just before each return statement I can see the page id is correct ... yet my html isn't updated. Anything simple that I'm doing wrong in the above?
Also I do see a print each time I change the page (so the computed properties I depend on are being fired)
Here is a full blown jsfiddle showing that after you click next the first time ... it still points at /#/page/2 instead of /#/page/3
http://jsfiddle.net/RhTyx/2/
Thank you in advance
Answer: First off: It would be nice, if you would not link a fiddle where the most important code is not part of the fiddle (the FilterSortSliceMixin). Therefore one cannot test anything, despite the fact the fiddle was really huge and contained lots of unnecessary code.
Regarding your problem:
I think this cannot work because the dependent properties you specified do not do anything. Your {{#linkTo}} helper sends the user into the the PersonPageRoute. The code of this route is:
PersonApp.PersonPageRoute = Ember.Route.extend({
    model: function(params) {
        return PersonApp.Person.find(params.page_id);
    },
    setupController: function(controller, model) {
        this.controllerFor('person').set('selectedPage', model.get('id'));
    }
});

So you are getting the personcontroller and set the property selectedPage. But this property is not specified in your dependent keys. So therefore i would suggest this:
//maybe even remove currentPage??
}.property('currentPage', 'availablePages' , 'selectedPage'),

So i guess you got confused with your naming. I guess, you should either have the property 'selectedPage' or 'currentPage', right?
Update: This is definitely a bug. Heres an excerpt from the LinkView class, which is used with the linkTo helper:
var LinkView = Ember.View.extend({
  attributeBindings: ['href', 'title'],
  href: Ember.computed(function() {
      var router = this.get('router');
      return router.generate.apply(router, args(this, router));
  })
});

As you see it does not specify any dependent keys. Maybe you can reopen/patch this class and add the dependent key. Don't know which one this would have to be, but maybe context?
Comment: ah yes -my fault (check the updated fiddle above). The updated property didn't fix the issue unfortunately
Comment: Hmm, this seems to be a bug. The link works functionally, but the href gets not updated for me properly too.
Comment: That explains it -thanks for the research on github to find this issue!


12-string acoustic guitar - how do nut and saddle materials affect tone?

Question: I'm doing some work on a 12-string acoustic guitar, and am planning to replace the nut and saddle. I need to raise the action a little bit for the E and B strings, and also want to change to a slightly heavier gauge, so I'll need a nut with slightly wider slots; the low E string doesn't quite fit in the slot as it is, and heavier strings will make this problem worse.
How much does nut and saddle selection affect tone? I like the tone of the GraphTech ones I have -- it's definitely better than the plastic nut and saddle that came with the guitar. But are there options for anything better?

The self-lubricating factor of Tusq material is very subtle, and though the tone is good, am I better off looking at a bone nut and saddle? Are there issues particular to 12-strings? (The tone on this guitar is quite good, although a little muddy.)
The guitar's pickup is a soundhole-mounted Fishman, so there's no undersaddle pickup to interfere with the acoustic sound.
Comment: @VariLogRant - If I'm wrong about this, someone please correct me, but 12-strings do tend to be lacking in bottom-end tone, due to over half of their strings being unwound (I think) so transmission of low frequencies to the top is even more important than on a 6-string. (If I knew what wood this guitar is made of, then that would be even more relevant information.)
Comment: I don't know that the specifics of the 12-string make a real difference to this question. The tone difference should be the same with 6 or 12 strings. Maybe the question should be changed?
Comment: If that is a picture of the guitar above, I'd say you have a solid spruce top. And urah, maybe there are some problems unique to 12-strings, I'm sure there are many who have the same questions about how nut and saddle material affect the tone of their 6-string guitars.
Answer: The nut and saddle simply act as conduits for the vibration of the strings to the body of the guitar--so their effect on the tone of the instrument is pretty small. Other people may tell you different though ;). An acoustic guitar lives and dies by the geometry of the instrument--and the majority of the sound is projected from the sound hold and the top as the body of the guitar acts as a natural amplifier. A better nut and saddle, if anything, will get you much better tuning stability and maybe a little better transfer of vibration from the strings to the top through the bridge and saddle; that could net you a little better sustain from sympathetic vibrations.
To give you some context, all of my electric guitars are equipped with bone nuts--which really cleaned up all my tuning stability issues and squeezed a tiny bit more sustain out of my Les Paul. I couldn't really notice a huge difference in tone based on the upgrades--which was from the cheap-o stock plastic nuts.
It also sounds like you are struggling with the lack of bass on your 12-string. Going to a lower gauge string set is a really good step in this direction, but a 12-string guitar is going to naturally sound brighter than a standard 6-string acoustic. Why? Well take a look at these two graphs:

Forgive me for getting all nerdy on you :D. Basically what you should take away from this graph is there are roughly 3 times the number of smaller gauge strings on a 12-string than on a standard acoustic assuming the cutoff is below the low D (0.036). The ratio is 3:9 for those of you math aware. So, from this you can see that the smaller, higher voiced strings have nearly thrice the presence--which will get you three times the highs. Note that I did these calculations using a medium set of Elixer Acoustic Phosphor Bronze and a medium set of Martin 12-String Phosphor bronze.
So there you have it :D.
Comment: The guitar does have problems staying in tune, so I'll price out bone nuts and saddles. I think that the tone problems are here to stay, although they're fairly minimal.
Comment: Also, I'd heard that a guitar's sound comes chiefly through the vibration of the top, and not through the soundhole. However, thinner-bodied guitars are definitely softer and more tinny-sounding, so I'm not certain that's true.
Comment: The top certainly provides a very large proportion of the tone of the guitar, I'd say 80% - 90% if I had to assign it a number. Note that I only said that the majority of the sound is projected from the sound hole, I didn't say it generated the tone of the instrument :D. The geometric configuration of the instrument allows the top to vibrate freely--along with the strings and other pieces of the instrument, thus generating your tone.
Comment: For a given purpose, that being the tuned-snare in the singer's hands, the bright nature of the 12-string works well, and I don't see 12-strings out there in other contexts. Yeah, Leo Kottke, but otherwise, not so much.
Comment: It's an old question, maybe you don't visit any more, but I'm sceptical about your extra sustain on any guitar - apart from open strings - with respect to having a bone (or brass, or whatever) nut. Once the string is fretted, there's no vibration behind it going to that nut, so how is a difference made - or even proven?


Criar matriz 3x3 usando Imageviews - SWIFT

Question: Como que eu faço para criar programaticamente uma matriz 3x3 composta de 9 ImageViews ?
Comment: Você já tentou simplesmente declará-la: `var anArray:[[ImageView]]` e para inicializar algo como `self.anArray = [[iv1, iv2, iv3], [iv4, iv5, iv6], [iv7, iv8, iv9]]`?
Comment: No fim das contas eu quero construir um quadrado com nove quadradinhos dentro. Cada quadradinho vai receber uma imagem que vai ter uma ordem específica.

Como que eu faço com relação ao tamanho dessas imagens ?
Answer: O comentário do @carlosfigueira responde sua pergunta:
var matriz: [[UIImageView]] = [[UIImageView(), UIImageView(), UIImageView()],
    [UIImageView(), UIImageView(), UIImageView()],
    [UIImageView(), UIImageView(), UIImageView()]]

matriz[1][1] //<UIImageView: 0x7fca39d34520; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <CALayer: 0x7fca39d33a70>>

Comment: Eu tenho 9 imagens no projeto e quero jogá-las nessa matriz, cada imagem vai ficar dentro de uma imageview, nessa mesma ordem de 1 a 9.

Mas como q eu faço com relação ao tamanho dessas imagens ?
Comment: você pode usar o método de inicialização da classe `public init(frame: CGRect)`. No exemplo acima ficaria: `var matriz: [[UIImageView]] = [[UIImageView(frame: CGRectMake(0, 0, 100, 100)), UIImageView(frame: CGRectMake(0, 0, 50, 50)), ...`
Answer: Já consideraste usar uma UICollectionView? A collection view se encarregaria de setar os frames das células onde as imagens aparecem, mesmo se as imagens possuem dimensões diferentes. Dá uma olhada no código abaixo, que cria uma array de 9 imagens e mostra como tu iria acessar esse array nos protocolos da collection view.
import UIKit
var arrayDeImagens = [UIImage]()
// só para criar as imagens fake
for _ in 1...9 {
    arrayDeImagens.append(UIImage())
}

// MARK: UICollectionViewDataSource

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return arrayDeImagens.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let imagem = arrayDeImagens[indexPath.item]

    /* aqui tu vais instanciar tua subclasse de UICollectionViewCell
       que contém uma UIImageView como subview e ira renderizar a tua imagem */

    return UICollectionViewCell() // essa linha é só para o compilador ficar quieto
}

// MARK: UICollectionViewDelegateFlowLayout

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return arrayDeImagens[indexPath.item].size
}


GetElementbyID and Innerhtml not working

Question: I don't know what I'm doing wrong. This is a 2 part question. Please see code below. First, it keeps saying that the variable capitals is null.  Second, I'm unable to get innerHTML working. I'm not sure why it isn't working. I know I have document.write which I'm not suppose to use so I'm working on understanding getElementbyId.innerHTML to work.
HTML
<form name="shares">

Enter information here:

                Capital to Invest
                <input type="text" name="capital">

                Price per share
                <input type="text" name="price" onchang="calculate();">

                <input type="button" value="Compute" onclick="calculate()">

The quantity you can be:

            No. of shares

            Change

    </form>

JavaScript
var capitals = document.getElementById("capitalr");
var x = capitals.id;
var pps = document.shares.price.value;
function calculate () {
    document.write("Capital = " + capitals +"
");
    document.write("Price per share is = " + pps);
}
document.getElementById("hello").innerHTML="Hello";

Comment: Note that every time the calculate() function runs, the entire document is overwritten and all your HTML is gone.
Comment: Where in the page is your javascript?
Comment: Go to jsfiddle.net and paste in your code, then post a link to the non working code so we can see what isn't working.
Comment: http://jsfiddle.net/5Uqg5/
Comment: Your fiddle doesn't work for different reasons: You don't have an element with ID `test` and you didn't bind `calculate` as event handler. You wouldn't be able to use `calculate` as event handler either, since you set up the fiddle to run the code inside the load event handler, which makes `calculate` local to the event handler. I recommend to make yourself familiar with JSFiddle first, so that you can reproduce the exact same problem that you are experiencing.
Answer: 1) The
 for your button doesn't have a
.
2) There's a timing problem -- you need to put your code in a function that executes at onload time.

I suggest you use "console.log" statements as a debugging tool to see how your code is progressing. That's helped me a lot.
Comment: Thanks! Where I can go to do more studying on the timing issue? On a different project I had, I used the onclick handler to grab getElementById.  On this one, I wanted to do it onload. It's not really what I'm going to do but I just wanted to see it.
Comment: @user3512034 You're welcome. I went to the http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element link and learned that there are many ways to solve this. Another link is http://stackoverflow.com/questions/191157/window-onload-vs-body-onload. It's a bottomless pit. (Can you accept my answer? Probably not.)


Module development trouble with saving module params using ajax

Question: I am really new to Joomla and 1.6 is also very new it seems so I am having a bit of trouble to save data into the module params field in the module back end.
Let me explain a bit better.
I have a small contacts manager that I want people to subscribe to using a joomla module in Joomla 1.6. Now the module is created and everything works fine. I even got it right to create a custom field in the module back end that calls my API and populates the dropdown box with the data needed.
I want to be able to save the selection as a module param to easily access it in my template. This seems to be very hard to do because I cannot find any documentation on it whatsoever.
Basically my process is as follows.

I go to the module manager in Joomla
admin.
I select my installed module and let
it open.
The Code runs to populate the
dropdown box with an amount of list
names a contact can subscribe to.
The kicker - I want to be able to
select a list name and save an ID
into the module params field in the
Joomla DB onchange with an ajax
request -

I get the onchange event to work and even run the script with the post request but in the PHP file I use to handle the post and save the data I cannot get the DB instance to do any operations on it. Thats the explanation, here's the code :
custom field in the module backend
<code>defined('_JEXEC') or die('Direct Access to this location is not allowed.');
jimport('joomla.html.html');
//import the necessary class definition for formfield
jimport('joomla.form.formfield');

// Include API utility file
require_once(dirname(__FILE__) . '/../lib/pmailer_subscription_api.php');

/**
 * Defines the JFormFieldLists class for the pMailer subscription module for
 * Joomla CMS version 1.6 to get the lists provided the API key.
 *
 * @category  Joomla
 * @package   Modules
 * @copyright 2011 Prefix Technologies Pty (Ltd) (http://www.prefix.co.za/)
 * @link      http://www.pmailer.co.za/
 */

class JFormFieldLists extends JFormField
{
    /**
     * The form field type.
     *
     * @var  string
     * @since 1.6
     */
    protected $type = 'lists'; //the form field type

    /**
     * Method to retrieve the lists that resides in your pMailer account using
     * the API.
     *
     * @return array The field option objects.
     * @since 1.6
     */
    protected function getInput()
    {
        $document = JFactory::getDocument();
        $document->addScript(
            JURI::base() . '../modules/mod_pmailer_subscription/lib/'
            . 'mod_pmailer_subscription.js'
        );

        $options = array();
        $attr = '';

        /*
         * Initialize JavaScript field attributes. This is the path to the
         * ajax handler that will save your list selection.
         */
        $attr .= $this->element['onchange'] = (string)
            'onchange="javascript: saveListSelection(\''
                . JURI::base()
                . '../modules/mod_pmailer_subscription/lib/utils.php'
            . '\')"';

        // Get the database instance
        $db = JFactory::getDbo();
        // Build the select query
        $query = 'SELECT params FROM jos_modules'
            . ' WHERE module="mod_pmailer_subscription"';
        $db->setQuery($query);
        $params = $db->loadObjectList();

        // Decode the options to get thje api key and url
        $options = json_decode($params[0]->params, true);

        // Create a new API utility class
        $api = new PMailerSubscriptionApiV1_0(
            $options['enterprise_url'],
            $options['pmailer_api_key']
        );

        // Get the lists needed for subscription
        $response = $api->getLists();

        // Make a default entry for the dropdown
        $lists = array('0' => 'Please select a list');

        // Builds the options for the dropdown
        foreach ( $response['data'] as $list )
        {
            $lists[$list['list_id']] = $list['list_name'];

        }

        // The dropdown output
        return JHTML::_(
            'select.genericlist',
            $lists,
            'mod_pmailer_lists_box',
            trim($attr),
            'id',
            'title',
            $this->value
        );

    }

}
</code>
The utility file that saves the param
<code>$db = JFactory::getDbo();

if ( (isset($_POST['op']) === true) && ($_POST['op'] === 'saveList') )
{
    $query = 'SELECT params FROM jos_modules'
        . ' WHERE module="mod_pmailer_subscription"';
    $db->setQuery($query);
    $params = $db->loadObjectList();

    // Decode the options to get thje api key and url
    $options = json_decode($params[0]->params, true);

    $options['list_selection'] = (int)$_POST['id'];

    $new_params = json_encode($options);

    $query = 'UPDATE jos_modules SET params = "' . $new_params
        . ' WHERE module="mod_pmailer_subscription"';

    $db->query($query);

    echo 'success';

}
</code>
The Javascript
<code>// Gets called on dropdown change event
function saveListSelection(url)
{
    // Ajax code here to save list selection
    var x = new Request({
        url: url,
        method: 'post'
    }).send('op=saveList&id=' + $('mod_pmailer_lists_box').get('value'));

}
</code>
I hope you can give me some advise as how to this I am stuck like crazy. The only constraint is that it HAS to be a module. Boss's orders.
Comment: lol no one likes Joomla  anymore, I Can relate ;)
Answer: Looks like no one relates to this question.
I have found a way to fix it though by NOT using ajax.


Alternate modules/themes directory

Question: I'm trying to setup an alternate modules and themes directory which I can track with GIT separate from the contributed modules directory.
Following this question, I created a directory in the following structure:
<code>/var/www/Mysite
       -sites/samplesite/modules/mymodule
</code>
mymodule was working just fine when it was based in sites/all/modules/custom/mymodule but once moved it was no longer listing on the modules page, nor the features page - mymodule is features generated.
I attempted the following directory structure:
<code>/var/www/samplesite
       -sites/samplesite/modules/mymodule
</code>
But it's still not working.
Can anyone please help me with this problem?
Comment: Did you empty the cache after you moved your module?
Comment: Yes, flushed caches multiple times
Comment: So is your directory structure this: /var/www/Mysite/sites/samplesite/modules/mymodule or this: /var/www/samplesite-sites/samplesite/modules/mymodule ? I assume the former but your question makes it look unclear.
Answer: Putting modules in sites/samplesite/modules/mymodule is specifically for a multi-site setup.
Drupal won't just load all modules in all sites directories all the time, it will only load modules in the samplesite directory if you are hitting the samplesite domain (or you have an entry in the sites/sites.php file to tell Drupal which domains map to samplesite.
The other option from the page you link to is to make a directory in sites/all/modules that is a symlink to your custom module directory.
Then (assuming you're using Apache), make sure your server is configured to enable the FollowSymLinks option.
There are also a couple of other options:

Add a directory for your modules, eg. sites/all/modules/samplesite or whatever is logical to call it. Exclude that directory in your main .gitignore file. make that new directory a clone of your other modules repository. Alternatively you could not have the sub directory and have separate repositories for each module.
Using a similar directory structure as above, use git subtree to have a repository in a repository (or many individual module repositories if that is your requirement). This seems like a decent post to give you more information on git subtree: http://getlevelten.com/blog/tom-mccracken/smarter-drupal-projects-projects-management-git-subtree

Either method may be preferable depending on your situation however I would probably recommend the subtree method over the completely separate repositories. It would be easier to manage things like deployments, since with the subtree method the main repo still contains everything, even though the source repos are different.

Alternate modules/themes directory


Polynomial modulus

Question: Can anyone explain why the two solutions to $n^2+7n-2 = 0$ modulo $43$ are $n=13$ and $n=23$ and how they are found?
Comment: Yes, keep adding on the modulus until you find a perfect square. There are more sophisticated methods than this, of course (Andre mentions Tonelli-Shanks).
Comment: Completing the square is a valid process in modular arithmetic. In particular, the quadratic formula holds true when the modulus is odd. Here we have $\Delta=b^2-4ac=57\equiv100$ which has square root $10$. Thus the solutions are $(-7\pm10)/2$; note $2^{-1}\equiv\frac{43+1}{2}=22$.
Comment: Observe $-7\pm10=3,-17$. I've already pointed out $2^{-1}\equiv22$. So then compute $3\cdot22\equiv23$ and $-17\cdot22\equiv13$. Why should you assume two sets of answers are different before you've simplified?
Comment: Then that's the root. You compute the square root of `g` and you compute the inverse of `2` and you compute `(k+sqrt(g))/2`, which *is* what I did in my above comments.
Comment: You compute the square root *modulo whatever number you need to*. Above I computed the square root of $57$ modulo $43$ by observing $57\equiv100$, hence the square root of $57$ is $10$ (well, one of them is).
Answer: The congruence is equivalent to $4n^2+28n-8\equiv 0\pmod{43}$ (we multiplied through by $4$.) This can be rewritten as
$$(2n+7)^2-49-8\equiv 0\pmod{43}.$$
Equivalently, we want to solve $(2n+7)^2\equiv 14\pmod{43}$.
Since $86+14=100$, We can probably spot immediately the solution $2n+7\equiv 10\pmod{43}$ and then by symmetry $2n+7\equiv -7\pmod{43}$.
Now we have two linear congruences to solve for $n$, namely $2n+7\equiv 10\pmod{43}$ and $2n+7\equiv -10\pmod{43}$.
To solve the first, rewrite as $2n\equiv 3\equiv 46\pmod{43}$, giving solution $n\equiv 23\pmod{43}$. The other calculation is very similar.
Note that we have essentially used a version of the Quadratic Formula.
Generalizations: The procedure we used is general. Let $p$ be an odd prime, and consider the quadratic congruence $an^2+bn+c\equiv 0\pmod{p}$, where $p$ does not divide $a$. Rewrite the congruence as $4a^2+4ab+4ac\equiv 0\pmod{p}$, and complete the square as above.
But we are left with a congruence of shape $x^2\equiv d\pmod{p}$. There are easy computational methods to check whether this congruence has a solution. (Half the time it doesn't, and then the original congruence does not have a solution.)
For primes of the form $4k+3$, there is an easy way to compute the solutions when they exist, essentially by using Fermat's Theorem. For other primes $p$, there are good algorithms for solving the congruence $x^2\equiv d\pmod{p}$, even for very large $p$. For details, you may want to look at the Wikipedia article on the Tonelli-Shanks algorithm.
Remark: We multiplied through by $4$ to prepare for the generalization. However, in our case we can complete the square somewhat more simply, by replacing $7$ by $50$. Then note that $n^2+50n-2=(n+25)^2-627$, and we can replace $627$ by $25$, making the solutions obvious.
Comment: Yes, multiplying is always going to be the best method.
Answer: Hint I  Make the polynomial a sum of a square and another number.
Hint II  What is $7/2\pmod {43}$?

Have a look at this page if you are not yet familiar with modular arithmetic: Here we are just computing things modulo a prime, namely, if the difference of two numbers is divisible by $43$, then we deem them as equal. And this explains what we meant by the inverse of a number: if $ab$ is regarded as equal to $1$ in our new point of view, then we say that $b$ is the inverse of $a$, and denote by $a^{-1}$.

Can you take it from here?
Comment: I am sorry but I have no idea what this is asking me. (n+7/2)^2-57/4?
Comment: You got it! Now just translate everything to modular arithmetic!
Comment: I have no idea how to take it the rest of the way though
Comment: How about the added version?
Answer: The number $43$ is a prime, thus we can work like we always do, for example, with real numbers: all the same rules apply to the integers modulo $43$. Now, we seek to complete the square. All equalities are in $\Bbb Z/43\Bbb Z$, the integers modulo $43$:
$${n^2} + 7n - 2 = 0$$
$${n^2} + 2\frac 72n - 2 = 0$$
Note that $2$ has as an inverse the number $22$ since $2\times 22=44=1 \pmod {43}$. Thus $\dfrac 7 2=7\times 2^{-1}=7\times 22=25$. Then we get
$$\begin{align}n^2+2\cdot 25 n-2+25^2-25^2&=0\\
(n+25)^2&=25^2+2\\(n+25)^2&=25\\n+25&=\begin{cases}5\\-5\end{cases}\\n&=\begin{cases}-20=23\\-30=13\end{cases}\end{align}$$
Comment: @RGB: as viewed by most users that I have discussed this with, upvotes and downvotes are used as a measure of whether an answer is good or bad. People who post good answers will usually take downvotes quite harshly. I don't see that they can be realistically used to order answers since you have only one vote and the answer will probably get many at cross purposes to yours. That being said, voting is capricious. I cannot tell you or anyone else how to vote; that is totally your decision. I am just trying to help explain some of the reactions that your rationale may draw.
Comment: @RGB I have posted this with the best intentions. It is true maybe the word *field* is not appropriate, but I don't see why the OP should not be familiar with $\Bbb Z_{43}$ or whatever notation he uses. I explained precisely what I mean by $2^{-1}=22$, for example, and why I wrote $2\frac 72$ since we want to complete a square.
Comment: Could the downvoter explain? What is wrong?
Comment: I was just giving my opinion in what order the answer should appear on the page. For an OP that is trying to understand "why... $13$ is a solution", 'field', $\mathbb{Z}/43\mathbb{Z}$, $2^{-1}=22$, $2\frac{7}{2}$, may not be an answer. The answer is not for showing that you know, but for making the OP understand.
Comment: That's ok. As I said, at the moment I casted my opinion the order resulted in, first the answer with only hints, then mine very basic but inefficient, and then yours, efficient but more advanced.
Comment: @RGB Do you think this answer is not helpful, then? I don't understand what you mean when you "downvote to order". Use downvotes appropriately, please!
Comment: That is not what my vote means. Helpfulness depends on the OP's ability to understand it. My vote meant my opinion on what order the answers should be read.
Comment: @RGB There are very few answers. I find it **useless** to order them in **any** way. Don't you agree? What is the significance in which order these answers are read?
Comment: Assuming RGB hadn't just changed his/her profile moments ago, this is apparently how RGB actually operates, and didn't just make up this voting rationale for this answer alone. Regardless, it's our right to vote how we wish, even if our reasons are seen as alien or unfair by others, and even if the accomplishments ("ordering") of our voting behavior exists only in our minds. You are perhaps too invested if you feel the need to understand why others vote as they do or hope to see meaning or good in them; voting patterns on a spectrum from reasonable to senseless is an inescapable reality.
Comment: @anon Of course that is how he/she operates. I disagree with this. It's as if some guy went around spray-painting houses he deems less worthy to look at as opposed to that nice house down the road.
Comment: @robjohn I don't want to make this something personal. I don't really care about *this* particular downvote, but rather, about the general idea RGB has on the voting system.
Comment: As I see it, the only *important* use of votes is that answers come to rest in some order, in the long run. Two things should be taken into account. Posts stay in the site, and people often have limited time to read. I, of course, can't control the universe, specially not with a vote in this website. But if I am given the option I will cast my vote, my little grain of sand, according to how I think it is beneficial for the main goals of the site.
Comment: @RGB I have decided to bring this up on [meta](http://meta.math.stackexchange.com/questions/10474/downvoting-to-rmorder/10475?noredirect=1#10475).
Answer: They mean that the remainders of $13^2+7\cdot13-2$ and of $23^2+7\cdot23-2$ are zero after division by $43$.
If two number $n$ and $n+43k$ differ by a multiple of $43$, then the remainders after division by $43$ of $n^2+7n-2$ and $(n+43k)^2+7(n+43k)-2$ are the same. To see this is enough to show that their difference is multiple of $43$. In fact, $\left((n+43k)^2+7(n+43k)-2\right)-\left(n^2+7n-2\right)=2\cdot43nk+43^2k^2+7\cdot43k$, which is multiple of $43$.
This means that to find them it is enough to test the remainders of $n^2+7n-2$ evaluated at each $n=0,1,\ldots,42$, in the division by $43$. The analogous is true in general for any polynomial modulo any number $p$. It is enough to search the zeros among $0,1,\ldots,p-1$.

Polynomial modulus


Java reflection performance drops when packaged as jar

Question: I have a real head-scratcher here. I tried everything, searched everywhere. It comes from an application I inherited that test JARs.
(It consists of a GUI front and a command-line application that does the actual checking. The GUI runs the command-line app by launching a new JVM on itself [java -cp "itself.jar" com.different.mainClass]. It's a bad design, I know, but may be relevant.)
Anyway, this program contains some reflection calls nested inside two for-loops. The problem is that when the application is JARed up, the first reflection call takes exactly one second every iteration. But when it runs from classes, it takes a few milliseconds.
Practically, this means this command:
java -jar myjar.jar

takes hours.
This command:
java -cp "...[bunch of jars];myjar.jar" com.myclasses.main

takes minutes.
The JAR being tested is always a jar. The difference is only in the test application.
Any ideas or avenues to pursue are greatly appreciated. Thank you!
Comment: So `myjar.jar` is the test application?  And you only get the performance issue when it's run on itself, or is it on all jars?
Comment: Yes, myjar.jar is the testing application. The JAR to be tested is a different JAR included in the class-path.
Answer: You could consider running your program under a profiler like the Eclipse TPTP or YourKit and more precisely identify where your time is being spent.  That will very likely point you to an error in your code, or somewhat less likely to point to a bug in a library.  Then, if you cannot figure it out still, post the relevant code here and we can help out.
Comment: SOLVED! I was tracing some code and found that when run from the JAR, some library classes were taken from the classpath of the launching GUI program. Once I removed this library or matched the version, the performance bug went away when running from a jar. I don't 100% understand it, but this is what occurred:

The same library JAR was being used by the GUI, by the application and by the JAR to be tested. Somehow, when running from the JAR, the JVM that was launched by the GUI, even with it not being in the classpath, used the wrong version of this JAR (the same one from the GUI).
Answer: I don't know if this is related to your problem or not, but the "-cp" arguments in this command will be ignored:
$ java -cp "...[bunch of jars]" -jar myjar.jar

The "-cp" and "-jar" command options cannot be used together.  An executable JAR file gets its classpath from the JAR manifest.
I don't see how this explains the symptoms you are seeing ... but it does mean that what you are trying to do with an executable JAR won't work, and that maybe renders your question moot.

FOLLOWUP
Given that that was just a bug in the question ... not the real problem ...
My suggestion is that you run your tests using the 2nd form of java command; i.e. with the -cp option and a classpath.  It is hard to see how it would make any difference to the effectiveness of your testing regime.
I suspect that identifying the root cause of the performance problem would entail a detailed examination of what the tester application is doing.
Comment: Thanks! This was an oversight when typing the question. Class-Path is indeed in the manifest file, not the command line. Updated above to reflect this.
Answer: As mentioned by others, you really need to profile the code to see where it is spending its time.
If I had to guess, I would suspect that the reflections work is resulting in repeated look ups to a class loader and loading a class is slower when extracting it from a jar file.
But again, that is just a hunch.  You need to profile it to be sure.


Instrument Register tone and quality chart

Question: I have been looking for some time now, for a chart of all the different register tone qualities of all the instruments played in an orchestra. If you have a hard time understanding what I mean by that, I am sorry that I do not know the proper term. I was watching an Orchestration Tutorial online, and the tutor shows part of such a chart in one of his videos:

 namely at 2:05.
If anyone has such a chart and knows where to get it, or can find one online it would be much appreciated.
Thank you!
Comment: Go to a public library and ask for a book on orchestration.
Answer: Here is my feeble attempt at combining the individual instruments Register tone quality into one chart.
Note: Samuel Adler's Orchestration book did not have any of this for the Strings but that is not what I was looking for so I am satisfied. Also, I had a hard time getting everything in the image, so some instruments are placed rather randomly...
Comment: Yes, I should clarify that while Adler's book is very good, it is not without flaw.  I gave my original answer with the understanding that no source in perfect.  This little list is a good start!
Comment: @jjmusicnotes Have you ever seen the [Lange Spectrotone chart](http://www.alexanderpublishing.com/Products/Spectrotone-Chart-Download__Spec-01-Download.aspx)? I just found it and was wondering if it was worth the purchase. [Cambria Music](http://www.cambriamus.com/publishedWorks/pw_charts.htm) also seems to have it, and at a lower price.
Comment: No, I have never seen that chart before today.  Personally, I wouldn't bother with the money as preference for timbre combinations varies greatly between composers.  Moreover, the chart obviously worked fine for the creator, but in reading descriptions about the chart I would not categorize timbres in the same way, and therefore the chart is of little use.  I would recommend that you find sounds that you like, find out how to write those sounds out, and then write your own sounds and hear them played back. Having your music played by real people is invaluably helpful feedback.
Comment: I'll pick a minor nit: be very cautious writing tuba below A1 (nominally 55 Hz).  In the hands of anyone but a skilled player those notes tend to resemble tuned flatulence more than musical pitches.
Answer: Normally questions concerning material solicitation are shut down, but I think in this case, since it applies to orchestration, which is musical practice related to composition pedagogy, it is pertinent to this forum.
First, there are two great texts concerning orchestration: Alfred Blatter's "Orchestration" and Samuel Adler's "The Study of Orchestration."  Adler's comes with a CD and DVD so you can listen to scoring techniques and see performers playing the instruments.  Both texts contain registral characteristics within each chapter for each individual instrument.  Blatter's text also include dynamic curves as well, which is extraordinarily helpful.
That said, there is no substitute for getting the sound in your ears and for talking with real musicians.  Some musicians I have talked to disagree or laugh at some of Adler's registral descriptions.  One of the wonderful things about orchestration is that it is equal parts technique and personal aesthetic.
So, books are helpful, but asking friends to play through sketches is exponentially more beneficial for the composer / orchestrator.
Good luck.
Comment: Ok, thank you! I think I know a way of obtaining a copy of Samuel Adler's book, and I will check out Alfred Blatter's too. If they contain what I am looking for then I will accept your answer. Also, good point at the end. I will do that too!
Comment: Glad it was helpful.  I should add that you won't find a single chart with descriptive qualities, but rather small individual charts within each instrument section.
Comment: Yes, I see that, and I tried to create my own chart with all combined. They must have something like that _somewhere_, but I will accept your answer. I will also add an answer of my own containing my attempt at combining the different instruments into one chart, but yours is the official answer :)
Answer: The chart is from Principles of Orchestration, by Rimsky-Korsakov.
Here's a response from the video author:

OrchestrationOnline 5 years ago
Hi Anji! That is an excerpt from
Rimsky-Korsakov's "Principles of Orchestration." Many orchestration
manuals have indexes of instrument ranges, but since there are so many
instruments that might be used, these charts cover far more than one
page.

Online Source
Here's the full chart: Chapter I Table B
Comment: Thanks! Good to know the actual source after all these years :)


Prove that 18 | a if and only if 2 | a and 9 | a

Question: This is part of homework.
Let $a \in \mathbb Z $. I know I can express $ 2|a $ as $\exists d\in\mathbb Z : 2d=a $ and $ 9|a $ as $\exists e\in\mathbb Z : 9e=a$ but don't know how to use it in this case.
My proof is this:
Let's say that if $2|a$ and $9|a$ then $18 ∤ a$ (antistatement). That is a contradiction as we can, for example, take $ a=36$. Then $2|a$, $9|a$, but also  $18|a$. So the original statement must be true.
Is this proof enough or if something is missing then what?
Comment: The contrapositive of the desired claim is not "if $2$ and $9$ both divide $a$ then $18$ can't divide $a$".  As you point out, that statement is clearly false.  Rather, the contrapositive is "there exists some $a\in \mathbb N$ such that $2$ and $3$ both divide $a$ but $18$ does not."  Thus just checking the contrapositive for one particular $a$, like $a=36$ doesn't help.
Comment: Are you allowed to use the Fundamental Theorem of Arithmetic?
Comment: Your proof only shows that the original claim is true for the special case $a=36$. -- namely, if your method were flawless, you could use it (again with $a=36$) shoprove the "theorem" that $18\mid a$ if and only if $2\mid a$ and $3\mid a$.
Comment: Hint : if $a|n$ and $b|n$, then $lcm(a,b)|n$.
Comment: @Shaun It's not forbidden but i'd not use it if possible
Answer: If $\;18\mid a\;,\;$ then there exists $\;b\in\mathbb{Z}\;$ such that $\;a=18b\;,\;$ hence $\;a=2(9b)=9(2b)\;,$
consequently there exist $\;b_1=9b\in\mathbb{Z}\;,\;b_2=2b\in\mathbb{Z}\;$ such that $\;a=2b_1\;$ and $\;a=9b_2\;,$
therefore $\;2\mid a\;$ and $\;9\mid a\;.$
Conversely, if $\;2\mid a\;$ and $\;9\mid a\;,\;$ there exist $\;c\;,\;d\in\mathbb{Z}\;$ such that $\;a=2c\;$ and $\;a=9d\;,\;$ hence
$2c=9d\;.$
$d\;$ has to be an even number, otherwise $\;9d\;$ would be odd but it is impossible because $\;2c=9d\;$ is even.
Since $\;d\;$ is an even number, there exists $\;d_1\in\mathbb{Z}\;$ such that $\;d=2d_1\;,\;$ consequently
$a=9d=9\cdot 2d_1=18d_1\;,$
$a=18d_1\;,\;$ therefore
$18\mid a\;.$


Add a directory to python path using Canopy (Windows 7 64bit)

Question: I am running Canopy 1.5.5 as my default python environment on Windows 7 (64 bit). I have recently made a module, named tools, that was thought to be used in different scripts located in different directories of the system. To do that I would like to add the directory that contains the tools module to my python path. What is the easy why to do that without messing thigs up?
Thank you
Answer: Put the directory in your PYTHONPATH environment variable. See this article for how to (and when not to) do this:
https://support.enthought.com/hc/en-us/articles/204469160-How-do-I-set-PYTHONPATH-and-other-environment-variables-for-Canopy-
Comment: Thank you, it worked for me with Rapid environment Editor.


Resultados estranhos ao calcular o fatorial

Question: Não consigo encontrar qual o erro no meu código. Quando coloco números menores ou iguais a 12 meu programa da o resultado certo, porém a partir do numero 13 os valores saem equivocados e não consigo saber por que. Qual o erro?
class vdois {

    static int fatorial (int numero){
        int fat = 1;
        while (numero >0) {

            fat *= numero;
            numero--;
        }

        return fat;
    }

    public static void main(String[] args) {
        int numero = 13;
        System.out.println(numero+"! = "+fatorial(numero));
    }

}

Comment: Não é o mesmo pois quero saber qual o erro na maneira que eu fiz.
Comment: Não está excendendo o valor máximo do `int`? Substitui por `float` para você ver.
Comment: Deu certo! Mas ao inves de printar  62272... printou 6.2272..., tem problema acontecer isso?
Answer: Isso acontece porque o valor do tipo int é no máximo 2.147.483.647. Se você calcular o fatorial de 13, verá que vale 6.227.020.800, ou seja, já é impossível representar o valor com uma variável int. Você pode corrigir isso alterando o tipo para double:
class vdois {

    static double fatorial (int numero){
        double fat = 1;
        while (numero >0) {

            fat *= numero;
            numero--;
        }

        return fat;
    }

    public static void main(String[] args) {
        int numero = 13;
        System.out.println(numero+"! = "+fatorial(numero));
    }

}

Com isso, você já aumenta o range de valores possíveis na entrada, pois o valor máximo do tipo double é 1.7976931348623157E308 e, se fiz os testes certos, é possível calcular o fatorial de até 171.


Como chamar a mesma ActionResult mais de 1 vez para atualizar a página?

Question: Preciso chamar a ActionResult cada vez que seleciono um registro novo no DropDownList chamando apenas 1 vez quando carrega a página.
No Controller
        private string PegarCaminhoImagem(Int16 controle)
    {
        sistema_mobileEntities dao = new sistema_mobileEntities();
        dao.fotos.Find(controle);
        var caminho = dao.fotos.First().Foto;
        return caminho;
    }

    public ActionResult AtualizaFoto(Int16 caminhofoto)
    {
        int largura = 100;
        int altura = 100;
        String CaminhoFoto = "";

        try
        {

           CaminhoFoto = PegarCaminhoImagem(caminhofoto);

           var webImagem = new WebImage(@CaminhoFoto).Resize(largura, altura, false, false);
           return File(webImagem.GetBytes(), @CaminhoFoto);

        }
        catch (Exception ex)
        {
            return Json("A Imagem não existe : " + ex.Message);
        }

    }

Na Views:

@model ProjetoDelphiMobile.Models.cliente

@{
    ViewBag.Title = "";
}

<form>
    <fieldset data-role="controlgroup">

           Foto:

                 @Html.DropDownList("idFoto", String.Empty)

           Nome:
            @Html.TextBoxFor(model => model.nome, new { disabled = false })

           Nome:
            @Html.TextBoxFor(model => model.nome, new { disabled = false })

            Nome do pai:
            @Html.TextBoxFor(model => model.pai, new { disabled = false })

            Nome da Mãe:
            @Html.TextBoxFor(model => model.mae, new { disabled = false })

            Data de Nascimento:
            @Html.TextBoxFor(model => model.datanascimento, new { disabled = false })

Retornar para consulta

    </fieldset>

</form>
Comment: Poderia explicar melhor o seu problema? Não está conseguindo acessar a ActionResult? Não está conseguindo retornar os dados?
Comment: O problema é que está chamando apenas 1 vez quando carrega a página.
Comment: Quando você altera o Select, ele busca apenas 1 vez? Em uma nova tentativa não faz a busca na Action!?
Comment: Sim, só chama 1 vez, é quero chamar sempre que selecionar uma informação nova
Answer: Você pode alterar seu código para pegar o valor do Select da seguinte forma:
Quando você usa o HTML Helper : @Html.DropDownList("idFoto", String.Empty) o parâmetro "idFoto" fica sendo o valor dos atributos id e name do select quando este e renderizado para HTML.
Usando o recurso Inspecionar Elementodo Google Chrome por exemplo, poderá perceber que o seu @Html.DropDownList quando renderizado vira: <select id="idFoto" name="idFoto">, o seu select no evento change continua retornando os mesmos valores.
$(document).ready(function () {
    $("#idFoto").on("change", function () {

        var srcRecebe = $($(this)).val();

        if (srcRecebe > 0) {

            $.post("/ConsultaCliente/AtualizaFoto", { caminhofoto: srcRecebe }).done(function (data) {
                $('#caminho').attr("src", data);
            })
        }
    });
});

Fazendo isso, toda vez que o Select sofrer alteração será executado esse código, pode retirar também o onchange="BuscarCaminho()", não vai ser mais necessário, visto que o código acima pega diretamente do Select.
Comment: Fiz alteração da perguntar com o seu código, como está pegando o idFoto, alterei o meu controller onde tenho uma função para me retornar o nome do caminho da imagem. Só que a imagem não esta carregando, o caminho da foto seria "C:\imagem.jpg"
Comment: @itasouza Acho que você confundiu as coisas, vou editar minha resposta.


Implementing GARCH(2,2) QMLE: where does the data (squared returns) come into play?

Question: I am trying to implement a QMLE estimation of GARCH(2,2) model as a side project.
We can represent GARCH(2,2) as follows:
\begin{aligned}
r_{t} &= \mu_{t} + \epsilon_{t}, \\
\mu_{t} &= 0, \\
\epsilon_{t} &= \sigma_{t}z_{t}, \quad z_{t} \sim N(0,1), \\
\sigma_{t+1}^{2} &= \omega + \alpha_{1}\epsilon_{t}^{2} + \beta_{1}\sigma_{t}^{2} + \alpha_{2}\epsilon_{t-1}^{2} + \beta_{2}\sigma_{t-1}^{2}.
\end{aligned}
Using standard arguments, we can write the log-likelihood as
$$
\sum_{t}^{T}l(\theta|r_{t}) = \sum_{t=1}^{T}\log\bigg[ \frac{1}{\sqrt{2\pi\sigma^{2}_{t}(\theta)}}\exp\{\frac{r_{t}^{2}}{2\sigma(\theta)_{t}^{2}}\}\bigg]
$$
where $\theta$ is just the vector of parameters.
This would be estimated, at each time $t$ by plugging in $\omega + \alpha_{1}\epsilon_{t-1}^{2} + \beta_{1}\sigma_{t-1}^{2} + \alpha_{2}\epsilon_{t-2}^{2} + \beta_{2}\sigma_{t-2}^{2}$ instead of $\sigma_{t}^{2}$ and $r_{t}^{2}$ (data). However, my problem is basically that I cannot understand whether

$r_{t}^{2}$ is the data that we have (which would be logical) or
if $r_{t}^{2}$ is simply generated from previous iterations of $\sigma_{t}^{2}$, as $r_{t}^{2} = \epsilon_{t}^{2} = z_{t}^{2}\sigma_{t}^{2}=z_{t}^{2}(\omega + \alpha_{1}\epsilon_{t-1}^{2} + \beta_{1}\sigma_{t-1}^{2} + \alpha_{2}\epsilon_{t-2}^{2} + \beta_{2}\sigma_{t-2}^{2})$.

The latter doesn't make sense, and it means I only need to initialize the process and then I wouldn't need any data to fit it, and this is exactly what confuses me.
If the former is true, then how can we say that $r_{t} = \epsilon_{t}$?
I have already checked this post, which was quite helpful, but still does not answer my question.
Perhaps it has to something with conditioning on information at time $t$, but I am struggling to clearly understand this.
Answer: If the model were true, you would find that
$$
r_{t}^{2} = \epsilon_{t}^{2} = z_{t}^{2}\sigma_{t}^{2}=z_{t}^{2}(\omega + \alpha_{1}\epsilon_{t-1}^{2} + \beta_{1}\sigma_{t-1}^{2} + \alpha_{2}\epsilon_{t-2}^{2} + \beta_{2}\sigma_{t-2}^{2}).
$$
This provides a way to generate a time series $\{r_t\}_{t=1}^T$ given the starting values and the parameters. Suppose that God or nature did that, and now you have observed $\{r_t\}_{t=1}^T$. If you wish to find out what parameters and starting values were used to generate this time series, you can use the data $\{r_t\}_{t=1}^T$ to estimate them using, say, maximum likelihood.
There is no contradiction between how the data were generated and that you might want to find the parameters that you cannot observe directly.
P.S. Note that $z_t\sim \text{i.i.d.}\ N(0,1)$, not only $z_t\sim N(0,1)$.


Problema em execução de tarefas com dois botões no mesmo form em c#

Question: Sou novo no c#, então perdoe algum erro de novato.
Preciso colocar dois botões em um mesmo formulário,um para chamar um formulário, e outro para executar uma função
Estou tentando assim:
    private void button1_Click(object sender, EventArgs e)
    {

        dados_bd dados_formulario = new dados_bd();
        conection_database conexao = new conection_database();

        dados_formulario.NOME = textBox1.Text;
        dados_formulario.LOCAL_ARMAZENAMENTO = textBox2.Text;
        dados_formulario.DESCRICAO = textBox3.Text;

        conexao.cadastro(dados_formulario);

        textBox1.Text = "";
        textBox2.Text = "";
        textBox3.Text = "";
   }

    private void button2_Click(object sender, EventArgs e)
    {
        Form2 teste = new Form2();
        teste.ShowDialog();
    }

Se eu coloco a função de chamar outro form no button1, funciona, mas quando seto a mesma para o button 2, não. Inclusive, nenhuma função fica disponível ao button2. Gostaria de alguns esclarecimentos sobre isso.

Mudei o código, como sugerido mais acima, mas não funcionou. Então coloquei a sugestão na função do button1, que era o único que funcionava, e a função que antes estava atribuída a ele, no botão que não respondia.
Mas, eis que agora os dois botões estão chamando a form2, mesmo a função estando atribuída apenas ao button1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            new Form2().Show();

       }

        public void button2_Click(object sender, EventArgs e)
        {
            dados_bd dados_formulario = new dados_bd();
            conection_database conexao = new conection_database();

            dados_formulario.NOME = textBox1.Text;
            dados_formulario.LOCAL_ARMAZENAMENTO = textBox2.Text;
            dados_formulario.DESCRICAO = textBox3.Text;

            conexao.cadastro(dados_formulario);

            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
        }
    }
}

Comment: E voce tem certeza que o evento está atribuído ao elemento?
Comment: Não tenho certeza, me diga como, repito, sou novato.
Comment: De dois clique no botão2 e verifica se ele está indo para o método button2_Click ou se ele está gerando um novo método.
Comment: Quando clico duas vezes, ele cai no método de button1. Preciso apenas fazer essa referência ao médoto Button2_click? Como faço?
Comment: conseguiu resolver seu problema Igor ? por favor, marque a resposta. Obrigado
Answer: Aparentemente não há qualquer coisa peculiar que faça o código funcionar no primeiro botão e não funcione no segundo. De qualquer forma, eu alteraria um pouco a invocação:
private void button2_Click(object sender, EventArgs e)
{
    new Form2().Show();
}

ShowDialog() não é uma boa porque o form vai ser invocado como modal, o que não permite mexer em outros forms enquanto ele estiver aberto.

Possivelmente os dois botões estão apontando para o mesmo evento, no caso:
    private void button1_Click(object sender, EventArgs e)
    {
        new Form2().Show();
    }

Clique em cada botão e verifique as propriedades, sobretudo na parte de eventos:
Comment: @ArturoTemplário Se você não vai precisar usar uma variável, é melhor não criar =D
Comment: @ArturoTemplário Não é o caso, certo? Se podemos fazer simples, por que devemos complicar? Deixemos os usos complicados para os casos complicados.
Comment: Muito obrigado pelas explicações, sempre é bom ouvir de alguém mais experiente :)
Comment: eu não costumo programar para Windows Forms, então desculpe a ignorância. Mas porque existe esse costume de abrir os forms sem manter uma variável como uma referência para ele?
Comment: Mas por exemplo, caso você tenha a possibilidade de abrir um form repetidas vezes, para, por exemplo, enviar uma mensagem. Aí você abre e fecha ele repetidas vezes. Mesmo assim é melhor não criar a variável?
Answer: Seu problema está na atribuição do evento,
você pode atribui-lo via código:
 public Form1()
    {
        InitializeComponent();
        button1.Click += button1_Click;
        button2.Click += button2_Click;
    }

    void button2_Click(object sender, EventArgs e)
    {
        //Evento click do botão 2
    }

    void button1_Click(object sender, EventArgs e)
    {
        //Evento click do Botão 1
    }

ou pela IDE como o Cigano mostrou acima, ficaria assim:

lembrando que, ao dar 2 Cliques no botão (dentro do visual studio), ele já será levado ao evento Click, ou dê 2 cliques no espaço em branco na frente do Evento desejado, na janela de propriedades, que será gerado um novo evento para o controle.