Pull the variable out of the fraction

Question: I have a code which outputs a polynomial, the last line is of the form: K[f[#]/g[#] &, 6], with f and g being some functions. The coefficients are fractions, but the output has terms which look like 1234x/46436. When I try to export this as latex, it looks ugly as the variable x isn't outside the fraction. Is there a way to put x outside the fraction (make it looks like (1234/46436)x) before or during the conversion to latex? Thank you!
Answer: You don't have an example polynomial, so I will use the following:
poly = (x+2)^5/10 //Expand

16/5 + 8 x + 8 x^2 + 4 x^3 + x^4 + x^5/10

To force rationals to precede the polynomial variables, you can wrap them in HoldForm before converting to latex. For example:
poly /. r_Rational :> HoldForm[r] //TeXForm

$\frac{1}{10} x^5+x^4+4 x^3+8 x^2+8 x+\frac{16}{5}$
Comment: @Silviu it is not good etiquette to ask a question, then when someone spends time to provide an answer, expand the question. Everything you want to do should be in your original post
Comment: Thank you! It looks like what I want. However, I also write the numerator and denominator of each fraction in its prime factorization, and if I use the line you suggested on that it doesn't seem to work. Do you know why might be the case? Something like this: 1/primeFactorForm[gcd]*Plus @@ List @@ Expand[gcd*poly]  /.
 Times[Rational[n_, d_], e__ ] :>
  primeFactorForm[n]/ primeFactorForm[d]*e  /. r_Rational :> HoldForm[r] //TeXForm

Pull the variable out of the fraction


Android String Initialisation

Question: I have a query about strings.
I'm declaring my string array as:
private static String[] name;

I'm then trying to add a string to it:
name[0] = temp    // Where temp as another string

I am getting a nullpointer error with the above code.  Am I initialising my string array correctly?
Comment: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Answer: Looks like you've missed to write
name = new String[CAPACITY];
somewhere
Answer: If you want to add dynamically elements to an Array of Strings I would recommend you to do
private static ArrayList<String> name = new ArrayList<String>();

and then use below to add Strings:
name.add(temp);

If you know the size that it will have, then you can create an array like this:
private static String[] name = new String[10]; //if it's going to have 10 elements (typo corrected)

Answer: The problem is you have not initialized your string array.
You can declare and initialize it this way:
private static String[] name = new String[4]; Where '4' is the size of your array.
or:
private static String[] name = {temp, temp2, temp3}; Where the temps are each individual item in the array.
Answer: At the point
private static String[] name;

in your code, 'name' is still null.
for an array of Strings you have to declare the (constant) number of strings you want to store.
int n = 10;
private static String[] name = new String[n];

You then cannot ever write more than n strings to your array.
If you want to have the number of strings dynamically, you have to use a Vector<String> or an ArrayList<String>. Both objects use the myStrings.add(String string)-method to add a string and you can access strings by calling myStrings.get(int position).

Android String Initialisation


Short story about advertising replacing music

Question: I remember a short story about a future where advertising jingles were the only type of music still performed.   If I recall, one musician rediscovered the idea that music could exist by itself and sets off an artistic revolution.  I read the story ~35 years ago but it could have been older.  Does anyone know the title or author?
Comment: Not what you're looking for, but a similar idea makes a brief appearance in the *Demolition Man* movie with Sly Stallone.
Comment: Sounds like it might be Panel Game by Brian Aldiss, but I can't find my copy of Space, Time and Nathaniel right now so I can't confirm for certain.
Answer: Tunesmith by Lloyd Biggle Jr.
Erlin Baque is the last true musician on Earth. Commercial jingles have replaced real art. The Performers' Guild enforces mediocrity on pain of blacklisting. . . But Baque has one weapon his enemies cannot resist: his music. (from Pastebin)


How do I sync Safari's Reading List between multiple Macs and an iPhone?

Question: I would like for Reading List to automatically sync between an iMac, MacBook Air, and an iPhone 4S.  The Macs are both running Lion 10.7.2 and the iPhone is running iOS 5.0.  All three devices are signed into the same iCloud account and have 'Bookmarks' checked.  It appears that some syncing has occurred at some point between them, but it hasn't seemed to be working lately.
Comment: I agree, I just checked and mine's not working correctly either. It's worked pretty well although not without hiccups. Sometimes iCloud syncing seems to need a kick in the ass to happen (restarting device, application or something like that).
Comment: I've got the same problem. iCloud does sync my Reading List from time to time but when it does it doesn't always sync everything. I think it's an iCloud problem. There's nothing to do but hope Apple fixes the issue. Except maybe letting Apple know about the issue.
Answer: Sometimes this can be caused by temporary issues with your account or the connection to the iCloud servers. Waiting it out isn't a bad strategy if you don't want to go for official support or when restarting the affected devices is not effective at clearing up the issue.
For ongoing issues, you might reach out to iCloud support to ensure it's not an issue with your setup or account.
Answer: This might be an issue with Apple ID password requirements. Does your 8 character Apple ID password include at least 1 number and 1 capital letter? If it doesn't, try setting a new compliant password to see if this fixes the iCloud problem.


How can I connect a Shure BETA 58A Vocal Microphone with a Samsung Galaxy S4?

Question: How can I connect a Shure BETA 58A Vocal Microphone with a Samsung Galaxy S4?
Answer: You can use a cable like this to connect the microphone to the 3.5mm jack headphone slot in your smartphone. That one is said to be working with a Galaxy Camera, be sure to check on Google and on users' feedback for the compatibility.
Important: you have to search, in general, for a cable which switches from XLR (the connection present in your microphone) to mini jack or 3.5mm jack (the headphone slot in your phone). The XLR has to be female (holes for the pins), while the jack must be male (the jack pin coming out, to be inserted in a jack hole). Be sure to check five times in the internet for compatibility issues and extra steps needed to make it work.
Comment: uhh the link links to a, uhh HDMI, uh, thingy.  Not an XLR-to-3.5mm adaptor, at any rate.
Comment: Thanks, I have no idea of how that thing came out. Inserted an appropriate link.


Simulating a quantum circuit with decoherence and noise

Question: Based on the answers given here and here, it is pretty clear that an arbitrary quantum circuit can be simulated with matrix algebra. The difficulty is that this assume perfect fidelity. I am unsure how to generalize this method to take into account imperfect gates and decoherence. I am sure that density matrices are involved.
Answer: You can simulate a noisy quantum circuit using density matrix evolution (as opposed to state vector evolution,) adding some noise operators to account for imperfect gates as well.
Some good reads could be Simulating noisy quantum circuits with matrix product density operators and Qiskit textbook chapter on density matrices.
Answer: If the goal is to classically simulate a noisy quantum circuit using discrete noise channels, there is an approximate simulation technique that avoids using density matrices (and therefore an exponential overhead) by simulating trajectories of the noisy quantum circuit.
Suppose you are interested in simulating an $m$-qubit unitary $U$ that can be decomposed as $U = \prod_{i=1}^m U_i$. We will assume a noise model where each application of $U_i$ is followed by some channel $\Phi_i$ acting on the state, and that the Kraus decomposition for $\Phi_i$ is known and is normalized to have the form:
\begin{equation}\tag{1}
\Phi_i (\rho)= \sum_{j_i} p(j_i) K_{j_i} \rho K_{j_i}^\dagger
\end{equation}
Then starting from the input state $|\psi\rangle$ and using the shorthand $\mathcal{U}_i(\rho) = U_i \rho U_i^\dagger$ we can compute the output as
\begin{align}
|\psi'\rangle \langle \psi'| &= \left(\prod_{i=1}^m \mathcal{U}_i \circ \Phi_i \right) |\psi\rangle \langle \psi| \tag{2}
\\&= \mathcal{U}_m \circ \Phi_m \circ \cdots \circ\mathcal{U}_1 \circ \Phi_1(|\psi\rangle \langle \psi|) \tag{3}
\\&= \sum_{j_1, \dots, j_m} p(j_1)\dots p(j_m)U_m K_{j_m} \cdots U_1 K_{j_1} |\psi\rangle \langle \psi | K_{j_1}^\dagger U_1^\dagger \cdots K_{j_m}^\dagger U_m^\dagger \tag{4}
\end{align}
Then the key to trajectory simulation is to sample a vector $\mathbf{j}$ with probability $p(\mathbf{j}) = \prod_{i=1}^m p(j_i)$ given according to the Kraus operators and perform (possibly subnormalized) state vector simulation:
\begin{equation}
|\phi_\mathbf{j} \rangle = U_m K_{j_m} \cdots U_1 K_{j_1}|\psi\rangle \tag{5}
\end{equation}
Then you repeat this $N$ times and average the state vectors together to get
\begin{equation}
|\tilde{\phi}\rangle \langle \tilde{\phi}| = \frac{1}{N}\sum_{\ell=1}^N |\phi_\mathbf{j}^{(\ell)} \rangle \langle \phi_\mathbf{j}^{(\ell)} | \tag{6}
\end{equation}
where each $\mathbf{j}$ is drawn independently at iteration $\ell$. But this is just an empirical average for the state resulting from noisy simulation, and so given large enough $N$, this empirical average will approach its expected value (by law of large numbers) which is given as
\begin{align}
\lim_{N\rightarrow \infty} |\tilde{\phi}\rangle \langle \tilde{\phi}| &= \underset{\mathbf{j}}{\mathbb{E}} [|\phi_\mathbf{j} \rangle \langle \phi_\mathbf{j}|] \tag{7}
\\&= \sum_\mathbf{j} p(\mathbf{j})|\phi_\mathbf{j} \rangle \langle \phi_\mathbf{j}| \tag{8}
\\&= |\psi'\rangle \langle \psi'| \tag{9}
\end{align}
where line (8) is substituted for Equation (4). This means if we perform some large number of size-$2^n$ state vector simulations and average the results, we get an increasingly good approximation for a size $2^{2n}$ density matrix simulation. The risk is that you will not generally know what $N$ is sufficient to get good convergence, and it will depend on your given noise model. But for intermediate-size systems (say $n\geq 20$), the linear scaling in $N$ is very tempting compared to the (worst case naive estimate) $O(2^{3n})$ scaling from matrix multiplication for $n$-qubit density operators.
This is the technique implemented in the qsim circuit simulator, but with a number of optimizations that are described in the white paper (disclaimer: I am a coauthor on that preprint).
Comment: Does this mean qsim support non-unitary operators for circuit simulation? Since Kraus operators are not necessarily unitary.
Comment: I don't know if you can simulate arbitrary non-unitary operators, but yes it uses matrix multiplication involving non-unitary Kraus operators in the course of simulating noisy channels.
Comment: Ok cool, so are those non-unitary Kraus operators predefined? Wondering how flexible a user can be in defining custom non-unitary Kraus operators for a trajectory simulation. Or is this method purely in the background and not accessible to users?
Comment: I haven't looked in a while. When I used it, qsimcirq supported converting cirq circuits that contained custom noise models, i.e. ones that I had specified kraus operators for. The custom model I used happened to be mixed unitary so i can't guarantee this is possible for arbitrary kraus ops, but i suspect it is
Answer: Let's call the Hamiltonian for the circuit $\hat{H}_\textrm{OQS}$, because it's an "open quantum system" which is open to decoherence from its environment, which we'll say has a Hamiltonian denoted $\hat{H}_\textrm{Bath}$. How shall we model $\hat{H}_\textrm{Bath}$? The environment is everything in the universe that interacts with $\hat{H}_\textrm{OQS}$: If it's the $\textrm{N}_2$ or $\textrm{O}_2$ molecules of the air that are interacting with the qubit, the most accurate quantum mechanical Hamiltonians for them involve their kinetic energies and the Morse/Long-range (MLR) potentials between them, which are basically harmonic oscillators until the atoms of the molecule get extremely far apart, for example at high enough temperatures for their bonds to start breaking. Likewise, if the qubits are in some solid-state material like silicon-chip qubits or qubits in GaAs quantum dots, then the atoms of the lattice can vibrate with MLR-like potentials, which are also harmonic oscillators except when the material is about to break. Whether the qubits are interacting with the vibrations of molecules in the air, or the vibrational phonons of a solid-state lattice, or even with photons in the air, $\hat{H}_\textrm{Bath}$ can be modeled as a sum of quantum harmonic oscillators:
\begin{align}\tag{1}
\hat{H}_\textrm{Bath} &= \sum_{\kappa=1}^N  \left( \hat{H}_{\kappa,\textrm{kinetic}} + \hat{H}_{\kappa,\textrm{potential}} \right)\\
&=\sum_{\kappa=1}^N  \left( \frac{1}{2}m_\kappa \hat{\dot{X}}^2 + \frac{1}{2}m_\kappa \omega^2_\kappa \hat{X}^2\right)\tag{2}\\
&=\sum_{\kappa=1}^N  \omega_\kappa\hat{a}^\dagger_\kappa \hat{a}_\kappa.\tag{3}
\end{align}
The simplest coupling we can have between each state $|j\rangle$ of the mult-qubit system
$\hat{H}_\textrm{OQS}$ and the oscillators of the environment, is linear coupling (and whatever the real coupling is mathematically, we can imagine that in a Taylor-type approximation of it, the first non-zero term will be linear):
\begin{align}\tag{4}
\hat{H}_{\textrm{interaction},|j\rangle} &= \sum_{\kappa=1}^N c_\kappa |j\rangle\langle j | \hat{X}_\kappa \\
&= \sum_{\kappa=1}^N c_{\kappa,j} |j\rangle \langle j | \left( \hat{a_\kappa} + \hat{a_\kappa}^\dagger\right).\tag{5}
\end{align}
Equation 5 is linear in $|j\rangle\langle j |$ and linear in $\hat{X}_\kappa$ and any more complicated Hamiltonian would appear exactly like Eq. 5 in a first-order expansion, which is already much better than simply ignoring decoherence (also note that I've absorbed the mass into the $\hat{X}$ operators to form scaled coordinates $\hat{Q}$ before using second quantization to represent the harmonic oscillators in terms of creation and annihilation operators, with the zero-point energy term ignored since it's proportional to the identity matrix and therefore has no non-trivial effect on the circuit's dynamics).
We now have the Feynman-Vernon Hamiltonian (which was actually studied earlier in a single-author paper about masers by Feynman's student Wells circa 1959-1961, and likely studied with different notation by Bloch and Wangsness before their 1948 paper, and apparently was used earliest in a Russian-language paper by  Bogoliubov, also see how the Froehlich Hamiltonian dating back to at least 1950 is presented here):
\begin{align}\tag{6}
\hat{H} & = \hat{H}_\textrm{OQS} + \hat{H}_\textrm{Bath} + \hat{H}_\textrm{interaction}\\
&= \hat{H}_\textrm{OQS} + \sum_{\kappa=1}^N  \omega_\kappa\hat{a}^\dagger_\kappa \hat{a}_\kappa+ \sum_j^M\sum_{\kappa=1}^N c_{\kappa,j} |j\rangle \langle j | \left( \hat{a_\kappa} + \hat{a_\kappa}^\dagger\right),\tag{7}
\end{align}
where $M=2^n$ for an n-qubit circuit.
You seem to already know that a closed quantum system (with no decoherence) with (constant-in-time) Hamiltonian $\hat{H}$ and initial density matrix $\rho$ evolves according to:
$$
\rho(t) = e^{-\frac{\textrm{i}}{\hbar}Ht}\rho(0)e^{\frac{\textrm{i}}{\hbar}Ht}\tag{8}.
$$
This is exactly the formula you would use to get the dynamics of the combined system comprised of the circuit plus its environment, so you could do the same matrix algebra to get the dynamics, this time including decoherence/noise. There might be many vibrational modes $N$ though, and many levels of the harmonic oscillators that are important, so the matrices might get huge quickly. Fortunately Feynman figured out how to solve this problem. If there's so many vibrational modes interacting with the system that we can say that the system's degrees of freedom interact with a mode of frequency $\omega$ with strength proportional to $J(\omega)$ (this is called the "spectral distribution function" or "spectral density function") for all non-negative real numbers $\omega$, and we have the initial condition:
\begin{align}
\rho(0) &= \rho_{\textrm{OQS}}(0) \otimes \rho_\textrm{Bath}(0)\tag{9} \\
 &= \rho_{\textrm{OQS}}(0) \otimes e^{-\beta H_\textrm{Bath}},\tag{10}
\end{align}
with $\beta \equiv \frac{1}{k_B T}$ at temperature T and with $k_B$ being the Boltzmann constant, then the dynamics of the density matrix of the circuit is given by the following double Feynman integral (it would be
a single Feynman integral if we only had to evolve the wavefunction, but since circuit will get entangled with the bath, we need to propagate a density matrix, which is like propagating two wavefunctions):
\begin{align}
\rho_{\textrm{OQS}}(t) &= \textrm{Tr}_\textrm{Bath} \rho(t) \tag{11}\\
                       &=  \int \int  \hat{O} \rho(0) I\mathcal{D}j(t) \mathcal{D}j^\prime(t),\tag{12}
\end{align}
where $I$ is known as the Feynman-Vernon influence functional (describing the influence of noise/decoherence) and $\hat{O}$ represents the dynamics of the quantum circuit without noise/decoherence.
If there's enough interest, I can give exact formulas for $I$ and $\hat{O}$ but it will involve a lot of typing.
The main point from a practical point of view, is that open source software in MATLAB and Python are available for calculating this double Feynman integral numerically for at least up to 16 qubits (maybe more) for if the bath is mathematically friendly enough for the calculation.
If you need to simulate more qubits or a more mathematically unfriendly bath, or need a faster calculation done but don't mind losing accuracy, Markovian (or even non-Markovian) master equations can be used to simulate $\rho_\textrm{Bath}(t)$ for the same Hamiltonian as above. Some of these master equations can give results quite close to the exact Feynman integral described above, especially if you use a unitary transform to look at the Hamiltonian in a frame which depends on parameters that are variationally optimized to minimize the Feynman-Bogoliubov bound on the free energy (essentially making the circuit-bath coupling weak enough in that frame to use weak-coupling master equation techniques without significant loss of accuracy), then transform back to the laboratory frame.
Answer: In addition to the rich physics answer by @user1271772 in terms of Hamiltonian, and computational approach answer by @3yakuya, I would like to add the quantum information picture here.
The imperfect fidelity can be modeled by two realistic scenarios:

The noisy gates (due to realistic crosstalk or decoherence via $T_1$ [amplitude damping] and $T_2$ [phase damping])
The false measurement apparatus (e.g. some measurement returning false outcome with some probability $p$)

The most general case incorporating both these phenomenon is a resulting density matrix which has suffered these noise types, which can be modeled as a quantum channel. It can be expressed using operator sum representation resulting into a final density matrix that can be beautifully written in terms of a superoperator as follows:
\begin{equation}
\Pi_{\text{real}}(\rho)=\sum_e \bigg( a_e^ME_e\Pi^M_{\text{ideal}}(\rho)E^\dagger_e+b_e^\bar{M}E_e\Pi^\bar{M}_{\text{ideal}}(\rho)E^\dagger_e \bigg)
\end{equation}
Here $\Pi_{\text{real}}(\rho)$ is the real projector incorporating the noise from the two above mentioned sources, with $\rho$ as any multiqubit state in general. $E_e$ are the error operators (usually strings of Pauli) and $M$ denotes the desired operator and $\bar{M}$ denotes the false measurement operator. $a_e^M$ and $b_e^\bar{M}$ are the probabilities of the true and false measurement outcomes. Here everything in known, in principle, given that you know what is the noise for the given circuit. Thus, you get the final density matrix with realistic noise.
You can say that after each single or two qubit gate you have an error $E_e$ in the circuit with some probability, and furthermore you can put a gate with a probability $b_e^\bar{M}$ that flips the measurement out come $M$ for any set of qubits desired.
Note that this does not contain any quantum gate required for the desired computation. Because quantum error correction is repeatedly formed and then computation, followed by desired rounds of error correction again, as the requirement maybe. You are not doing both simultaneously, they will not necessarily commute.


Tax situation for non-resident

Question: I have an F1 visa and my spouse is a permanent resident with no income. My employer has deducted FICA taxes and I would like to get a refund for that as well. What will be my best options for filing? I prefer to file joint.
Answer: Yes, you can file as Married Filing Jointly if you guys want. Either you are a resident alien, and so you can file jointly as both of you are resident aliens, or you are a nonresident alien and can use Nonresident Spouse Treated as Resident to treat you as a resident alien for the whole year and then file jointly.
If you were a resident alien on F1, the FICA tax would have been deducted correctly. If you were a nonresident on F1, you should have been exempt from FICA tax (this is true even if you used Nonresident Spouse Treated as Resident to file jointly with your spouse). You are exempt from the Substantial Presence Test for the first 5 calendar years on F1, so assuming you hadn't been to the US on F or J status before, if you came on F1 in 2012 or before, you would be a resident alien for all of 2017, but if you came on F1 in 2013 or after, you would be a nonresident alien for all of 2017. If you were a nonresident alien and they deducted FICA in error, you should first ask the employer to have it refunded. If the employer can't, you can file Forms 843 and 8316 to IRS to ask for a refund; note that this is independent from your income tax return, and may take years to receive a response.

Tax situation for non-resident


Should meta descriptions be unique for each page?

Question: Specifically, I'm wondering about pages that have a purpose that is sort of removed from the main site. For example, a privacy policy page - would you duplicate the description of the main page or is it best left alone?
Answer: Yes, all meta descriptions should be unique, because every page is (or should be) unique.
However, not every page really needs a meta description. It's only useful for pages that you want to rank in search results because that's where it is shown. For a privacy policy page, I would simply omit the meta description tag entirely.
Comment: As I mentioned in a similar question, the meta description text is used for more than just search engine results. Perhaps not all pages need it, but any page a user might bookmark should have it IMO. For instance, a user dashboard isn't something you'd want indexed by Google, but a user still might bookmark it. So it's useful to have a meta description that the browser can pull automatically. Also, many screen readers use the meta description to give a summary of a page.
Answer: Meta description is intended to be crawled, and has no direct effects for users. I guess you already know that.
Unless you want a different description for your privacy policy page and similar when these pages appears on google results.
As best practice, I'd recommend to put a simple unique description, but don't spent too much energy on that, because I believe only a few people will really be interested in searching your privacy policy page or similar.
Comment: Some web browsers store the page description as part of their bookmarking functionality.
Answer: Meta Descriptions also affect Click Through Rate (CTR) from the search results so a unique and relevant description can affect traffic for those pages ranked in the search engines


Conditional Shortest Path Through Weighted Cyclic Directed Graph

Question: Vertices in my graph are composed of {name, category} where category is one of {red, grn, blu, ylw}. Edges in my graph are weighted and directed. In the visualization, the thick end of the edge represents the destination.

My graph has negative cycles, for example [A-red, B-red, C-blu, X-grn, D-blu, A-red] has a cost of -1, comprised of edge costs [1, 1, -1, -3, 1].
I want to find the shortest path between arbitrary {source, destination} vertices subject to the following conditions:

Each vertex may only be visited once.
The count of vertexes visited along the path must be <= m
The count of categories visited along the path must be <= n

So, for example, assuming a function shortest_path(source, dest, m, n) then:
shortest_path(('A','red'), ('D','ylw'), 100, 100) would return [A-red, B-red, C-blu, X-grn, D-ylw] which has a cost of -2. This path visits 4 vertex categories [red, blu, grn, ylw].
shortest_path(('A','red'), ('D','ylw'), 100, 3) would return [A-red, B-red, C-blu, D-ylw] for a cost of 3. This path visits 3 vertex categories [red, blu, ylw].
Any suggestions here? I believe Dijkstra's algorithm and Bellman-Ford are out here as my graph contains negative cycles. So I think i need a brute force search of edges, integrating the stopping conditions mentioned above.
Python code for initializing my graph is here:
import networkx as nx

class Vertex(object):
    def __init__(self, name, category):
        self.name = name
        self.category = category
    def __hash__(self):
        return hash((self.name, self.category))
    def __eq__(self, other):
        if isinstance(other, Vertex):
            return other.name == self.name and other.category == self.category
    def __str__(self):
        return '{}-{}'.format(self.name, self.category)
    def __repr__(self):
        return str(self)

d = {
    Vertex('A','red') : {Vertex('B','red') : {'weight':1}},
    Vertex('B','red') : {Vertex('C','blu') : {'weight':1}},
    Vertex('C','blu') : {Vertex('D','ylw') : {'weight':1}, Vertex('X','grn') : {'weight':-1}},
    Vertex('D','ylw') : {Vertex('A','red') : {'weight':1}},
    Vertex('X','grn') : {Vertex('D','ylw') : {'weight':-3}},
}
G = nx.DiGraph(d)

pos = nx.circular_layout(G)
nx.draw_networkx(G,pos, arrows=True, with_labels=True)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos, edge_labels=labels);

Update
Here is my current traversal algorithm, its essentially a DFS but I record both the parent of each vertex I examine, and the cost of traversing from the parent to the vertex. This allows me to reconstruct a path and compute a total cost for the path. However, I'm not sure its a great solution. My aim is to get the algorithm working well then port to cython for performance (my real graph is huge).
#DFS
def calcd(parents, distances):
    d = 0
    for v in parents[1:]:
        d+=distances[v]
    return d

def backtrace(parent, start, end):
    path = [end]
    while path[-1] != start:
        path.append(parent[path[-1]])
    path.reverse()
    return path

def dfs(graph, source, target):
    visited = set()
    stack = list()
    parent = {}
    distance = {}

    stack.append(source)

    while stack:
        u = stack.pop()
        uob = graph[u] #edges outbound from u

        for v, eparams in uob.items():
            parent[v] = u
            distance[v] = eparams['weight']

            if v == target:
                path = backtrace(parent, source, target)
                print('Reached Target via {}'.format(path))
                print('calcd', calcd(path, distance))

            if v not in visited:
                visited.add(v)
                stack.append(v)

source, target = Vertex('A','red'), Vertex('D','ylw')
dfs(G, source, target)

This prints:
Reached Target via [A-red, B-red, C-blu, D-ylw] calcd 3
Reached Target via [A-red, B-red, C-blu, X-grn, D-ylw] calcd -2

Answer: The problem is NP-hard, even when you ignore the constraints about categories.  See https://cstheory.stackexchange.com/q/17462/5038 for a simple proof based on a reduction from the longest path problem (or from the Hamiltonian path problem).  Therefore, you should not expect any efficient algorithm.
There are algorithms whose running time is polynomial in the size of the graph but exponential in $m$ (the length of the path). See https://en.wikipedia.org/wiki/Longest_path_problem#Parameterized_complexity.
The categories don't increase the complexity of the problem by more than a constant factor, since there are only 4 categories.  For instance, if the path is required to use at most 3 different categories, you can enumerate all ${4 \choose 3}$ subsets of 3 categories, and for each, construct a smaller graph that contains only the vertices in that subset and then solve the problem on that graph without the restriction on the number of categories.  So for an algorithm design perspective, I suggest you first solve the problem while ignoring the categories.  It will then be straightforward to extend your solution to deal with the categories.
Comment: Yep seems like a reasonable approach. I have updated the original post with my current algorithm (basically a DFS). Would love to get your thoughts/comments.


cadence naming confusion

Question: Checking out cadences for a student, I thought that 'perfect' was the U.K. version of the U.S. 'authentic'. Then went on to find 'perfect authentic' cadence. It seemed like tautology, but it appears to be to do with the voicing. Does this become an issue? 'Perfect' is V>I, or V>i: end of? How does the voicing change anything? What other different cadences are there that are more specific than the usual perfect/imperfect/interrupted/plagal?
Answer: Not only are there inconsistencies between UK and American terminology, there are inconsistencies within just the American terminology! You're 100% correct that an "authentic cadence" is V–I, but it can be a bit more complex than that; here I'll give you the "academic" way of understanding classical cadences.

At A, we see the common Perfect Authentic Cadence (PAC). It's labeled such because both the V chord and the I chord are in root position and the soprano ends on scale-degree 1.
At B, we see the Imperfect Authentic Cadence (IAC). It's labeled this way because, although both the V chord and the I chord are in root position, the soprano ends not on scale-degree 1, but on scale-degree 3. (It could have also ended on scale-degree 5 and still been an IAC.)

From these two definitions, we see than an Authentic Cadence (AC) involves a V chord moving to I and both are in root position. This latter part can be contentious, but a number of music theorists, from Heinrich Schenker to William Caplin, have insisted on the V chord also being in root position. (More on that later.) The distinction between Perfect and Imperfect solely rely on the soprano scale degree.

At C, we see the standard Plagal Cadence. Note that some theorists don't consider this a "real" cadence per se because there's no V chord. I think that's silly, but from a standpoint of Schenkerian analysis, I understand why they say that. (In short, the Schenkerian mindset is that music is, at its most basic, a motion from tonic to dominant and back to tonic. If there's no dominant, there's no complete musical motion, thus no cadence.)
At D, we have what we in America call the Deceptive Cadence (DC). It typically moves V–vi, but really it can move from V to anything that's not I. (Note that some distinguish a Perfect Deceptive Cadence from an Imperfect Deceptive Cadence based on what scale degree is in the soprano, but this is pretty rare.)

Now, here's where the inconsistencies between textbooks come in:

At E, note that the cadence ends with IV6–V6–I. Some textbooks (like the Kostka/Payne) will call this an IAC because the V is inverted. Though this is one way of viewing it, the majority of professional music theorists will call this a Contrapuntal Cadence (CC) on account of the stepwise motion in the bass. In short, if one or both of the final two chords is/are in inversion, it is a Contrapuntal Cadence.
At F, we have a similar issue, but here both the final chords are in inversion: the V quickly moves through a V42 into a I6. You can call this a Contrapuntal Cadence, but it's such a common progression that it has earned its own name: an Evaded Cadence (due to how the bass quickly "evades" the feeling of closure with a root-position tonic chord).

Edit: Since I'm here I figured I might as well include some discussion of half cadences as well, even if they weren't addressed in the original question.

At G, we see the standard Half Cadence (HC). For a half cadence, all that matters is that it ends on a root-position V chord. (But again, some think a HC is possible with an inverted V chord.) There's also a disagreement on whether or not this V chord can include a chordal seventh. I think a V7 is fine to create a HC, but some disagree!
And at H, we see a more specific type of HC. Due to the half-step motion in the bass from the iv6 to the V, this is called a Phrygian Half Cadence. This must be a half step in the bass; if we move from IV6 to V in major, with a whole step in the bass, this just goes back to being a regular HC.
Comment: That's a lot of info! Thank you for your effort. I can surmise that PAC cannot happen unless there is satb - 4 part harmony. Although 4 part shouldn't necessarily be necessary to create a cadence. And IAC does sound like an oxymoron! Don't suppose 'imperfect  perfect' cadence is in the running! Until now, I'd have called E and F perfect cadences, which I suppose they are, but special cases thereof.
Answer: It does have to do with the voicing.  I found a definition that explains it pretty clearly I think,

In a perfect authentic cadence, the dominant chord in root position is followed by that of the tonic in root position, and according to some theorists, the cadence is not "perfect" unless the uppermost voice is the tonic in the final chord.

http://dictionary.onmusic.org/terms/2563-perfect_authentic_cadence
An authentic cadence then I guess could be summed up as any old V - I.
I only remember from school this naming applying to this type of cadence, I do not remember anything like a perfect plagal cadence, or perfect authentic deceptive cadence.
Comment: Bean-counters *like* counting beans. The more types of beans there are to count, the better!
Comment: That's the confusing bit, I think! If one *has* to end on root position, why only that one?
Comment: I think it helps to remember that these terms are always created in reaction to things happening in music.  A perfect authentic cadence is really just someone saying that this is the most perfect version of this cadence, I suppose the other cadences  could have that distinction based on voicing but just don't, as far as I remember.

cadence naming confusion


Why not have the diaphragm in camera body instead of the lens?

Question: Why is the diaphragm to control the amount of light entering the camera typically in the lens and not the camera body itself?
Comment: I have a Pentax Auto110, a cute little interchangeable-lens system from from the late 1970s. This system has an iris in the camera body which functions as both the aperture control and the shutter. So, they're not _all_ that way.
Comment: Thanks @mattdm, I really enjoyed reading about Pentax Auto110
Comment: @mattdm And so did the (compact point and shoot) Nikon W35
Comment: @Ryccardo Well, the Nikon doesn't have interchangeable lenses, so the distinction is... less distinct.
Comment: @mattdm yep, it was implemented that way as a cost cutting measure -- implementing "shutter closed" as "ƒ/∞"
Answer: The diaphragm is not at the back of the lens but in between optical elements.
Forcing it to be at the back would be severely restrictive in terms of lens design and wide-angle lenses would become impossible on most a sensor-size and flange distance combinations.
Comment: +1, exactly the answer. From a practical standpoint- the delicate shutter has a mirror to protect it, if the diaphragm was placed in the body there would be nothing to protect it.
Answer: Most lenses have one or more lens elements behind the diaphragm also. I actually haven't seen one that doesn't.
http://en.wikipedia.org/wiki/File:Tessar.png

From: http://en.wikipedia.org/wiki/Photographic_lens_design
Comment: Well, this is not a complete answer to the question. Why they 'need to' or had better to have elements behind the diaphragm?
Answer: Simple reason - it performs better when placed inside the lens. Interestingly the shutter assembly can also be made to perform better when placed inside the lens. So called leaf shutters operate when the cone of light passing through the lens is at its narrowest. This limits the travel required, allowing the shutter to go from completely open to completely closed far faster than a shutter inside the camera, allowing significantly faster sync speeds (maximum shutter speed with flash).
So why don't all lenses contain leaf shutters in addition to irises? Increased cost is one factor, unlike the case for an integral lens iris, a leaf shutter would have no effect on image quality so the cost is harder to justify. Secondly there's the fact that a focal plane shutter can achieve shorter exposure times than a leaf shutter by beginning to close before fully open (at the expense of no longer being able to sync with a flashgun).
Answer: The diaphragm performs two different functions:

It limits the amount of light that passes through the lens
It modifies the depth-of-focus

The second function can only be accomplished by placing the diaphragm at a particular point in the light path (at the focal point of one of the lens elements). That place is essentially always inside the lens body.
If you put the diaphragm on the camera body, you'd be limited to essentially the wide-open focus depth, and you might have some weird vignette-style effects from imaging the aperture onto the focal plane.
Answer: Actually, in-body apertures have existed on interchangeable-lens cameras, and in a way that allows lenses of different focal lengths to have common maximum apertures. Perhaps the best-known camera to do this was the Pentax Auto 110, a 110-format film SLR. Pentax went that route with the Auto 110 because it would be sturdier and less complex than trying to fit an iris and the auto-aperture linkage into the tiny lenses for the system.
The main problem with that approach is that it severely restricts the optical design of the lenses that may be used with the camera, since the node point of the lens (the point at which you can controllably restrict the amount of light passing through the lens without vignetting the image) needs to lie behind the physical lens. When that can be arranged, an iris that is external to the lens will have the same effects on exposure and depth of field as a more conventional design.
That means that retrofocus lens designs are impossible since the iris has to interact with the wide-angle group of elements and not the rear telephoto group, and that limits how wide the lenses can be. It also means that any long lenses need to be true telephoto designs (that is, the lens has to be optically shorter at the film side than it is overall) with a rear geometry that looks the same as the widest lens used. When your widest wide-angle option isn't so very wide, your longest long lens can't be too very long, and your mid-range lenses may not be optimal designs because you can't just put the iris where it "wants" to be, you lose a lot of options. And since the main draw of interchangeable lens cameras is being able to use the best lens for a particular task, cutting the choices down to three or four possible lenses over a narrow range of focal lengths would be a pretty effective foot bullet. Unless, of course, you're making cameras in a niche where it makes a sort of sense, like the Auto 110.
Comment: Are you absolutely sure the Pentax 110 SLR has a diaphragm that changes aperture size in order to allow more or less light? I thought the l shaped blades where not a diaphragm but asimple shutter to open and shut and that correct exposure on this camera was achieved simply by changing the time of the exposure.
Comment: @AndresCCC I'm pretty sure. You can see in the [manual](https://brettscaife.net/photo/manuals/auto110/index.html) that the aperture ranges from wide-open f/2.8 down to f/13.5 and you can read more about it [at Cameraquest](https://www.cameraquest.com/pentx110.htm).


What if natsu ate a star?

Question: Admittedly, I'm only 60 something episodes in, so this may already have an answer.
However, as hypothetical as this may be, due to the fact it seems impossible, I'm simply curious what hardcore Fairy Tail fans think might happen if Natsu were able to eat the fire of a star? Just how strong might he become? How much might his physical form change? Would a star's gaseous fire even be compatible?
If you've got the knowledge, I wouldn't mind someone applying some "scifi" theoretical science and possibly even math to the answer. Looking for a great read of an answer! Good luck and thank you!
Comment: Stars are NOT fire!
Answer: TL:DR, Natsu would be an OP fire god, and would never need to eat fire ever again
So as far as we know, Natsu's magic allows him to absorb fire (whether magical or natural) and lets him redirect it and use it however he wants. From all references there is no canon drawbacks from consuming exuberant amounts of fire, nor do we know the absolute limit of how much fire Natsu can consume. So within the Canon of Fairy tail, if Natsu actually consumes a star, he might as well not need to ever eat any more fire, unless it was in defense; he would be able to spout fire and use fire magic at any time.
However, let be speculative for a minute and try to SCIENCE this out. If Natsu was able to consume any amount of fire, dragon killer magic has to be able to preserve ones internal organs from being ripped apart by the heat and energy generated by any form of fire. But a star is a unending fusion reaction, and the mass of a star is capable of affecting large masses of matter. Thus if Natsu was able to consume a star, he would be consuming all of that mass. Given that Natsu's canon height of 175cm, and the average human weight of 65.3 to 79.8 kg, with an potential volume of around 0.06 to 0.08 m^3. If Natus was to consume the smallest possible star (a red dwarf, at the minimum weighs about 7.5% of our sun) would be gaining 1.49 x 10^29 kilograms. This will not generate a black hole, but hypothetically, this much mass will effectively cause the planet to envelop Natsu at is core. Not only killing him, but reshaping the planet, and killing everyone on it. So Natsu would be a fire god, and would never need to eat fire again, but he would also be the new core of the planet.
Comment: LoLz. Props for making me laugh
Comment: tried to channel Austin from THE SCIENCE!
Comment: This is probably my favourite answer as of now.  Sad that it's technically wrong as stars don't burn or produce fire, but are undergoing fusion reaction. (Oxygen is a requirement for fire, but there is close to none in space.)
Comment: and yet we still stars to "burn out" as they near the end of their life cycles, and "burn their fuel" as their cores collapse.

furthermore, fire/flames as a chemical reaction, is the production of ionized gases that react by giving off heat and light. This most scientific definitions are the principle properties of plasma. Stars are essentially balls of plasma that are produced by the nuclear fusion reaction.

What if natsu ate a star?


Fluxx: Does this person play all cards or does his turn end with new cards in hand?

Question: The "Play All" rule is on the table. Someone plays the new rule, "Get on with it" which states that "At any time before your final play, you may discard your entire hand and draw a new hand of 3 cards.  This is a free action but if you take it, your turn ends immediately."  So, if this player decides to discard his remaining hand & draw 3 cards, does he still have to play them, or does his turn end immediately with new cards still in hand?
Answer: The most logical way of doing it would be to end the turn with 3 cards in hand. This is because "Get on with it" always requires you to have at least one more play, and it still causes your turn to end. There is no reason for a Play All to effect the card any differently than any other Play X rule.
Answer: Play All is like having a rule that says "Play N where N is more cards than you could possibly play", so if you use "Get On With It" it's just like interrupting any other Play N rule. Or to look at it another way, when "Get On With It" ends your turn, that's it and your turn is over so you can't play any more cards.
Answer: The short answer is the players turn ends and they will have 3 cards in hand. To simplify it don't think of it as play all but play X where X is the current number of cards in your hand. Here is a quick example that might help.
A player starts his turn with 3 cards in his hand, play 3 cards, draw 1 card and get it on with rules are in effect. The player will start by drawing 1 card bringing him 4 cards in hand and having 3 plays to make. After looking at the cards he decides that if he played any of the cards in his hand it would be bad for him and good for his opponents so he decides to use get on with it. The first part of the card has him discard his hand and draw a new hand. Next it says that this is a free action but if you take it your turn ends immediately. That would be a new rule which takes precedence over the existing play 3 cards rule.
Now you can repeat that setup and replace the play 3 cards with a play all cards and after the player has discarded and redrawn 3 cards they would still have the same number of plays left as in the play 3 setup however the get on with it card will still trump and end the turn.
As a side note this is how it works in the iPad version of the game.


Do today's aircraft still have INS (inertial navigation system)?

Question: Do today's new aircraft like Boeing 787 still have INS (inertial navigation system)?
Answer: Short answer
Aircraft still use inertial navigation systems because INS is autonomous, it doesn't need any external support to work, it provides more information, and is more accurate than a GNSS in the short term. There is no plan to stop using it.
On the contrary, INS is required for certain operations. For instance the B787 cannot be flown without at least one IRU operative. See B787 Master Minimum Equipment List MMEL, item 21-01-01 page 182.
The usual solution for air navigation is to use INS, frequently updated by GNSS to contain drift, as long as GNSS signal is available, accurate and reliable (professional GNSS receivers are able to determine their reliability).

GPS/INS sensors fusion, source

Details
While INS has several disadvantages, namely initial alignment time and drift, it has also unique capabilities:

INS is autonomous, position is determined without external cooperative support.

INS position can be updated 1,000 times per second.

INS provides position information like GNSS, but also orientation (attitude), rotation rate and related accelerations. In the short term these data are very accurate. For example, the yaw damper uses instantaneous motion data to counter Dutch roll.

INS provides True North direction.

On the other hand, global navigation satellite systems (GNSS):

Contrary to inertial navigation systems (INS), are dependent on a lot of factors to work, including space vehicles, ground stations, antennas, or solar activity.

GNSS signals can be obstructed, altered or jammed.

GNSS is updated at a slow rate (e.g. once or 10 times per second, that is by increment larger than 20m for an airliner at Mach .85), due to the heavy computation required to extract and process the weak GNSS radio signal.

The best known GNSS, the American Navstar GPS, is a military system funded and managed by US Air Force.

While GPS is in effect always accurate for civil uses, it must be remembered there is no guarantee from the US DoD on that. The Navstar GPS operational specifications for SPS (civil) service allows for 72 minutes per day (2σ / 95th percentile) with a DOP > 3, that is more than 17m horizontally and 37m vertically. During these 72 minutes, the error is unlimited.

In the field of aviation, GNSS and INS are more and more coupled with air data and magnetometers, that's called data/sensor fusion to take the best of each system, cross check results and detect sensor failure.
As a everyday life example: Without an inertial sensor in a car "GPS receiver" (more accurately: a GPS-aided navigation system), the navigation system would be helpless at roundabouts. The GPS receiver instantaneous precision, its low update frequency, and its lack of orientation sensing would prevent it to correctly derives the actual position and the closest roundabout exit.
Comment: Do aircraft really use 1Hz GNSS? Receivers with 5Hz and 10Hz capability have been widely available for some time now.
Comment: @hobbs: You're right. That's still a large "blind distance" between fixes. 1 Hz is 280 m at 1,000 km/h, 10 Hz is 28 m.
Answer: To answer the specific question on the 787, yes.
According to this article

Boeing 787 avionics overview
Rockwell Collins provides the flight deck display system, pilot
  controls....Earth reference system (inertial navigation)....

In the more general sense pretty much all the big stuff flying (as far as I know) still has an INS unit. This may be due to the aircrafts age in that it simply comes from a time this was cutting edge. In the newer case they are still used to cross check GPS accuracy you can find more on in this answer (and dangerously close dupe).
Answer: Absolutely.  Both intercontinental civil aircraft and military aircraft are equipped with GNSS updated solid state INS systems using ring laser gyros for positional detection and navigation.
Comment: Can confirm that the T-38, F-16, and F-15 utilize RLG INS systems - sounds like they work pretty well, especially when linked to GPS positional updates
Answer: Modern aircraft have an "inertial reference system", which has the set of gyroscopes and accelerometers and is used to feed all systems that need those data.
The attitude, its rate of change, and accelerations (vertical acceleration is wing loading, lateral acceleration approximates side-slip) are used for:

Attitude indicator, obviously.
Also heading indicator.
Pitch and roll flight envelope protection on aircraft that have it (Aribus from A320 on, Boeing from 777 on and some other).
Autopilot and yaw damper. Altitude and heading respond too slowly to changes in control input, so those modes also need attitude and accelerations as intermediate references.
Flight laws. On Airbus even the manual control selects wing loading and roll rate and the actual control surface deflection is calculated by the computer, so it needs the wing loading (vertical acceleration) and attitude values.

The position is integrated. This means it accumulates error over time. However, there is never large error over short time. It can be also updated at high rate, usually 100 to 1000 times a second.
On the other hand, GNSS (e.g. GPS) does not accumulate error, as it does not rely on the previous measurement when doing the next, but it has slower update rate, usually only 1 per second, and it oscillates around the actual position with variable error magnitude of which can only be estimated to limited degree.
Therefore combining the two systems give some advantages:

INS interpolates the position, providing higher rate of updates to the autopilot, so it can follow defined route more precisely.
Since each system has different kind of error, cross-referencing them provides higher accuracy then either system alone.
INS provides fall-back in case GNSS (which may fail or lose precision for external reasons) fails. This is especially important when flying Required Navigation Performance (RNP) procedures. These are in places with limited terrain clearance like narrow valleys. If GNSS fails, the INS allows enough time to safely climb out of the terrain (and divert) before it accumulates too much error.


Would it be possible to use 3D printed node based structures to make cheaper GA planes?

Question: A car boasting 700HP and under the U.S LSA weight limit was just announced by Divergent Technologies. I was curious on peoples thoughts on using this technique in planes. Obviously there are some issues with the surface of the structure bearing load, but I imagine these could be overcome.
Answer: 3D printing is unlikely to make anything cheaper in the near future. With current printing technologies it's an order or magnitude or two more expensive per unit than volume manufacturing techniques such as extrusion or injection moulding.
It's notable that the company you link to chose to make a supercar rather than a low-cost small car. There's little price competition in that market, as brand loyalty dominates. Most supercars are bought as status symbols or for fun rather than for their actual road performance. Most of the incumbents manufacture very small runs with a lot of hand assembly: exactly the kind of manufacturing that 3D printing is competitive for. On top of that, because of the status symbol marketing, there's huge room for new players to differentiate based on a green image. Tesla has done this in the last few years, which is why some of DMF's marketing material focuses on dissing electric cars.
Runs are small in GA too, so there's potentially a wider niche for these techniques to fit into. The market that would most closely fit IMO is kit aircraft. A kit that's primarily 3D printed parts joined by standard spars, with a flexible outer shell, could have shorter lead times and less tooling cost.

After discussing this with some mechanical engineer colleagues today, they pointed out how 3D printing of metals is now being used as a complement to CNC machining in the rocket industry. For a part that has to be machined from a single piece of metal, they 3D print a shell that's slightly larger than the required shape, and then machine it to the correct shape. It allows you to achieve the tolerances you get from machining (which 3D printing can't yet deliver), but without the waste you get from cutting down a solid block.
It's an aside to the main question, but it's a way that 3D printing could be used to reduce the cost of some components and allow designs that would have been economically infeasible.
Comment: If I read your first paragraph it seems like your answer is "no". But GA aircraft are, as you mention further down, produced in small numbers. It seems that 3D printing as a competitive production technology when the production volume is low. The lower tooling costs offset the higher unit costs. In the end your answer tends to be a "yes", but I am not sure.
Comment: @DeltaLima There's small numbers and small numbers. Even a run as small as a few hundred units can be a lot more expensive with 3D printing. While some 3D printing techniques could make even smaller runs feasible from a manufacturing point of view, it wouldn't reduce the one-off cost of designing and certifying a new type. That's why I say it could find a niche in kit aircraft, which mostly fly on a Permit to Fly rather than a type certificate.
Answer: 3D printing is still an emerging technology. It's far from practical as a primary manufacturing method, but it is certainly possible as parts production - it is vastly cheaper to maintain a database of instructions than a warehouse of parts. Printers capable of making 1000cm$^3$ parts out of structural plastics like ABS are readily available on Amazon for $600. If you need bigger, the price goes up. A lot.
Airbus at one point was experimenting with 3D printing of sintered metals. If that ever works out it will revolutionise the spare parts industry, probably not in a good way.
As Dan said, kit and model aircraft will be early adopters.
Obligatory xkcd
Answer: I work at a company that routinely uses 3D printers for design of new components - although not for the aviation industry.  As the other posters have said, these parts are not cheaper than parts produced using other technologies.  However, our 3D printers have vastly increased the efficiency (and decreased cost) at which we can design new products.  Although 3D modeling of new parts in software goes a long way, being able to actually use the part in a prototype is a complete game changer.  And by printing out modified designs we can dramatically shorten the feedback loop to arrive at the "right" design.
I would suspect that use of this technology by aircraft manufactuers could therefore decrease the cost of design which might result in decreased costs overall.
Answer: The comments here are on point however I would like to mention that its very actively being looked into. GE successfully 3D printed a full working mini jet engine. That in and of its self is a pretty cool accomplishment. However it should be noted that the cost may not have been fully considered for that particular project.
GE also has at least one FAA cleared part that is 3D printed. It is a part for the GE90-94B jet engine.
Answer: The only kind of 3D printing process which produces structures fit for the load/weight ratios usual in aviation is electron beam printing. It uses titanium, stainless steel or aluminium grains (feels and looks much like sand) and heats that up locally to the melting point in an inert atmosphere, layer by layer. The advantages are:

Very fine structure, better than what is achievable by casting.
No molds.
Geometries which would be impossible to mold by casting or milling.

But there are disadvantages:

Rough surface; minimum roughness is given by grain size.
The surface imperfections translate into a notching effect, so the actually usable cross section is smaller than what is produced, which reduces material efficiency.
Manufacturing cost hardly goes down with the number of parts.

The only areas where this has been used gainfully so far are special cases:

Titanium implants, where replacements for bone structures can be custom-made within less than 24 hours. The rough surface is an advantage here, because it allows better integration into the body.
Replacement parts in case a JIT assembly line is compromised by one part missing.
Impossible geometries like hollow core pins for injection molding. The channels for the cooling water inside can have a corkscrew shape, one for the inflow, and one interleaved for the outflow. The gains in process efficiency can be immense.

In general, a 3D printed airplane is possible. Cost savings can be realized for a few special parts, but the general structure would certainly be more expensive. Consider that the surface roughness means that at least aerodynamic surfaces and contact areas with other parts need to be planed (e.g. by milling) after 3D printing.
While a single-issue sports car might be cheaper to produce this way, I very much doubt that GA manufacturing will benefit from 3D printing soon, even with the reduced production volume of today, except for some special parts.


When do I choose my energy type for Draconic Breath?

Question: The draconic breath feat says "If the breath weapon of your draconic forebears does not deal acid, cold, electricity, or fire damage, you choose from among the four energy types mentioned above." Does that mean I pick one when I get the feat or each time I use it?
Answer: I'd suggest that you'd pick the type upon choosing the feat, otherwise it'd be mechanically better to choose a draconic forebear which doesn't deal one of the energy types so you could get the extra utility.
Answer: This DM would allow any creature that possesses the feat Draconic Breath to pick anew the breath weapon each time the feat's benefit is used
The benefit of the feat Draconic Breath (Races of the Dragon 102), in part, says

As a standard action, you can convert an arcane spell slot into a breath weapon. The breath weapon is a 30-foot cone (cold or fire) or a 60-foot line (acid or electricity) that deals 2d6 points of damage per level of the spell slot you expended to create the effect.

To this reader it seems that, prior to the arcane spell slot's conversion, no decisions about the feat need be made. That is, before the creature takes the standard action and expends the spell slot, the creature has no breath weapon (at least via this feat, anyway). Nothing about the feat's benefit seems to this reader to limit the creature to only ever one of the listed area types then one of the corresponding energy types. In fact, this reader has always imagined sorcerers were just versatile that way, tapping into the power of dragonkind broadly to produce whatever effect they need at the time.
Likewise, to this reader the feat's Special entry seems to encourage this reading, saying, "If the breath weapon of your draconic forebears does not deal acid, cold, electricity, or fire damage, you choose from among the four energy types mentioned above," and again failing to mention when or even if such a choice need be made. The Special entry to this reader seems to be just a reminder that, for example, having a pyroclastic dragon in the family tree doesn't entitle the creature to an off-menu sonic breath weapon via this feat.
In short, this DM would be okay with ruling that the creature can pick a different (or the same) breath weapon each time a standard action's taken to convert a spell slot to activate the breath weapon. This DM believes that feats are allowed to do things, and to this DM that seems a reasonable thing to allow for a two-feat investment that also costs precious—and, to stay relevant, increasingly higher—spell slots.
However, this player can imagine another DM seeing the feat's benefit as potentially unbalanced if read this way. Being able to pick from among even four energy types does give a sorcerer—and, let's face it, the feat will likely be in the hands of a sorcerer who has plenty of spell slots to expend—a degree of versatility that a DM may not want or expect. This player would try to convince such a DM that the two-feat investment is, therefore, excessive for the result—saying, for example, that a sorcerer 6 can pick the spell lightning bolt—that has double the breath weapon's area—and save two feats, and that spell remains relevant until level 10! But, were that DM to remain unconvinced, this player wouldn't leave the campaign over it—there are plenty of other good or better feats; nonetheless, were such a ruling handed down early in the context of a potentially long-term campaign, I might either pick a different feat or retrain away the feat after level 6 or so (when the feat's largely no longer relevant) were the Player's Handbook II feat retraining rules in use.


Is garbage separation beneficial, if yes, how beneficial is it?

Question: I would have a question. I lived till now in a number of Eastern and Western European countries. With time I saw that the states/cities in which I lived made provisions (most recently in Poland-Warsaw), that garbage needs to be separated. Myself being an economist, I always wondered, are there real benefits to this garbage separation, or is it more a "feel good/image thing". Thus my question is, what exactly are the benefits (e.g. cost reduction, garbage processing efficiency...) of garbage separation. Any examples (especially quantifications of the benefits) would be very welcome (references to articles would be appreciated).
Comment: what are you comparing to? A place where the municipality does the separating and still recycles and diverts, or a place where it just all goes in the landfill? Or incinerator? Or ocean? The costs/benefits only exist in comparison to something else.
Comment: By "garbage separation" do you mean separating out recyclables? Or is it more than that, such as separating out green waste, used batteries, or something else?
Comment: @Kate Gregory Actually I must admit I don't know. My original idea is whether there is a benefit of recycling vs not recycling (Thus that would be the comparison you are asking for). Yet I would have to ask the question why we would be separating the waste and then everything would still go to the same landfill. As such any example of how waste separation contributed in a positive way (e.g. cost reduction and efficiency), would be deemed as sufficient by me).

Highly Irregular--->Primarily recyclables (Glass, Paper, etc...).
Comment: Your question is very broad. I suggest you limit it to one specific fraction  and one specific country to make it answerable instead of theoretical.
Comment: While the point of broadness is true, all I would actually want is one example (empirical study optimally), where it is confirmed that waste separation of any kind is efficient.
Answer: Let's compare a garbage-separating and recycling city A to three imaginary cities:

B, in which garbage is not separated and it all goes to landfill, incinerating, ocean dumping etc
C, in which garbage is not separated by householders but is separated by municipal staff, and some is recycled
D, in which garbage is separated by householders but then just all sent to landfill (or whatever) anyway

Compared to B, the benefits are that some recycling happens. This means landfills are less likely to fill up, and the city may recoup some money - for example some cities pay to truck garbage a long way to landfills in other countries, and either pay less for recycles to be taken away or in some cases can actually sell their recycles. The cost savings do not always offset the costs to the municipality (trucks with special sections for recycles, larger storage and processing facilities, employee training) but in many cases they do.
Compared to C, the benefits are that the city doesn't have to pay its staff to sort, the householders do it for free. Also, the city doesn't need a large facility to do the sorting in. The costs are that untrained householders may throw out materials that could have been recycled, or contaminate a load of recycles with something non recyclable. As a result such locales spend money on training the householders. Also typically the city gives out free sorting containers which costs them money.
Compared to D, the benefits are solely the psychological ones (which also happen compared to B) that people become aware of whether materials they buy are recyclable or not, and see what proportion of their waste stream is plastic, paper, compostable, metal, and so on. They may change their consumption habits as a result. There are some places that feel this change in consumer habits is actually more important than what happens to the garbage after it is picked up, while others believe constructing a sham recycling program is ridiculous. The truth is that at any given time some city somewhere is sending recycles to the landfill (or incinerator) because the capacity of the places that take their recycles has been reached. The desirability of the collected material varies, but cities don't dare stop collecting; in fact the pressure is high to include more and more materials in the collection.
For example, where I live I can recycle film plastic (grocery bags etc.) There is a nearby factory that makes them into wood substitute. People who visit me and see this have asked their municipalities to do the same. Well those cities aren't near my factory. And there is only so much wood substitute needed; since it doesn't rot once we all have a picnic table and a deck why keep making more of the stuff? Yet they don't want to feel bad throwing out plastic bags, so they want their cities to take it and make them feel better. Often that means the cities start taking it, and do send a few loads to the diversion project, but not necessarily all of them.
If it's true that the benefits are large even compared to D, where the only difference is consumer behaviour, then it's clear to see they are even larger compared to B, since we both change consumers and divert from landfill. It's not clear how large they are compared to C. Among other things it depends on land cost and municipal wages.
Comment: Would you have any study or examination of the case C you proposed. From an argumentative POV I find your essay conclusive.
Comment: some numbers (and some more references) are in http://large.stanford.edu/courses/2012/ph240/micks2/ -- but you don't need a study to show that it's cheaper for me to sort my plastic bottles from my garbage (since I don't bill the city for that) than to build a place where paid city employees go through my unsorted garbage and sort it for me.


Smart Contracts & Ethereum for CRUD

Question: I want to understand whether Smart Contracts & Ethereum can be used to achieve the functionality of our current VB6 ERP application where we have concurrent users creating new transactions, editing/deleting existing transactions and have reports to view saved transactions. Can Smart Contracts/Ethereum be a platform of choice for such applications
Answer: Blockchains are, in theory, immutable. Once you have data in there nobody can take it out. Therefore also Ethereum transaction are immutable - they can't be modified or deleted. There is a small exception to this which does not make a difference here but I'll blurt it out: chain reorganizations (reaching consensus) may delete some blocks with transaction, but those transactions will be reprocessed in another block.
However, blockchains (and Ethereum) are very good in concurrency. Multiple users can read and write and the Ethereum can reach consensus about in which order the transactions should appear in the canonical (final) chain. Also viewing is very easy - all data which was ever input into the blockchain is visiable forever for everyone.
Therefore Ethereum is not suited for CRUD operations, and no blockchain is.
Comment: Thank you Mr. Peltonen for answering the question.
Its fairly clear to me that it would not be possible to build an ERP like application in Ethereum or for that matter no blockchain.
Answer: As the previous comment states, blockchain is not designed for CRUD operations, but... I believe there is a provocative idea here. An ERP performs many functions, but one could abstract its architecture as made of a few major building blocks: master data, transaction records, reporting, planning, and so on. One of the ERP initial - and still most important - use cases is to be the "system or records" for a collection of business processes (e.g. inventory management, procurement, sales etc.). And this happens to be a perfect use case for blockchain: storing in an secure way the records of processed transactions along a timeline. One "blockchain-enabled-ERP" would still have to use regular databases for other functions, like planning, and reporting, but I'd argue that with the emergence of IoT, moving the records into the blockchain is the inevitable right direction.

Smart Contracts & Ethereum for CRUD


How to print the math a computer does for binary search

Question: I'm working on a program that will ask the user to input a value between 3000-3100 and do a binary search and show how many comparisons it made.  Overall the search part of the program is working fine; however, my professor wants me to print the program doing the math.  For example, I need the program to show the computer doing the binary search math, and show the comparisons it takes for the program to find the inputted number.
I have a comparisonCount that I'm incrementing it when I do a comparison, but the results aren't what I think they should be. For example, my professor said if you input 3067 there should be 7 comparisons, but currently the program is saying 4, and the counter is saying 3.
Can you help me find the reason for the discrepancy?
Here's the code:
package binary.search;
import java.util.Scanner;

public class BinarySearch
{
    public static void binarySearch(int[] array, int lowerbound, int upperbound,         int key)
    {
        int position;
        int comparisonCount = 1;   // counting the number of comparisons
        // To start, find the subscript of the middle position.
        position = (lowerbound + upperbound) / 2;
        //System.out.println();
        while ((array[position] != key) && (lowerbound <= upperbound))
        {
            comparisonCount++;
            if (array[position] > key)          // If the number is > key, ..
            {
                upperbound = position - 1;     // decrease position by one.
            }
            else
            {
                lowerbound = position + 1;    // Else, increase position by one.
            }
            position = (lowerbound + upperbound) / 2;
        }
        if (lowerbound <= upperbound)
        {
            System.out.println("The number " + key + " was found in array.");
            System.out.println("The binary search found the number after " + comparisonCount + " comparisons.");
        }
        else
            System.out.println("That number is not in this array. The binary search completed "
                + comparisonCount +  " comparisons.");

    }

    public static void main(String[] args)
    {
        // Set up variables

        int arrLength = 100;
        Scanner inp = new Scanner(System.in);
        int[] num = new int[arrLength]; //Create array
        int repeat = 1;            //Boolean for repeat loop

        char yesNo;
        int upperLim = 3100;
        int lowerLim = 3000;

        //Populate array
        while (repeat == 1)
        {
            int value = 0;
            int valid = 0;

            for (int i = 0; i < num.length; i++)
            {
                num[i] = i + lowerLim;
            }

            //Get integer from user
            do
            {
                System.out.print("Please enter a number between " + lowerLim + " and " + upperLim + ": ");
                value = inp.nextInt();

                if (value < lowerLim || value > upperLim)
                {
                    System.out.print("That wasn't a valid number. Please try again. \n");
                }
            }
            while (value < lowerLim || value > upperLim);

            //Run binary search
            binarySearch(num, 0, arrLength - 1, value);

            do
            {
                valid = 0;
                System.out.print("Would you like to rerun the program? Y for yes, N for no.\n");
                yesNo = (inp.next()).charAt(0);
                if (yesNo == 'Y')
                {
                    repeat = 1;
                    valid = 1;
                }
                else if (yesNo == 'N')
                {
                    repeat = 0;
                    valid = 1;
                }
                else
                    System.out.print("Not a valid response. \n");
            }
            while (valid != 1);
        }
    }
}

Comment: why dont you just add a counter and increment it when there is a comparison?
Comment: how would I go about doing that? declaring a counter and then using counter++ ????  Like I need it to print that it did (3100 -3000)/2 = 50, so 3047 would be at the lower half of the scale and so on until it finds the number.  Would a counter do that?
Comment: yup. int counter =0; then when you need to increment it, call counter++
Comment: for some reason the counter still isn't giving me the right reading.  My professor said if you input 3067 it should be 7 comparisons, currently the program is saying 4, and the counter is saying 3...
Comment: @JosephReed for 3067 the numbers compared will be 3049,3074,3061,3067.So there cant be 7 comparisons.
Comment: Added java tag, inferred from `import java.util.Scanner`. Tidied code formatting and a little rewording of the question.
Answer: Seven iterations is the maximum that it would take to find a number in a set of one hundred. That's because log2100 is somewhere between six and seven and you need to use the higher of those two values to be certain of finding it.
However, it may be less for certain specific values because of the way it works. Let's change your code so that it outputs what it's doing at each stage (just a few added outputs, sections marked with //<<here to //<<):
while ((array[position] != key) && (lowerbound <= upperbound)) {
    System.out.print(String.format(                        //<<here
        "Step %d, lo=%2d, hi=%2d, mid=%2d, [mid]=%4d, ",
        comparisonCount, lowerbound, upperbound,
        position, array[position]));                       //<<
    comparisonCount++;
    if (array[position] > key) {
        upperbound = position - 1;
        System.out.println(String.format(                  //<<here
            "too high, hi:=%2d", upperbound));             //<<
    } else {
        lowerbound = position + 1;
        System.out.println(String.format(                  //<<here
            "too low,  lo:=%2d", lowerbound));             //<<
    }
    position = (lowerbound + upperbound) / 2;
}
if (lowerbound <= upperbound) {
    System.out.println(String.format(                      //<<here
        "Step %d, lo=%2d, hi=%2d, mid=%2d, [mid]=%4d, found!",
        comparisonCount, lowerbound, upperbound,
        position, array[position]));                       //<<
    System.out.println("The number " + key +
        " was found in array.");
    System.out.println("The binary search found the number after "
        + comparisonCount + " comparisons.");
}

For example, if you're searching for 3049, you'll basically find that straight away:
Step 1: lo= 0, hi=99, mid=49, [mid]=3049, found!

For your specific value of 3067, it goes like this:
Step 1: lo= 0, hi=99, mid=49, [mid]=3049, too low,  lo:=50
Step 2: lo=50, hi=99, mid=74, [mid]=3074, too high, hi:=73
Step 3: lo=50, hi=73, mid=61, [mid]=3061, too low,  lo:=62
Step 4: lo=62, hi=73, mid=67, [mid]=3067, found!

Hence four iterations, as you're seeing. If you want to see the full seven iterations, you can just search for 3099:
Step 1, lo= 0, hi=99, mid=49, [mid]=3049, too low,  lo:=50
Step 2, lo=50, hi=99, mid=74, [mid]=3074, too low,  lo:=75
Step 3, lo=75, hi=99, mid=87, [mid]=3087, too low,  lo:=88
Step 4, lo=88, hi=99, mid=93, [mid]=3093, too low,  lo:=94
Step 5, lo=94, hi=99, mid=96, [mid]=3096, too low,  lo:=97
Step 6, lo=97, hi=99, mid=98, [mid]=3098, too low,  lo:=99
Step 7, lo=99, hi=99, mid=99, [mid]=3099, found!


Learning Arakelov geometry

Question: I have a complex analytic background (Griffiths and Harris, Huybrechts, Demailley etc). Also, I understand some PDE. I want to learn Arakelov geometry (atleast till the point I can "apply" computations of Bott-Chern forms and Analytic torsion to producing theorems of interest in Arakelov geometry). I know almost nothing of schemes or of number theory. I don't how much of these is needed to learn this stuff. I'd be grateful if any good references/suggestions are pointed out.
Comment: You should know about schemes in general, and a good deal about K-theory and intersection theory in particular (Fulton's book alone will not suffice). I suggest you have a look at "Lectures on Arakelov Geometry" by Soulé, Abramovich etc..., and a check the references given there.
Comment: I would say Fulton's book is not necessary since you anyway do intersection theory via K-theory.
Answer: Dear Vamsi,
A while ago I wrote my point of view on what "you should and shouldn't read" before studying Arakelov geometry. See
What should I read before reading about Arakelov theory?
Taking another look at that answer, it seems that my answer is  written for people with a more algebraic background.  I think the "road to Arakelov geometry" for someone from analysis is a bit different, but I'm convinced that the following is a good way to start for everyone.
If you're more comfortable with analysis than algebraic geometry, I think  a good idea would be to start with the analytic part of Arakelov geometry. This is explained very well in Chapter 1.1 of R. de Jong's thesis
http://www.math.leidenuniv.nl/~rdejong/publications/
and P. Bruin's master's thesis (written under the supervision of R. de Jong and B. Edixhoven)
http://www.math.leidenuniv.nl/~pbruin/
These two explain very well what Faltings and Arakelov did in their articles.
Since you don't want to apply the analysis to do intersection theory on an arithmetic surface, you don't have to go into this, I believe. (This is where schemes and number theory come into play.)
Now, I think after reading the relevant parts in the above references, you could start reading papers about analytic torsion (assuming you're already familiar with what this is). There's many of these, but I'm not the person to tell you which one is the best to start with.
Good luck!
Comment: Thanks for the answer. I also want to know if there are any applications of Analytic torsion outside Arakelov geometry. If not, I guess I would have to learn the scheme stuff....
Comment: There are definitely situations outside Arakelov geometry where analytic torsion appears. I just don't know any of them. I only know that analytic torsion appears in Arakelov geometry when one wants to define the Quillen metric on the determinant of cohomology of a hermitian line bundle. See the bourbaki talk by Jean-Benoit Bost in the early 90's or Soule's book on Arakelov geometry.
Answer: I second the suggestion of the book "Lectures on Arakelov Geometry" by Soulé, Abramovich, Burnol and Kramer.
There is this nice text by Demailly which motivates the treatment of intersection theory on the infinite fibers and probably suits you with your background.
With this in mind the analytic part of the above book should be ok to read.

Learning Arakelov geometry


How to troubleshoot Oracle database server errors?

Question: My team inherited an Oracle-based web application and they are fairly inexperienced with Oracle database servers.
The Oracle 10g server is running on a Windows 2003 Server with plenty of disk space and from time to time, all connectivity is lost, the application stops working, not even SQL Plus is able to connect to the database server.
But when we check the Windows Service manager, it says that the service is up and running. A restart usually fixes the problem, but we need to properly troubleshoot it so we know what's causing it and so we can avoid it to happen anymore.
Where should we start looking for clues? What are the criticial log files we should be investigating?
Comment: What's the error you get when trying to connect with SQL*Plus?
Answer: On the server you should have an environment variable called ORACLE_HOME which indicate the root of the Oracle install.  Most likely the Oracle trace/dump folders will be under there.  Search for a folder called "bdump" (background dump).  That's where the main log file, knows as the alert log, will be, as well as trace files generated by background processes.  There will be an adjacent file called "udump" which will contain any trace files generated by user processes.
However, my real advice is that you should either hire someone who knows Oracle or get Oracle Support involved.
Comment: Ditto on Dave's last comment. A day (or even half-day) from an Oracle person could save several days of digging around. Also, they'd be able to check out what db backup/restore is (or isn't) in place
Answer: The alert log would be the first file to check.
It will probably be in $ORACLE_HOME/admin/bdump and (probably) called alert_DATABASE-SID.log
It contains most of the important actions that the database does, as well as any important errors that occur.
Answer: I have to agree with cagcowboy.  Check your alert logs for errors.  If no errors then maintain a sysdba login into the database and when it hangs, attempt to do a hang analysis.  See metalink note 215858.1 on hanganalyze.
Answer: Have you tried tnsping?  We've occasionally run into problems with the listener that requires an assist from our DBA.  tnsping is the diagnostic tool we use to do triage.
I would recommend hiring an experienced Oracle DBA if at all possible.
Answer: check the alert log to see how the Db is structured. sometimes badly set parameters make hangs or slow performance. or you can shutdown and start in mount mode, then check the v$parameter values for problems. setting total memory is very important.


Finding the Index where a stock is listed and its impact on a stock's price

Question: How do I determine if NKE is a component of the  S&P, DOW or Nasdaq indexes and what effect an index  has on a stock's  price?
Is there a technical indicator that indicates if a stock is affected more by an index's volatility than another stock?
Answer: I think you may be misunderstanding what an index is. An index is just a mathematical calculation based on the values of certain stocks. An index goes up when the stocks in the index go up, and down when they go down. An index is volatile when the stocks in it are volatile.
It is true that being included in an index can affect a stock - in the sense that it is bought by managers who want to track indexes, and being in an index gives it a perception of 'quality'.  However those are secondary effects. Changes in the index don't affect the stock.
In general a stock is not affected by the behaviour of an index it is in. Instead the index is determined by the prices of the stocks that are in it.
(A stock may be bought or sold because a trader sees a change in an index and thinks the market is going up or down, but that is true of a stock that is not in the index as well.)
Comment: So no one actually owns shares of S&P 500, Dow, Nasdaq, etc? However, a person could own shares of an "index tracking" mutual fund or ETF? Those indexes are just placed on the front page of many financial websites to give us all a general look at major parts of the stock market?
Comment: Yes, that's it.
Answer: To see if a stock is a component of those indexes, Google:

"XYZ" Stock Components (where XYZ would be Dow, Nasdaq or S&P 500)

I would think that an index's volatility would be more affected by the stock's volatility than vice versa because index price is a function of the price of its components.
Answer: Everything is affected by everything
Being part of a stock index doesn't mean it's just that index and no other indexes which affect the price of a stock. Indexes affect each other as well, because the companies belonging to them are in competition of investors' money.
So, let's say the STOXX 600 index rises by 20% as measured in US dollars. Now the US stocks of S&P 500 are much better investments because you can get a particular amount of dividends for a stock price that hasn't increased yet. Guess what the investors do? They flock to S&P 500, because it's a better investment. The S&P 500 will increase by an amount for which the best estimate is 20% (although due to various random reasons, it won't increase exactly 20% but rather by an amount very close to 20%).
About the only location where you can say two indexes don't affect each other is a closed economy, where only locals can invest to the local indexes and locals are forbidden from investing to the global indexes.
You may be interested in beta (β)
In finance, beta is used as a measure for the characteristic of an individual stock when compared to the market portfolio. If the market portfolio rises by a relative amount X, the stock rises by a relative amount β * X. Similarly, if the market portfolio falls by a relative amount -Y, the stock falls by a relative amount -β * Y.
These are the explained stock price movements. Each stock price has also random movements that cannot be explained by movements in the market portfolio. In theory, there could also be deterministic risk-free return alpha (α), but in practice you cannot find α due to an efficient market.
Stocks with high β are high-risk high-return stocks. Stocks with low β are low-risk low-return stocks. So, the risk and return go hand in hand.
A quote from Investopedia:

By definition, the market has a beta of 1.0, and individual stocks are ranked according to how much they deviate from the market. A stock that swings more than the market over time has a beta above 1.0. If a stock moves less than the market, the stock's beta is less than 1.0.
Comment: Now I understand why the website "Seeking alpha" is... seeking alpha! lol I wonder where or why these greek letters are used? It's not like B stands for "high risk" or a stands for "risk free returns," I just wonder what's the history of these terms?
Answer: To find out whether or not NKE is part of the Dow Jones Industrial Average, do a Google search for list of Dow stocks and check whether or not NKE is in that list. (It is.)
Likewise, to find out whether or not NKE is part of the S&P 500, do a Google search for list of S&P 500 stocks and check whether or not NKE is in that list. (It is.)
To find out whether or not NKE is part of the NASDAQ Composite, look up which exchange NKE is traded on and see whether or not it's NASDAQ. (It's not; NKE is traded on the NYSE.)
It's probably impossible to measure the effect that indexes have on NKE's stock price, because it's impossible to determine which changes in NKE are because of the indexes, and which changes are not. What you can do is look at the correlation between NKE's daily returns and the indexes' daily returns. To do that, create a CSV file with the daily returns and then use statistics software to calculate the correlation.


Bound on exponential sum with weights

Question: Let $e(z)$ denote $e^{2 \pi i z}$ and let $f(z)$ a smooth real function.
I know one can bound sums of the form
$$
\sum_{x \leq X} e(f(x))
$$
via for example Van der Corputs's result, provided we make assumptions
on the range of the derivatives. I was wondering if there were results of this type
for weighted sums. Can we bound a sum of the form
$$
\sum_{x \leq X} g(x) e(f(x)) ?
$$
If so I was wondering what kind of assumption would be needed for g(z).
(In particular, would it possible for $g(z) = 2^z$, for example? ) Thanks!
Comment: if $g(z)=2^z$, then the last summand should give the dominant contribution to the sum. If $g$ varies slowly, then you can use partial summation. Look also in Titchmarsch and in Iwaniec-Kowalski for various results about exponential sums.
Answer: You can use van der Corputs's method for weighted sums as well, see Ch. III in

Karatsuba A. A., Voronin S. M. The Riemann zeta-function Walter de Gruyter & Co., 1992.
Answer: What is the exact result you have in mind? I see that a lemma of Van der Corput says something about integrals of functions which oscillate rapidly enough. In the case of a sum I don't see that you could expect the same cancellation to go on.
At any rate, the link has a result similar to what you want using integration by parts. Whatever is true for sums can probably be similarly generalized by a summation by parts .

Bound on exponential sum with weights


SharePoint - 80 : Error: The web.config is invalid on this IIS Web Site:

Question: I tried to deploy a .wsp solution to my SP farm.
But I met the following error:

Last Operation Result:    Some of the files failed to copy during
  deployment of the solution.
Last Operation Details:   V-SERVER1U :
  http://v-server1u/ : SharePoint - 80 : Error: The web.config is invalid
  on this IIS Web Site: D:\InetPub\wss\VirtualDirectories\80\web.config.

There is another suggested solution as follows, but I am unable to locate the service in my server.

In Central Administration-> Operation-> Services on Server, please
  stop the Windows SharePoint Services Web Application service,
  SharePoint will remove the sites in IIS. And then start the Windows
  SharePoint Services Web Application service again, SharePoint will
  recreate the sites in IIS based on information stored in configuration
  database.

I also tried to implement -Force in SP Management Shell deployment command, but met the following error too:

Install-SPSolution : This solution contains resources scoped for a Web
  application and must be deployed to one or more Web applications.

I have no other possible solutions to fix this. May I know how can I resolve it?
Answer: The service name in your post is "Microsoft SharePoint Foundation Web Application". You could stop and re-start the service "Microsoft SharePoint Foundation Web Application" in Services on Server.

To troubleshoot the issue, you could re-deploy the .wsp solution in the site.


Is it possible to monitor/block ALL network activity while using Orbot/Orfox on an unrooted phone?

Question: Does a person using an unrooted Android device have any options to successfully monitor and even restrict all network access; and have assurance that they are properly configured so that any allowed connections are routed through the Orbot/Orfox bundle? [LG K20: Android 7.0] Thank You!
Answer: The only approach to this is to use something like a "no-root" firewall. A "no-root" firewall uses the same principle as the Orbot VPN mode, except it uses it's position to deny connections to specific apps.
In this way, you could deny connections to all apps, except for Orbot effectively only allowing apps that can locally talk to Orbot be able to reach the internet, through Tor.
This would require that the apps are natively capable of utilising either an HTTP or SOCKS proxy and it has limitations, specifically ones that OrWall attempts to prevent. For example, the VPN might not be active during boot or before Orbot starts, which is why part of the OrWall design is to insert and init script to stop connections happening before the app can initialize and reconfigure the users iptables settings.
So there isn't something that is equivalent to OrWall without root, the closest solution would be some kind of "no-root" firewall.
Comment: Cacahuatl:  Thank you for responding. My confusion stems from not fully understanding the method(s) required to configure "native" System apps -- specifically Android System [UID: 0000?], LG apps, and Verizon apps -- to proxy via HTTP or SOCKS as you mentioned; or if this is even possible to do with these apps. I suspect that they are gaining network access via their own stealth ports, and will disregard any such customized routing(?).
"Rooting" keeps revealing itself to be the way to appease most of my concerns, but I've formed the impression that I need firmer footing along this path...
Comment: You can specify a proxy to use under the network connection settings, when you're configuring which wireless interface to use and that might allow some apps to use it but if they don't have native proxy support then the method simply won't work for them, they will not be able to connect to the internet.