Adding new data to an existing saved NSMutableArray saved on an iPhone

Question: I have an app that uses a saved file to load 2 pieces of data every time the App starts. Runs perfectly fine.  On the NEW version of my App, I want to add a Third piece of data.  However, I get this error when I run it:
Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]
Because when it reads the file on startup, it calls for a third piece of data when the existing saved file only contains two.
Here's my code:
int roundingSegment = 1;

and then:
- (void)viewDidLoad {

//---Check for existence of the Archive File on Startup-
NSFileManager *filemgr;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];

// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];

// Build the path to the data file
dataFilePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"data.archive"]];

// Check if the file already exists, and if so, loads the data
if ([filemgr fileExistsAtPath:dataFilePath]) {
    NSMutableArray *dataArray;
    dataArray = [NSKeyedUnarchiver unarchiveObjectWithFile:dataFilePath];
    defaultValueTextField.text = [dataArray objectAtIndex:0];
    segment = [[dataArray objectAtIndex:1] intValue];
       roundingSegment = [[dataArray objectAtIndex:2] intValue];
    NSLog(@" Segment is %d", segment);
       NSLog(@" RoundingSegment is %d", roundingSegment);
    }

[super viewDidLoad];
}

The problem occurs right at the end of the method because the existing NSMutableArray file with TWO pieces of data already exists and my code is trying to read a THIRD, namely the 'roundingSegment' variable.  (where I indented the code under // Check if the file exists...)
Do I have to delete the existing NSMutableArray the user has his data saved in when he loads the NEW version of the App?  And if so, HOW?!
OR, more preferably, is there a way to augment and add a third piece of data on the first run of the App so it doesn't hang when it tries to get my 'roundingSegment' variable?
Any help you can lend would be greatly appreciated!
Answer: You need to check [dataArray count] to see how many elements are in your array.
You should also consider refactoring your code to use a better mechanism for storing app data. Take a look at NSUserDefaults.


Practical Uses of Kernel Density Estimators

Question: Perhaps this question is too broad, but I would like to know - how does one use a kernel density estimate in practice? I know of course that one can use it to draw pretty pictures on top of histograms, but what in particular can a KDE be used for that the empirical distribution itself cannot be used for, especially with the whole notion of needing to properly determine the correct bandwith?
Comment: Kernel density estimators are also used in in nonparametric smoothing regressions. See, for example Buja, A., Hastie, T., & Tibshirani, R. (1989). [Linear Smoothers and Additive Models](https://projecteuclid.org/journals/annals-of-statistics/volume-17/issue-2/Linear-Smoothers-and-Additive-Models/10.1214/aos/1176347115.pdf). *The Annals of Statistics*, 17(2), 453–510.
Comment: One elementary use is to find the mode of a sample.
Comment: Rather than only drawing pretty pictures on top of histograms, lose the histogram altogether.  That's not to say that histograms should be completely replaced.  In other words it seems a bit schizophrenic to show both especially if you think the underlying distribution is relatively smooth and don't have too worry too much about boundaries.
Answer: As noticed by others, empirical distribution is not smooth, it's a step function. Say that you observed three datapoints: 2.56, 4.17, and 4.89 and I ask you "what would be the probability density of observing the value 3.14?". Given empirical distribution, there is no nice answer, you need to make some rather arbitrary decision on how to proceed. It's not really that empirical distribution "cannot be used" in such cases, but that it would serve as a very rough approximation of the underlying distribution.
There are many uses of kernel densities, for example:

Plotting is an obvious one.
Estimating mode of a continuous distribution, as mentioned by @BruceET in the comment.
Kernel regression, a non-parametric regression model.
Naive Bayes algorithm can use them to approximate the distributions of continuous variables.
Kernel discriminant analysis is another classification algorithm using KDE.
In cases involving data-based optimization or sampling, you often want not to be blind about the regions of the distribution where the data was not observed. In such cases, kernel density is a nice and simple way to "interpolate" those regions.

etc.
Yes, choosing the bandwidth is somehow arbitrary, but it often does not hurt us that much to pick imperfect bandwidth and there are already many available algorithms for picking it. Notice however that when using other methods (empirical distribution, $k$NN) you run into other problems, like deciding on how to interpolate and extrapolate from the estimated distributions, or picking other kinds of hyperparameters.
Answer: Kernel density estimation is a broad topic.
I have found publications on this topic by Bernard Silverman to
be informative and easy to read.
KDEs are used to approximate probability density functions of continuous distributions from data in one or more dimensions.
This Answer is limited to one-dimensional
distributions.
One use of KDEs is to make sense of the concept
of the mode of a sample. Elementary textbooks have formulas to find the 'mode' of a sample from a histogram. Often, these formulas choose a particular value in the histogram bin with the largest count. One difficulty with this approach is that there can be many different ways in which to choose bins for a histogram and so the 'sample mode' depends on how the histogram is drawn.
Consider the following sample of size $n=500$ from a gamma population distributed $\mathsf{Gamma}(\mathrm{shape}=5, \mathrm{rate}=0.1),$ which has mean $\mu = 5/0.1 = 50$ and mode $\delta = (5-1)/0.1 = 40.$
set.seed(827)
x = rgamma(500, 5, 0.1)
summary(x); length(x);  sd(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  6.573  35.058  46.678  50.415  62.719 138.549
[1] 500          # sample size
[1] 21.70053     # sample sd

Two histograms of these data are shown below.
The gamma population density curve (solid black) and the default kernel density estimate, KDE, from R (dotted red) are shown. The density and KDE are exactly the same in the two panels. However, respective modal intervals are $(49,60]$ and so $(40,50];$ histogram-based 'sample modes' would differ.

R code for histograms.
par(mfrow=c(1,2))
hist(x, prob=T, br=5, ylim=c(0,0.02),col="skyblue2")
 curve(dgamma(x,5,.1), add=T)
  lines(density(x), lwd=2, lty="dotted", col="red")
hist(x, prob=T, ylim=c(0,0.02),col="skyblue2")
 curve(dgamma(x,5,.1), add=T)
  lines(density(x), lwd=2, lty="dotted", col="red")
par(mfrow=c(1,1))

In R, the KDE connects 512 points, with horizontal and vertical coordinates summarized below.
kde = density(x);  kde

Call:
        density.default(x = x)

Data: x (500 obs.);     Bandwidth 'bw' = 5.361

       x                 y
 Min.   : -9.508   Min.   :1.785e-06
 1st Qu.: 31.526   1st Qu.:3.744e-04
 Median : 72.561   Median :2.738e-03
 Mean   : 72.561   Mean   :6.086e-03
 3rd Qu.:113.596   3rd Qu.:1.146e-02
 Max.   :154.630   Max.   :2.042e-02

The x-value with the largest y-value can be found as follows:
dx = density(x)$x; dy = density(x)$y
mean(dx[dy==max(dy)])
[1] 43.17016

It seems reasonable to say that the sample mode
is $43.17.$
Because gamma distributions are continuous, samples will not have tied observations, except those due to rounding. So it may be reasonable to view the mode of sample from a continuous distribution as the value that best approximates the mode of the population distribution.
Of course, you might get slightly different values for the sample mode by varying the bandwidth of the KDE or the types of curves chosen for the kernels. However, the default choices in R seem
useful for finding a reasonable value for the sample mode.
Note: The KDE method of finding sample modes does not work well when the mode of the population distribution is at a boundary of the support of the distribution. (For example, an exponential distribution.)
Answer: Here's one place where KDE is more convenient than ECDF: inverse CDF technique for PRNG. Yes, you can in principle use ECDF too, but since ECDF is step function, its inverse is not continuous either, so you have to do some sort of interpolation between the observations. It's not as elegant as KDE.


Can I install a light between two three-way switches?

Question: is it possible to add a light to a three way switch circuit between the two three way switches (ie can i tie into the three wire connecting the two switches in anyway to make them work the new light I've added)?
Comment: No.  The lights can only be controlled by the common terminal on one of the switches. Connecting the light to one of the travellers, will cause it to only be controlled by a single switch.
Comment: The trouble is basically all 3-way circuits use a 3-conductor wire (take a look at some [3-way circuit diagrams](http://www.easy-do-it-yourself-home-improvements.com/3-way-switch-wiring-diagram.html)). You always need 2 travellers, and so the other wire is either a neutral or the switched hot (and in the case of the light between the two switches, on one side it's switched hot, the other side it's neutral). The only way it would be possible is if you have a 4-conductor wire between the two switches or run a new 2-conductor wire (either between switches or to the new light).
Comment: The other option is to go to "smart" switches, such as Insteon, Z-wave, or UPB. With these, the switches communicate to each other using a separate carrier signal (either wireless or over existing 120V lines). Effectively any "smart" switch/keypad can control any other "smart" switch/bulb/module from anywhere in the house. If you go this way, you'd have to replace both switches with smart switches, and your 3-conductors between the two become hot, neutral and switched.
Comment: Tester101, I think your comment is the answer. If you entered it as an answer, I would certainly vote for it.
Answer: If you tap into the existing light box: Yes
There you will have the switched power and neutral.
If you try to tap into the triplex running from one of the switches: NO.
There you will only have the travelers and a power.
Answer: Yes if you don't need the three way functionality still and one of the boxes has power coming into it.  You can put a blank on one box, put your new one in-between, and keep one box for the current light switch.  I don't want to get into the wiring on this because it is simple (get rid of your 3-way comms wire - red one) and make sure your power/neutrals pass through, but there are tons of ways that 3 ways can be wired so don't want to get into too much detail.


How do you group a picture and a table in Word 2016?

Question: I am working through an issue with graphics that need to be translated in Word but I cannot change the original image. Is there a way to layer a table over a graphic and keep them locked together?  The Group function is grayed out when I select both elements. I have tried creating the combined elements in Word and PowerPoint but when I paste into my document, the two pieces move independently, even with an achor applied.
Answer: To put a picture behind the table use the "Text Wrapping", "Behind text" option.
To position it under the table anchor it to the first cell in the table using "Position" "Vertical" below "Paragraph", drag the achor to the first cell.


Is there any way to force the viewport to orbit the geometry center of the selections not the origin point

Question: when you toggle "orbit around selection" the fact is that the viewport orbits the origin point of your selection. and that origin point is not always at the selection's geometry center, sometimes even at the world origin, which makes the viewport navigation so frustrating.
Is there any way to force the viewport around the selection's geometry center no matter where its origin point is.
Comment: Preferences -> Navigation tab -> Orbit & Pan panel -> Orbit Around Selection orbits around the selected object based on geometry, not the origin point, so I am not sure what you are talking about. Could you clarify? Numpad . also centers the selection based on geometry not the origin. Maybe you have some floating vertices somewhere far away or your geometry is affected by something?..
Comment: I don't know what would make more sense. For me personally, the default Blender's navigation settings work absolutely fine without all this stuff. I was also going to suggest locking the view to 3D Cursor like Harry McKenzie answered.
Comment: I forgot to mentioned it is in edit mode
https://www.udrop.com/KSDP/2023-09-28_23-57-42_rf22.00.mp4
Comment: @MartynasŽiemys I haven't noticed this before.. in Edit Mode the orbit seems to be about the mean vertex location, (weighted towards density)?  Where it would make more sense to orbit around the selection's bounding box center?
Answer: My frustrations with viewport navigation have ended once I started using Lock To 3D Cursor. I just simply Shift+RMB to set the 3D Cursor to my point of interest and Shift+MMB to pan drag the view until the 3D Cursor is in the center of my viewport and my viewport navigation works perfectly. Or in your case set it manually to the geometry center. This also has always solved my zooming far in problems. I'm just confused why so many people don't use this feature. I have never found any reason to disable this so it's permanently enabled for me.
Comment: kind of solved my problem but still, just not as smooth as I expected, thanks anyway


IR Leds to be Driven by Coin cell

Question: Can a coin cell with rating >= 500 mAh be used to drive a set of 3 IR LEDs if each takes 100 mA forward current? I'll be drawing 300 mA (3 LEDs) current continuously from the cell, I heard that coil cell can deliver only low discharge current because if high current is drawn voltage drops very fast to thresh hold voltage of 2V.
Comment: a little help: if you don't want to get downvotes (and this question is asking for a downvote), you should show that you tried to solve problem, googled something, show some interest in solving the problem! Try googling stuff. There is no need to ask people every small question you may come up with, it's not a popular strategy around here. Showing that you tried to do/understand something will make everyone more positive to you.
Comment: You need each IR led to run at 100 mA, or they are rated for a maximum of 100mA but could (should) be run lower?
Answer: The internal resistance of a 2450 coin cell is about 10 Ω when fresh (see https://data.energizer.com/pdfs/cr2450.pdf). If you consumed 300 mA, the voltage would drop by 3 V -- and you wouldn't be able to drive the LEDs.
These cells are not suitable for high continuous currents; they are intended for very low continuous drain (at les than 1 mA), or brief high current pulses.
Although these are rated at over 500 mA.h, this does not mean you can consume at a load of 500 mA for 1 hour -- but you can consume at 1 mA for 500 hours.
Answer: Absolutely not. Coin cells can give only few milliamps at a time in the circuits they're normally used, I tried them in my project that pulled like 50-70ma (I was young), don't remember exactly, but it dropped immediately from 3.2 down to 2.65 when connected. It is indeed used for ultra low-power applications where current draw is sub-milliamp. Li-ion 3.7V batteries are a lot better for this application, but you still need some serious capacity if your LEDs are going to be ON for any signigicant amount of time and not one second per hour of work. So if some 500-1000mah battery physically fits in your project, you better use that, they don't cost much anyway and they're also rechargeable! I think it would be a win-win.

IR Leds to be Driven by Coin cell


Do 64gb and 128gb SDXC cards work on the Macbook Air 2011?

Question: I'm considering getting a SDXC card to extend the drive space of my Macbook Air. I just want to make sure both the 64 GB and 128 GB SDXC cards work on the 2011 Macbook Air.
Answer: It appears to work according to several reports:
http://www.zdnet.co.uk/reviews/ultraportables/2011/07/26/apple-macbook-air-2011-133in-40093522/

There has been some concern that Apple lists the MacBook Pro models on
  its web site as having an SDXC card slot, for high-capacity SD cards,
  and only lists the card reader on the Air as an SD card one. We tried
  a 64GB SanDisk SDXC card in the MacBook Air's card reader, and the
  system recognised it as the appropriate size and was able to access
  files on it. However, if you're looking to get a massive SD card in
  order to augment the smallish 128GB SSD built into the Air, note that
  the card slot leaves the SD card hanging halfway out on the side of
  the system, so it's not appropriate for full-time use.

https://discussions.apple.com/thread/3014714?start=0&tstart=0

I got my Transcend SDXC 64GB flash card, and yes, it reads and writes
  perfectly in my MacBook Air.

According to iFixit it uses the Gensys logic GL822 SD slot controller which is a USB 2.0 high speed device (480mbps) and supports up to 2TB SDXC cards.
Answer: According to this discussion thread on Apple's forums, both 64 and 128 GB SDXC cards are well supported on the latest [mid-2011 at the time of writing] MBA, provided you format them using the Mac OS X Journaled option.
Answer: My mid-2011 MacBook Air recognizes and uses a Komputerbay 64 GB SDXC card just fine. It's a $54 card from Amazon. However, I only get read speeds around 33 MB/s from this card.
the card reader is on a USB 2 bus so it will never be all that fast.  As some point they put the card reader on a ?pci-e? bus and it has higher possible speed.


$\int \frac{2x}{9x^2+3}dx=?$

Question: So this one seems very easy. And it really is (I guess). But I have an issue with this one. I solved it this way:
\begin{align}
& \int \frac{2x}{9x^2+3}dx=\frac{1}{6} \int \frac{x}{3x^2+1}dx=\frac{1}{6} \left( x\frac{\arctan(\sqrt3x)}{\sqrt{3}}-\int 1\cdot\frac{\arctan(\sqrt3x)}{\sqrt3} dx\right) \\[10pt]
= {} & \frac{1}{6} \left( x\frac{\arctan(\sqrt3x)}{\sqrt{3}}-x\frac{\arctan(\sqrt3x)}{\sqrt{3}}+\frac{\arctan(\sqrt3x)}{\sqrt3}\right)=\frac{\arctan(\sqrt3x)}{\sqrt3}+C
\end{align}
But at the same time, the textbook says, that it is equal to this:
$$
\frac{1}{9}\log(3x^2+1)+C
$$
Did I do something wrong? It would be quite hard for me to believ that these to functions are the same.
Thanks for the responses!
Comment: Try u-substitution instead.
Answer: Much simpler to just set $u=9x^2+3$. So $du=18x\,dx$ and the integral becomes
$$\frac19\int\frac{du}u.$$
You want to avoid trigonometric substitution if you can do $u$-substitution instead.
Answer: I'd have written $u = 9x^2+ 3$ so $du = 18x\,dx$ and $2x\,dx = \dfrac{du} 9$.  Then you have
$$
\int \frac{2x}{9x^2+3} \, dx = \frac 1 9 \int \frac{du} u = \frac 1 9 \log|u|+C = \frac 1 9 \log ( 9x^2+3) + C.
$$
This is the same as
$$
\frac 1 9 \log ( 3( 3x^2+1)) + C = \frac 1 9 \left( \log(3x^2+1) + \log 3 \right) + C = \frac 1 9 \log(3x^2+1) + (\text{a different } C).
$$
Your initial integration by parts says
$$
\frac{1}{6} \int \frac{x}{3x^2+1}dx=\frac{1}{6} \left( x\frac{\arctan(\sqrt3x)}{\sqrt{3}}-\int 1\cdot\frac{\arctan(\sqrt3x)}{\sqrt3} dx\right).
$$
That's alright as far as it goes.  I haven't attempted to figure out just what you're doing after that, but let's recall how to antidifferentiate the arctangent function:
\begin{align}
& \int \arctan x\,dx = \overbrace{\int u\,dx = xu - \int x\,du}^\text{integration by parts} \\[10pt]
= {} & x\arctan x - \int \frac{x\,dx}{1+x^2} = x\arctan x - \int \frac{dw/2}{w} \\[10pt]
= {} & x \arctan x - \frac 1 2 \log|w|+C \\[10pt]
= {} & x \arctan x - \frac 1 2 \log(1+x^2) + C.
\end{align}
So I suspect the first term in the result just above this line (suitably adapted with your $\sqrt3$, etc.) will cancel out the first term in your integration by parts and then the result will ultimately be the same.
Generally I wouldn't integrate by parts when a simple substitution will work, unless there were some special reason to do that.
Answer: Hint
$$\int \frac{2x}{9x^2+3}=\frac{1}{9}\int \frac{18x}{9x^2+3}dx.$$
Answer: $$\int \frac{2x}{9x^2+3}dx$$
$$2\int \frac{x}{9x^2+3}dx$$
Apply Integral Substitution $u=9x^2+3\quad \:du=18xdx$
$$2\int \frac{1}{18u}du = 2\frac{1}{18}\int \frac{1}{u}du=2\frac{1}{18}\ln \left|u\right|=2\frac{1}{18}\ln \left|9x^2+3\right|$$
So
$$\int \frac{2x}{9x^2+3}dx=\color{red}{\frac{1}{9}\ln \left|9x^2+3\right|+C}$$

$\int \frac{2x}{9x^2+3}dx=?$


How to control one motor with two float switches

Question: I have 2 tanks , one is under another and hopes to pump from under tank to upper one using a 0.5 Hp single phase motor.By connecting float switches for both tank,can I control the motor to turn on when the water level of lower tank is high and switches off when the water level of upper tank is high ( Upper tank has lower capacity than Lower ) and vise versa
Comment: I suspect that you want to control one motor with two switches, rather than have the motor control the switches, as the title says.
Comment: Certainly, yes.
Comment: I have question with the circuit, each float switch has 3 wires, what are the wires i need to use
Comment: You need to [edit] your question to add links to the datasheet for the switches. We can't guess.
Comment: https://www.wiltec.de/float-switch-pump-level-controller-cable-5m.html
Comment: You need to edit your question to add links to the datasheet for the switches. Don't hide them in the comments.
Comment: Do you want to keep the upper tank filled (ie, pump where upper tank not full AND lower tank not empty) or to only start pumping when the lower tank is full?
Answer: According to the datasheet the sensor and under the assumption that it works like https://www.youtube.com/watch?v=tA76sm_jJTk it can be used directly without the need of any additional circuit:

The parts are taken from the datasheet chart 2 and 5.
Answer: Yes, by using a relay, wired up as a latch. You have the high-limit switch as SPDT type which can serve as a cut-off.
Here's how it works:

The lower tank-high switch energizes the coil.
Relay self-energizes through one set of contacts, which latches it.
The upper tank-high switch turns off the relay, latch opens.

The connection looks like this:

simulate this circuit – Schematic created using CircuitLab


How do you calculate the nearest point on 2 curves?

Question: Given the points of a line and a quadratic bezier curve, how do you calculate their nearest point? .... Similarly, given the points of 2 curves, how do you get the nearest point?
Comment: I believe [this question](http://stackoverflow.com/questions/2742610/closest-point-on-a-cubic-bezier-curve) is a good start.
Answer: Here is my try. The following algorithms are far from perfect, but they are simple and I believe you should start with this, check whether they work in your situation, and switch to something faster and/or more accurate later.
The idea is the following:

Sample the Bézier curve, find the nearest point on that sample
Sample a neighbourhood around the found point, find a new nearest point
Continue until the point no longer changes much

Algorithm for distance from Bézier curve to line
The Bézier curve is parametrised by a function F(t) using a set of control points and a varying parameter t. The number of generating points is unimportant.
The line is parametrised by two points A and B.

Let SAMPLES = 10 for instance
Start with t0 = 0 and t1 = 1
Let dt = (t1 - t0) / SAMPLES
If dt < 1e-10 (or any other accuracy condition you see fit), algorithm is finished and answer is F(t0).
Compute a list of SAMPLES + 1 points on the Bézier curve:

L[0] = F(t0)
L[1] = F(t0 + dt)
L[2] = F(t0 + 2 * dt)
…
L[SAMPLES] = F(t0 + SAMPLES * dt)

Find which point in L with index i is closest to the line. Use any point/line distance method you know, for instance the square distance ||AB^L[i]A||² / ||AB||² where ^ denotes cross product and ||…|| is the distance.
If i == 0, set i = 1; if i == SAMPLES, set i = SAMPLES - 1
Let t1 = t0 + (i + 1) * dt and t0 = t0 + (i - 1) * dt
Go back to step 3.

Algorithm for distance from Bézier curve to Bézier curve
This time we have two Bézier curves, parametrised by F(t) and G(t).

Let SAMPLES = 10 for instance
Start with t0 = 0, t1 = 1, s0 = 0 and s1 = 1
Let dt = (t1 - t0) / SAMPLES
Let ds = (s1 - s0) / SAMPLES
If dt < 1e-10 (or any other accuracy condition you see fit), algorithm is finished and answer is F(t0).
IF this is the first run of the loop:
6.1. Compute a list of SAMPLES + 1 points on F (see above).
6.2. Compute a list of SAMPLES + 1 points on G.
6.3. Find which pair of points are closest to each other.
6.4. Update t0, t1, s0, s1 as seen above.
ELSE: alternatively compute a list of points on F OR a list of points on G, then find which point on F is closest to G(s0) and update t0 and t1, OR which point of G is closest to F(t0) and update s0 and s1.
Go back to step 3.

Issues
By design, these algorithms will always converge to a local minimum. However, there is no guarantee that they will converge to the best solution. In particular, the Bézier curve algorithm isn't very good at all, and in the case of two curves being close to each other at many places you may unfortunately miss the solution by a long shot.
But as I said, before you start thinking about more robust solutions, you should first experiment with those simple ones.
Answer: 1)
Translate everything to one axis,so instead of needing to calculate the length of one point to, the 'line', the 'line' is, say, the Y-Axis.
Then, uh, given a bezier curve I'd say it's up to the number of control points.
If there are three, (beginning, 'control' and end) I'd do some sort of scan (say each a couple of percent and then refine between the closest ones (with say a 'binary' approach).
More points I'd try out the couple that were closest to the (translated Y-Axis).
I am sure a math-guy can give you the exact solution (in mathematics) but if you want to find the/a solution in a video game you might be better off with a slightly ok solution as the real solution might contain several answers (I'm not even talking about processing power).
Comment: ps. 2 curves, don't even think about it (you might get anything  (at least as may as..) according to the number of control points)
Answer: Some answers from the Algorithmist blog page, which correctly finds the closest point on the given quadratic bezier curve.
Demo.
Comment: I guess he wanted us to view the demo's source: http://www.algorithmist.net/DegrafaClosestToQuad/srcview/index.html
Comment: Yep, nice demo. Where's the answer?
Answer: For the Bezier curve - straight line case, the most accurate way to find the answer is to do the following:

Transform the problem so that the straight line is always horizontal at Y=0. This is done by multiplying all the control points by an appropriate affine matrix. (I assume you are familiar with representing affine transformations of the plane with 3x3 matrices with 3 fixed entries.)
Inspect the Y coordinates of the control points. If they don't all have the same sign, there can be an intersection with the line. Compute the roots of the Y part of the Bezier curve. You can use any root finding method for polynomials, there are plenty of them in the literature. For example, google "convex hull marching" - this is a reasonably good method for the polynomials used in Bezier curves. Every root you find is a time value of an intersection with the line, where the distance is zero - your work is done.
If all Y coords have the same sign, compute the derivative of the Y part of the Bezier curve. You can ignore the X coordinates of points, since they make no difference - the target line is horizontal. Find the roots of that derivative. These are the time values at which the curve is locally closest to the line.
Explicitly evaluate the Bezier curve for all roots you have found in the previous step and report the root which gives the smallest distance from the line. You also need to check the endpoints - they might give a smaller distance than any root.


Diagram design and editing

Question: I'm new to editing drawings and need to make diagrams look realistic.im attaching an image for reference from MIT open course ware

For example the shadowing and reflections. How to add all this and what software to use
Comment: Question as laid out has no real answer.
Comment: There are literally dozens of software applications capable of this. Some better at certain aspects than others, but all capable.
Comment: Like specifically is there software for drawing and editing these images
Answer: What software to use is a hard question. To answer this we would need to know quite much about the context in which you are working and what you know!
The first question you need to answer is do you know how to draw that thing on pen and paper? Why? Well in order for you to do this you need to go through one of several options. If you do not know how to draw then any advice we can give you is totally insufficient. Sure we can say use a 3d modelling application. But that is simply glossing over the fact that in order to effectively use a 3d application for presentation graphics requires you also to know how to draw things.
Next you mention realistic. However again we are glossing over the fact that there is nothing realistic about the supplied MIT course ware illustration. Indeed no 3D application can make the kind of perspective mistakes that the image is doing. Also the image has no shadows and no reflections. All it has is simple gradient shading.
In reality you probably need several software depending on your exact needs. Personally if i would be publishing a similar image I would use probably 2 separate tools. One for the mechanical design and one for publication. Though if you know how to draw in a vector package one software may be sufficient (though not necessarily from a time cost use perspective) if you never need the mechanical design.
I would use whatever mechanical 3D solid cad i happen to have open, or whatever my client prefers and then cleanup in illustrator. But that's probably 2 months of foundational knowledge out for you to replicate.
Answer: The drawing is a part of a presentation of an idea or structure without being a manufacturing drawing. If you are a beginner you should use a simple enough 3D modelling program for this. It makes the wanted view and plausible shading with zero effort after you have drawn the model.
Your model seems easy. An experienced person gets it ready in a hour. I guess a beginner must work tutorials few days before trying this with all small parts. But the elementary 3D extrusion parts like those in my example are easy. With simple enough 3D program a beginner draws them within the same hour he started.
You can insert also annotations in 3D or export the rendered view to a 2D vector drawing program (Illustrator, Inkscape, Affinity Designer...even PowerPoint or Open Office) and insert lines and texts there.
Purhcase recommendations can here be considered as spamming, but I recommend freeware. Get DesignSpark Mechanical. (=DSM) It's a very useful subset of premium priced commercial program named Ansys SpaceClaim.
DSM is not handy when inserting complex 2D annotations (making 2D drawings is intentionally made slow in the free version), so a vector drawing program is a must. But Simple 3D geometry parts are drawn very fast (forgive the random colors):

The rectangular blocks and the tube are the simplest kind of extrusions, they took about one minute. The binding clip is taken from another drawing. Drawing it from scratch as well as all those small parts and bent wires need some serious practicing.
All parts can also be inserted in a 2D drawing program but it prevents changing the view.
Many mass produced standard parts (nuts, bolts, electric components) are available as ready to insert 3D models. Part sellers keep them available for free. People create 3D models for fun and also to earn some money. There are numerous 3D model marketplaces and free download websites.
Answer: Others have mentioned the possibility of using 3D or CAD software of some kind. However just going by the diagram itself, I see nothing here to suggest it was created using those kinds of software. In fact, quite the opposite, I see perspective errors which would not be present if 3D or CAD software had been used.  This is not to say 3D software couldn't be used, and in any case it would certainly make a better job of it as far as the perspective problems are concerned.
To me, the example you posted looks like something which was drawn using 2D vector software. There are plenty to choose from, for example Adobe Illustrator, CorelDraw, Affinity Designer, or even Inkscape (which is free). Also there is no reason you couldn't fix those perspective errors using vector software if you know how to draw in perspective properly.
I don't see anything in the diagram example which would not be achievable using any of the above software. Of course, 2D vector software still has a learning curve, but probably much less than any 3D or CAD software.
As for shadows and reflections, there are actually none present in that diagram. Almost everything is just simple filled shapes, and the shading of the PVC pipe is a simple gradient.
Here's a very rough example showing what's achievable in Inkscape (and any of the other software I listed).  Here I've fixed the perspective problem by setting up some guides and a vanishing point - a very simple kind of perspective grid.
Comment: No i mentioned the fact that its not made in 3d as it has a failed perspective, in fact if you look at the image its isometric except the table that is in perspective. Its just that if the goal is to make stuff, then you get the diagram for free by designing said stuff. So there is no need to spend 1 time unit drawing the  conceptual sketch out to publication form. Then do the actual manufacturing drawings in 0.8 timeunits. Since you can in fact do both in 1 timeunit.
Comment: @joojaa yes, I understand that totally.

Diagram design and editing


Difference between export const foo, export default foo and module.exports = foo

Question: I am really confused about:

export const foo
export default foo
module.exports = foo;

I know these are very basic but could someone please differentiate and explain these to me. I really want to understand.
Comment: Have a look at this: http://stackoverflow.com/questions/40294870/module-exports-vs-export-default-in-node-js-and-es6
Comment: I'm also wondering about `export const WHATEVER = ({ aVar }) => {   .. some code .. }`   Can't find an example of that anywhere.
Answer: Let take each of these one by one.
export const
 export const foo

This is ES6 export syntax for a named export.  You can have many named exports.  It says that you want to export the value of the variable foo and you are also declaring that symbol to be const in this module.
You can't actually use export const foo all by itself just like you can use const foo; all by itself.  Instead, you would have to assign something to it:
export const foo = 12;

The const applies only to within the module itself.  It does not affect what someone can do with the value once they've imported the value from the module on the other end because at the other end (where its imported), it's value is copied into another variable.  If that other variable is created with the import statement, then it is automatically const on the import side (you cannot assign to it) no matter what it was declared on the export side.
This could be imported as either of these:
import {foo as localFoo} from 'lib';
import {foo} from 'lib';

The first imports the foo property of the module into a localFoo named variable.
The second imports the foo property of the module into a foo named variable.

export default
export default foo

This is also ES6 syntax and says that you also want to export the value of the variable foo and you want that to be the default export value so if someone imports just the module and not any properties of the module, this is the variable they will get.  You can only have one default export per module.
Internally, the default export is really just a named export with the special name default assigned:
import localVar from 'myLib';

This will get the default export from myLib and assign it's value to a locally declared variable named localVar.  The above is a shorthand for this:
import { default as localVar } from 'lib';

So, the default export just allows you to have a shortcut import for one particular export.  The ES6 import/export syntax was designed to make the syntax as brief as possible for the default import/export.  But, for obvious reasons, there is only one default property per module.

module.exports
// inside of myModule
module.exports = foo;

This is node.js syntax for exporting the value of the variable foo and you're exporting it at the top level.  When someone uses this module:
let x = require('myModule');
console.log(x);    //  will show the value of `foo` from the previous module

This is not ES6 syntax, but is regular ES5-compatible syntax using the module.exports and require() infrastructure built into node.js.
Answer:
The export statement is used to export functions, objects or primitives from a given file (or module).

Named Exports
This is a named export in ES6 javascript
export const foo

which is imported like:
import { foo } from 'path'

Default Export
This is a default export (This can be imported using any name)
export default foo

which is imported like so:
import bar from 'path'

This is commonjs export which is used in nodejs programs.
module.exports = foo;
which is imported like:
var foo = require('path')

For more details
Answer: export const foo : exports constants (ES6)
export default foo : exports object (ES6)
Above statements are ECMA Script 2015 (aka ES6) implementation.
In an normal ES6 JS file one can export any object(variable) or constants. Pls note that you cannot change constant reference, though internal structure can be modified(weird).
In ES6 one can have multiple exports in module(script file). which can be added in calling script as
import {Obj1, Obj2} from module_file

coming to export default, One can have only one export default in module. and while importing when exact names are not defined default is been picked up.
module.exports = foo; is older implementation and it is same as export default. except it is imported with require statement instead of import
for more    refer https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export


What is the difference between `image normalization`, `contrast stretching` and `histogram equalization`?

Question: I believe that they all do the same task of distributing the frequency of pixel intensities to a bigger range, but can these terms be used interchangeably?
Answer:
I believe that they all do the same task of distributing the frequency of pixel intensities to a bigger range

They do.

but can these terms be used interchangeably?

no, they can't. because the way they increase the dynamic range of the image diffears.
All this methods do a transformation of the pixel intensity $u$ of and image into a new pixel intensity $v$ $$v = f(u) $$ in order to improve the dynamic range of the image.
for constrast stretching (that as far as I know is a more general case of image normalization) the transformation is a piecewise linear function
$$ f(u) = \begin{cases}
      \alpha u & 0 \leq u < a \\
      \beta(u - a) + v_a& a \leq u < b \\
      \gamma(u - b) + v_b & b \leq u < L
   \end{cases}$$
Where L is the total number of gray levels.
On the other hand, Histogram equalization is a more powerful technique for image enhancement that aims to give the histogram of a given image the desired uniform shape. This is achieve by the transformation
$$v_{aux} = F_u(u) = \sum_{i=0}^u p_u(i) $$
$$v = int\left( \frac{v_{aux} - v_{aux_{min}}}{1 - v_{aux_{min}}} (L-1) + 0.5 \right) $$
where $p_u(i) $ is the normalized value of the histogram at the  grey level $i$


Differencing in a simple OLS regression

Question: I am attempting to do a simple OLS regression on time series data from 1990 to 2019, and there a trends in my variables GDP capita (dependent variable), oil prices etc which I am able to difference. I am not able to difference variables such as inflation as they are already stationary at level as demonstrated on Eviews. Is this acceptable in a model to have differenced variables and variables stationary and why? To offer context I am using the log of gdp per capita as my dependent variables with oil price as my main independent along with others such as net exports and inflation to calculate the impact of oil price on a net exporting country. I am not able to a VAR analysis as I have not been taught this as of this time. Any further help would be help that you assume would be helpful would be gratefully appreciated.
Comment: You can't trust automated tests of stationarity, i.e. eViews. This is because the test is calculated on the univariate time series when in fact there are cross correlations that are not controlled for. Even if a time-series is not stationary, differencing won't necessarily remove the autoregressive effect. GDP should be inflation adjusted because that is the standard analysis of this kind of output. Variograms of residuals from OLS models should be compared to determine AR-1 autocorrelation, and fits for lagged effects of exposures should be considered.
Answer: (hi, im noob but
"Is this acceptable in a model to have differenced variables and variables stationary and why"
(for me, yes, because :

ols requires stationarity, just because of mathematics inside of it
like "constant mean"
if inflation is stationary its ok
if another vector (oil) is not stationary, you use diff and when its stationary its ok

as school task, i think you simple can answer ... ols requires all data (vectors) to be stationary
for example data 1 2 3 4 5 have trend and nonconstant mean ...so ols calculate this vector very bad ... but when we diff at lag 1, .. intercept is 1 and ar(1)=0 and model fit data like 100%

Differencing in a simple OLS regression


DC Resistance of Cat5e Cable and Type 2 PoE

Question: I see that the PoE Type 2 standard assumes a maximum loop resistance of 12.5 Ω/100 m, but cat 5e is specified to have maximum loop resistance of 18.8/100 m Ω. Does this mean that PoE type 2 is not guaranteed to work over the full 100 m Ethernet range supported by Cat 5e?
Comment: You can always be less then the maximum =-D (and more then the minimum).
Comment: What this means is that worst case scenario, you can have a compliant 5e cable that is not POE compliant, it will likely still work, but it is something to be  aware of. Realistically you will have cables that don't hit either maximum.
Comment: My assumption is that the type 2 standard really does not worst-case at 100 m with cat 5e cable. I am just wondering if anyone else has made this observation. I think most people just assume PoE works to 100 m – the same reach as Ethernet.
Comment: Whether or not PoE+ works is highly dependent on the PSE and PD. If you assume a worst-case cable (100m, 18.8Ω), a minimally compliant PSE (50V output) and a minimally compliant PD (42.5V minimum input) sourcing maximum current, then no, it won't work. But good cable will be lower resistance, a well-designed PSE will increase the voltage at larger currents, and a well designed PD will be able to tolerate a _much_ lower input voltage.
Comment: Everything I can see agrees with your statement. It appears that the type 2, 30 W standard is not guaranteed to work out to 100 m. Even Cat6, which used 23 AWG wire, is not guaranteed to work at 100 m – though it will get very close.
Answer: The answer is POE is a regulated power bus, the cable will burn up power but the systems should compensate for several reasons.
The POE system can source more power on the source than the device needs. It depends on the class of device, for a class 2 device 0.51W has been reserved for the "cable" at the worst case of 44V using the power equation P=I*V the current from the source would be ~160mA. The cable has only been allotted 0.51W of power to burn, so we can use another cable to find the max resistance allowed under spec, keep in mind that you have to account for both the resistance of the cable to and from the device. P=I^2*R can be rearranged to be P/I^2 = R where P=0.51W and I = 0.160A and solving for R get you 19.921 Ohms (for the total resistance of the cable). So it looks like the engineers who wrote the POE spec did their homework and added margin even for the worst case.
Thats a worst case figure, the device will usually have some margin in it (A good engineer if they needed 6.3W would probably jump to a class 2 device.
The PSE's can also source more voltage, they are required to source 44V but probably have the ability source more depending on the supply.
Don't go with cheap equipment though or you might get devices that have no margin or aren't up to the spec.
POE Explained is a great resource. I'll quote it

Note also that these figures are upper limits to power. Power cannot be "forced" down the cable – a
  surprisingly common misconception. The PD simply presents a load to the cable and draws as much
  current as it needs. Most PoE-powered devices will draw a fixed level of power, so for example a 5 watt
  IP camera will advertise itself as Class 2, as it will never need more than 6.49 watts, and then draw
  enough current at its local voltage to provide the 5 watts it requires to operate.
The figures in the table are also based on the worst-case operating
  conditions for PoE. PSE voltage is nominally 48 volts, but its
  allowable range is between 44 and 57 volts: because efficiency
  increases with voltage, the losses are based on a PSE supplying the 44
  volt minimum. A worst-case value for cable resistance is also assumed,
  and this is based on a maximum length7 of light-gauge cable, with an
  allowance for connectors, patch panels, or bad wiring. 7


What is the most effective way to take notes in class?

Question: I'm a freshman in college, so I'm pretty new to the lecture style of classes where you do most of the work outside of class, and the professor discusses it and gives more information in class. Well, to start the year I took notes basically word for word, concept for concept what my professor in any given class was talking about. However, I found later throughout the year that I didn't remember concepts that the professor was conveying because I was so busy writing. What should I do in the future? What has worked well for you all?
Comment: There is no one answer.  Different people take notes best in different ways.  So, if you get a list of suggestions here, try them and see which ones work best for *you*.
Comment: I think that this question has the potential to be a very valuable addition to the site; perhaps it can be edited to be a better fit.
Comment: Do a site search on note-taking. There are several other Q&As that you might find useful.
Comment: There is a gadget, a special pen, you can buy that transcribes the lecture.  I haven't tried it.  Might be worth trying!  //  It would be helpful to know what sorts of classes you're taking.
Comment: Voting to reopen --- the purported reason for closure does not appear to be a real rule (and it is not mentioned in the linked page).  This question is clearly about study habits that are relevant to academia.
Answer: I'm a PhD candidate from Caltech and here are my tips:

If it's a Math/Stat class, you should always bring a notebook and a pen to drop down the derivations and you have to review the notes immediately after the class; You should always make sure you are not lost in the middle of this type of classes.
If it's a Bio/Chem or any class focusing on stories and concepts, you should always print out the powerpoints in advance and bring a laptop. So that you can highlight on the hardcopy and type fast on the text editor. The text editor on your laptop is very efficient when the lecturer refuses to hand out the notes. I'm still using my small netbook to take notes during seminars.
If it's a CS class focusing on the codes/syntax, you should bring your laptop and have all the tools installed before the class. You should always type in the commands as the lecturer does and save all the commands together with comments which include your own notes. Those are very precious materials to your own benefit.
Learn to use the short forms of words when typing:
with as w/
without as w/o
experiment as exp.
statistically significant as stat. sig.
Practice the ability to type without looking at the keyboard.
Always have a good sleep.

Hope these help you


Binding signal to property's slot in designer

Question: Is there a way to bind some signal not to wigget slot, but to widget's property slot in designer?
I do can connect stuff in widget's ctor or add some custom slots to my widget to proxy slot invokation, but it I do not want to make my widget know about what should be connected where or overload my widget with a number of such "dumb" slots.
It would be great to declare, say qt's property, and have possibility to bind signal to it's slot directly in designer. Is this possible?
Answer: You can indeed create connections in Designer. Just use the Signal/Slot editor in designer and select a widget in your form as the sender, select the signal, select the receiving object and the slot you want called.


Can depot storage be shared between my characters in the same server?

Question: Is it possible to share depot storage between all characters in one account and the same server? Usually, I have to trade items by parcels, but maybe there is any solution to do it simpler?
Answer: The only way I'm aware of to share items among characters on the same server without using a parcel is by buying a house and invite all your characters.
Another way without using a parcel, nor a house, is to store your items in a hidden location (e.g. underneath a tree outside the city) and quickly change character to pick them up. It helps to put your target character at the spot before hand. However, this is risky and I don't recommend it. Someone might follow you, the server could suddenly disconnect or if it is really busy, you could be put in a queue for login.
TLDR; Use a parcel for non-premium, or buy a house on a premium account.
Comment: Ohh, those two tricks are unfortunately just workarounds. I usually sending items between my characters by parcels, but I thought that maybe there exist any way to turn shared depo on. Something like in Guild Wars. There all characters was one shared chest, and we could browse all our treasures, no matter on which character we are logged in.
Comment: @TravelerVihaan I understand what you mean, but that does not exist. I double checked the list of premium features and there is no such thing. Perhaps suggest it so CipSoft? :)


Trouble parsing JSON with getBodyParams()

Question: I'm trying to use getBodyParams() to parse a JSON posted to a module controller action from an API. The incoming headers have content-type set as application/json; charset=utf-8, and I've tested to make sure there is a valid JSON string in the body. But when I try to get the retrieve the body  using getBodyParams(), I only get an empty array as a response. The documentation makes it sound like it's possible to parse JSON and other content types. Does anyone know the correct way to use getBodyParams() to parse a JSON body?
Answer: Got in touch with P&T support and got the following response back:

We don't currently support parsing JSON via getBodyParams(), however I'm looking into it and looks like Yii can be configured to support that, when the request's Content-Type header is set to application/json. We would need to enable that feature ourselves though.
In the meantime you could do:
$body = Craft::$app->request->getRawBody();
$data = craft\helpers\Json::decode($body);

Comment: Thanks for following up with them. That's helpful to know and I hope they do add this in one of the next releases.
Comment: @Udo They did mention they would be adding it to the roadmap for a future release at some point.
Answer: As of Craft 3.3, if you send a request to Craft with a Content-Type: application/json header, Request::getBodyParam('property') will work as expected, returning the property value from the JSON data in the request body.
Comment: Hey Brandon, this doesn't seem to be working for me. To be clear, I'm making a POST request to the current URL (not an action URL specifically) with the Fetch API and the body JSON includes an "action" parameter. It looks like the action is ignored and the route's HTML is returned instead.
Comment: @benface Yeah, `action` params in the body are ignored if the content-type is `application/json`, because it's likely that the `action` param wasn't actually intended for request routing in that case (GitHub webhooks send an `action` value in JSON, for example). So you will need to either route the request based on an `action` param in the query string, or define a URL rule in `config/routes.php`, etc.
Comment: Thanks Brandon, that makes sense!


Best place to store authentication tokens client side

Question: When my users are authenticated they receive an authentication token, I need to use this authentication token to authorize some asp.net WebAPI calls. To do this I need to add the token to the head of that call, so I need the token accessible from the users browser. I think that storing the token in a cookie isn't the safest way, so what is the safest way to store that token and still accessible in my javascript to make API call's?
Comment: In what way will SSL help secure a token stored on the client?
Comment: "I think that..." When the rest of the world relies on cookies for storing such tokens, maybe you should explain your thinking so we might all be better informed and have a chance of coming up with a solution which addresses your concerns?
Comment: Session cookie. Don't overthink it, these things were made for a reason.
Comment: http://ceur-ws.org/Vol-313/paper9.pdf please read this.. If your trying to implement something against best practice that is not generic. Then your will have problems later down the line supporting your client.
Comment: I think using a SSL certificates should do your job, there publications here explaining their usages and what they do: http://www.rfc-base.org/rfc-6101.html.
Answer: There are two ways you can save authentication information in the browser:

Cookies
HTML5 Web Storage

In each case, you have to trust that browsers are implemented correctly, and that Website A can't somehow access the authentication information for Website B. In that sense, both storage mechanisms are equally secure. Problems can arise in terms of how you use them though.
If you use cookies:

The browser will automatically send the authentication information with every request to the API. This can be convenient so long as you know it's happening.
You have to remember that CSRF is a thing, and deal with it.

If you use HTML5 Web Storage:

You have to write Javascript that manages exactly what authentication information is sent to the API.

A big practical difference people care about is that with cookies, you have to worry about CSRF. To handle CSRF properly, you need an additional "synchronizer token".
All-in-one web frameworks (like Grails, Rails, probably asp.net) usually provide an easy way to enable CSRF protection, and automatically add synchronizer token stuff in your UI. But if you're writing a UI using a client-side-only web framework (like AngularJS or BackboneJS), you're going to have to write some Javascript to manage the synchronizer token. So in that case you might as well just go with the HTML5 Web Storage approach and only worry about one token.
Comment: You could also split the token into two parts (see https://jcbaey.com/authentication-in-spa-reactjs-and-vuejs-the-right-way). One part in a http-only cookie, one in the local storage. That way, CSRF is not possible, and it cannot be stolen via XSS.
Comment: So is storing in LocalStorage (from Javascript) secure for a JWT token?
Answer: The best way to protect your access token is to not store it client-side at all.
How does that work? Well at the point of generating the access token, generate some other cryptographically secure PRNG (which you map to the access token on the server), map this to the users session ID and return this to the client instead.
This will reduce the attack area because what you are now returning is a token tied to a session, and both would be required in order to authorise the token. When the session expires so does the token, naturally, and the user would be forced to re-authenticate thus generating a new access token.
It's still not 100% secure, however, you need to weigh up the possibility of something like that happening within a users session. Based on that, you can then tweak your session/token expiry times to suit, although you also need to be wary of usability - you don't want to be expiring sessions after 5 minutes as having to log back in constantly can be tedious (or maybe you can, depends on the type of application).
Comment: I don't understand the distinction between a public and private token. In OAuth a token is a token. If you can use it to make a request to WebAPI then what protection are you offering here? Are you assuming there is some information in the token that needs to be protected? If you are using Katana's OAuth provider, it handles that by encrypting the claims that make up the token.
Comment: Isn't an access token just a cryptographically secure randomness, though?
Comment: @LazarLjubenović well that all depends on _how_ that token is generated, when using services like OAuth etc. then yes you can pretty much guarentee the token coming back is safe to be stored on the client (to an extent).
Comment: Thanks for your awnser, but I need to include the token in the header of my AJAX API call so I need the full token accessible in my javascript.
Comment: @jfamvg I'm not suggesting you don't store *a* token on the client, I'm saying don't store the *private* access token there. Generate a public token and send that instead.
Comment: I have to send the literal token to the WebAPI, so I need to make an additional call to the server to get the token form the private token to send that to my WebAPI.
Comment: @EdGreaves was a while ago now but based on the question, the assumption was the user had a "sensitive" token that they didn't feel comfortable storing on the client. My suggestion was simply don't store the token client-side at all if that's the case, store what would be effectively a public key that could be mapped to a private one on the server. If the public key was ever compromised there would be no concern about internal data being leaked. You still of course have the issue that the key could be used for malicious purposes but that's a whole different issue.
Comment: @James Isn't that just a session then? What's the point of storing the token on the server and having some key / ID on the client side to reference it?
Answer: ARMOR is designed specifically to meet this requirement. The Anti-forgery token can be stored anywhere on the UI that you see fit. The library comes equipped with a custom JavaScript component that extracts the token from the UI and automatically includes it in AJAX headers.
Here is a tutorial on the subject, and here is the GitHub repo.
Answer: I'd store the token in a cookie with the following three flags:
1. Secure: transmit over https
2. HttpOnly: client-side JS cannot read it (XSS protection)
3. SameSite (either Lax or Strict): CSRF protection
In this way you are immune to XSS and CSRF.
You only need to be careful about SameSite, as it is relatively new and only got recently supported by the 4 major browsers (Chrome, FF, Safari, Edge)
see: https://caniuse.com/#feat=same-site-cookie-attribute
For more info regarding cookie hardening see
https://odino.org/security-hardening-http-cookies/
Answer: Alex's blog must be informative.

A server dies every time someone implements OAuth in a single page is
  web app. Stop the genocide! Use a server side proxy! Act now!

https://github.com/alexbilbie/alexbilbie.github.com/blob/master/_posts/2014-11-11-oauth-and-javascript.md
Comment: The proposed solution in that article seems unhelpful. Assuming the attacker has access to a user's client state (tokens, cookies, etc.) then the attacker can simply send the same request to the proxy server: `GET /ajax/resource/123 HTTP/1.1  Cookie:   Host: example.com`. If he means "use cookies instead of local storage", he should say so more clearly.
Comment: That article does not make sense. How will the proposed proxy server differentiate between the "real user" and the "attacker"? All http requests can be faked. CSRF just needs one-extra http call to obtain csrf token. Only solution to author's problem can be captcha and rate-limiting. Please explain if I am wrong.
Answer: You need to send the token to server in every requset. So it doesn't matter you store it in cookie or html 5 storage. Both are secure storages and eveyone who has access the client machine has access to the token too anyway.
But I recommend do not use the submitted token in cookie on your server to prevent CSRF attack. I think it is good idea to manually include the token in every request you make whenever required.
Using cookie also makes the request header bigger which is not appropriate.
Comment: This is conflicting.  How can you include a token in every request and at the same time not include it in the `Cookie:` HTTP header?  Well, you could make your own `X-Something:` header, but that is probably worse since you need to maintain the code for the storage of the content of the header.
Comment: You are right grochmal. It is possible for my web apps as I always just invoke api call through ajax request. So my method can not be implemented in other senarios.


Why can't I create nodes on EC2 default network with OpsCenter 5.2.1?

Question: I've had to update our DataStax OpsCenter service from 5.1.3 to 5.2.1 because when I tried to add a new node to our Cassandra Cluster (DSE 4.6.6 on Amazon EC2) it said that "No nodes were available to retrieve a configuration from."
Updating to 5.2.1 fixed that issue, but it created a new one; now the VPC ID doesn't allow me to create nodes on the EC2 default network, it's not shown entirely, it only allows me to choose one of the 2 VPC's we already have.
It seems that they've added VPC support on 5.2.0...

Support for AWS VPC when creating clusters/nodes in the EC2 Cloud.
  (OPSC-3429)
  http://docs.datastax.com/en/opscenter/5.2/opsc/release_notes/opscReleaseNotes520.html

It shouldn't be mandatory, since on the previous versions we had to create our cluster without a VPC, but the "Add node" documentation is not promising...

A list of current VPC IDs in the region in which the current OpsCenter instance is built. Both the VPC ID and the network range are displayed. The AWS default VPC ID is also indicated. The VPC ID list is prepopulated after entering your EC2 credentials. An AWS VPC (Amazon Web Services Virtual Private Cloud) holds one contiguous network range that can be subdivided into subnets.
  http://docs.datastax.com/en/opscenter/5.2//opsc/online_help/opscAddNodeCloudCluster.html

I need to create nodes on the default EC2 network, since the other nodes are already there and migrating to VPC is not an option for us right now (perhaps in a not-so-near future we'll have time to do so).

Is this a bug on OpsCenter 5.2.1?
Something that I need to update on our settings?
Is there a workaround to create the server in the old-way? (ie, downgrade and fix the configuration node error somehow)
Answer: This is a duplicate of a StackOverflow post which has been answered here: https://stackoverflow.com/questions/32704753/why-opscenter-doesnt-allow-me-create-nodes-on-the-default-ec2-network-anymore


What does it mean for a function to be a solution of a differential equation?

Question: What does it mean for a function to be a solution of a differential equation?  I think I understand, but I still don't have a simple or intuitive understanding.
Comment: What does it mean for a number to be a solution of an equation?
Comment: Not quite.  An equation is a statement about numbers involving an unknown.  A number solves an equation if, when substituted for the unknown, it makes the statement true.  Likewise, a differential equation is a statement about functions involving an unknown function.  A function solves a differential equation if, when substituted, the statement is true.
Comment: A number is a solution when it fits within the range of answers that the function generates.  For differential equations an equation is a solution when the equation is created satisfies the derivative's range.
Comment: Simple? If you "plug in" the function to the differential equation and it gives an equality, then it's a solution!
Answer: Solving $x+1=3$ means finding a value for $x$ that satisfies the equation $x+1=3$. In this case, $x=2$ does the job because $2+1=3$.
Now, given a differential equation such as:
$\frac{dy}{dx}= 2x$            ..........(1)
a solution to this equation is a function (call it $y(x)$). Of course not any function will do. The correct function must satisfy the equation we have in (1) above.
for this particular case, y(x) can be equal to $x^2$.
Why? Because the derivative of $x^2$ with respect to $x$ is $\frac{dy}{dx}= 2x$ which is what we have in our equation.
But wait, what about $y(x)=x^2$+5?
In fact, this is another solution. As you can see, in this case we end up with many solutions all of the form:
$y(x)=x^2+k$
where k is a constant. This is because, all of such functions satisfy our differential equation.
Comment: I guess the solution must be continuous otherwise the differential equation could not have existed in the first place.
Comment: Is it necessary that solution of differential equations should be continuous ( differentiable indeed) everywhere in the given domain?
Answer: Suppose that $\Omega \subset \mathbb{R}^{n+1}$ and that you have some function $F: \Omega \to \mathbb{R}$. Then $F$ defines the differential equation
$$F(x, y, y', ..., y^{(n-1)}) = 0$$
A solution to this differential equation is a function $y: (a,b) \to \mathbb{R}$ defined on some open interval (which could be all of $\mathbb{R}$) such that
$$(x, y(x), y'(x), ..., y^{(n-1)}(x)) \in \Omega$$
for all $x \in (a,b)$ and
$$F(x, y(x), y'(x), ..., y^{(n-1)}(x)) = 0$$
for all $x \in (a,b)$. Since every ordinary differential equation can be written in such a way this defines the notion of solution unambiguously. Intuitively, you can think of this as "$F$ being $0$ on the graph of $y$ and its derivatives." In practice you usually add some requirements on $F$ and $\Omega$, for example it is usual to require that $\Omega$ is a region, and that $F$ is continuous and invertible around $0$.
To give an example, if you have the equation
$$y''(x) = 2x^3y(x) + y'(x)^2$$
then you can take
$$F(x_1, x_2, x_3, x_4) = 2x_1^3x_2 + x_3^2 - x_4$$
Answer: When you write an algebraic equation you are trying to generalise a calculation for say. In a way you are saying what will be the end result if you give certain input or vice-versa.
Similarly when you write a function you are generalising the notion of the end result itself. After defining a function you can opt for any result your wish and find the input required to get that desired result.
In the same way when you define a differential equation you are actually trying to emphasis that in what way the rate of change of a function and its value will merge together to give the result. This kind of approach is useful in study of complex systems where the rate of changes can be measured with time and which helps in understanding the nature of system mathematically.


Select every other face loop

Question: How can I select every other edge loop. In this example its not too bad to do it manually but it other cases it might be. How can I easily select alternating face loops?
Comment: Related: http://blender.stackexchange.com/q/11038/599
Comment: Select Loops > Edge Rings.
Checker deselect
Answer: Every nth face loop:

Switch to edge select mode (CtrlTab> Edge)

Select an edge loop (AltRMB) going in the direction you want the edge ring selection to go.

Checker deselect (3D view > Header > checker deselect) the edge ring (you can use the F6 menu to set the number of edges to skip before deselecting one)

Select another edge loop (AltShiftRMB) in the direction you want the edge loops the go.

Press Edge ring in 3D view > Header > Edge Ring.

Note that when using checker deselect numbers > 2, you might get extra edge loops. Switch to face select mode afterwards to get rid of them.

Every nth edge loop:
The original text of the question asked about edge loops, yet the image was of face loops. Here's a technique to select every other edge loop.
Note if you are using a version of blender newer than this commit (2.71), then you can skip to step 4.

In vertex select mode (CtrlTab), select two edge loops one edge loop apart (AltShiftRMB), that are perpendicular to the direction you want. Then select a single vertex in between them (ShiftRMB). (This is required because Checker deselect only affects selected geometry connected to the active element. i.e you need one connected selection).

Use checker deselect (3D view > Header > checker deselect), then press F6 to edit the N in nth if you want. If you see that the wrong set of edges (the ones you want to remain deselected) are being kept by the selection, change the Offset value.

Still in Vertex Mode, select the edge loop (AltShiftRMB) in between the original two edge loops.

Switch to edge select mode (CtrlTab). You should see parts of the loops you want selected, plus one crossing loop you don't want.  If the wrong parts are selected, back up to step 2.

(Versions prior to 2.71: skip this step.)
(2.71+): Select an edge ring with CtrlAltRMB, then run checker deselect. (Thanks to ideasman42 for making checker deselect work with edges).
(2.79): Select the edge ring (perpendicular to the loops you want), but leave it selected.

Press Edge Loop in 3D view > Header > Select.
(2.79): Also deselect the unwanted perpendicular edge ring.
Comment: There is an option for this nowadays built-in: select all faces, then do from menu Select -> Checker Deselect . from there you can enter an amount too
Comment: I was trying to do a similar thing but with flat surface (removing every second face to make a fence). This answer was difficult to understand because it was long and Ctrl+Tab did not show Edge in Blender 2.81a. But using this as a hint, I could achieve it. I just selected all faces, then "Select -> Checker Deselect" on the menu in the toolbar.
Answer: This is not working in 2.93.8, but I found a video with an even easier answer.  (Did not test on 2.79b.)
https://www.youtube.com/watch?v=yCAWAOfFqDg
1: In Edge Select Mode: Select one Edge only (not an Edge Loop) that is parallel to the loops you want to select, then select the next edge (the other side of the quad).
2: Select: Edge Ring to select all the edges parallel to the ones you want, in one segment of the crossing loops.  (Note: depending on your geometry, you could just Box or Circle select all the edges in one ring in Wireframe mode.)
3: Select: Checker Deselect.  Set it to how many you want to select/deselect, and set the offset until the segments of the loops you want are selected.  You will have one segment of each edge loop.
4: Select: Edge Loops.  Boom, done.  Your single segments will be extended into their entire loops.
Thank to Sneaky Kitty Game Dev!
Answer: I don't think there's a direct tool to do this.I've been playing with all sorts of methods to try and get the effect you want and only one thing has worked, and it doesn't seem like it should.
If you can end up selecting all the vertical edge loops, with all the horizontal edge loops deselected (I used edge ring select for this (ctrl+alt+r-click), but it does mean you're making as many selections as you have horizontal divisions, so a quicker way to do that would help), then you perform a "Select Loop Inner-Region", it should, if it behaves the same as my 2.68 install, actually leave you with alternate face loops selected as in your screenshot.
Bit of a hack perhaps, but there it is.
Comment: If you first select an edge *loop* with Alt+RMB, then press edge *Ring* in *Header > Select*, then you get every edge going in one direction selected in just two steps. Unfortunately, *select loop inner-region* doesn't seem very reliable for me.. Using the torus example, along the major radius it does fine, but along the minor radius it select occasional double loops.
Answer: In 2.70a:
Change to polygon mode
Press Alt + Right mouse button to select loop (or left if you have changed defaults). Where you click on the polygon determines which loop is selected. You want to click in the upper half of a polygon near the top edge in the middle
For subsequent loops also hold down the Sift key while you Alt + click to add to the current selection
Comment: I think the OP wants an automated way of doing this.

Select every other face loop


Evangelion Thrice Upon a Time do people still remember what happened? Is the world rebuilt upon the old ruins?

Question: In the end the choker still exists. That looks more like a bomb not a necklace. I want to know for sure if people who are back still remember what has happened before the Impacts and EVA, or if the new world is built upon existing ruins of the old one. It seems the Human Instrumentality Project only changes human and souls, not the physical structures of the world like buildings or streets or cars or trains.
Answer: From what I have been able to piece together from this series, is that it is highly convoluted.
[Spoiler Warning: I have not edited in spoiler captions, because that would basically make this entire answer a spoiler.]

Firstly I'll address the choker, as that is what your question focusses on. The choker is a symbol that represents a link to the universe of Evangelion. Why is it still there at the end? Well, let's get into it...
The Time Loop Exists
The one thing that we can confirm is that the "time loop" exists. This has been a long running theory that has had some support over the years, from small aspects; i.e. the beginning of Evangelion Neon Genesis, and the Rebuild series are exactly the same, apart rom the fact that the sea is red; a very distinct difference. In the original series, the only area of ocean that was red was the north pole where the Second Impact occurred whereas in the End of Evangelion, the entire world is destroyed, and by extension the entire ocean is turned red. This is then shown in the beginning of the Rebuild.
There are different Characters/Clones except Shinji
This is where things get very confused. The two characters I will focus on are Asuka, and Kaworu.
Towards the end of the movie, they hint that Eva pilots are all clones. The Asuka in the Rebuild is a different iteration of Asuka that was left on the beach at the End of Evangelion. This is point out by a small but very distinct detail about the two Asukas: on her Plug suit, Asuka Langley Sorhyu has little black rectangles on the collar, whereas Asuka Shikinami Langley has diamond shapes in the same place.

Shikinami Langley, toward the end of the movie suggests an awareness that she is a clone, but nothing is suggested as to why there is a need for clones. One might say that it could simply be due to the highly complex synching between a pilot and its Eva, so in the case that one Pilot dies, a clone can replace them. This is exhibited entirely through Rei in both series; but it is also suggested that Rei's cloning is entirely different to the rest of the Pilots.
One suggestion is that the cloning is a "backup plan" in case the events of the Human Instrumentality Project go awry, and the events need to be done over. However, it is not entirely clear if, even though she is aware that she is a clone, that she is aware of the Loop itself.
Kaworu on the other hand has one very distinct line:

"Now the promised time has come Ikari Shinji-kun. This time, I'll definitely… make you happy."

If anything, this alone shows an awareness of previous events. However, being the Incarnation of Adam (there are mentions of him being the First, and Last Angel in relevance to his interaction with the Loop) as well as a mention of him putting his name with Shinji's when he wrote the Dead Sea Scrolls - implying some kind of singular event involving the two. Additionally, during the montage of Shinji interacting with all the others in the series (Asuka on the beach, Rei trapped in the spirit of Unit 01, etc.), Kaworu shows the casket(s) he woke up in, showing that he is the only one to wake up in them - each one contains him, to be woken up in each Time Loop; seemingly indefinitely, until the loop is broken.
The reason that Shinji is not a clone, is because he is aware of everything that has happened up until this point. The most prominent example being Asuka, left on the beach from the End of Evangelion. That said; the events of Evangelion are very likely something that he made up in his own head.
Evangelion doesn't exist
The common theme that Evangelion revolves around is Shinji, and his relationship with his Father, after the loss of his mother; coming to terms with his grief, and dealing with it in several ways. The final episodes of the Original Anime show a healthy outcome (Shinji realises that his mental state has clouded and poisoned his beliefs that he is a "worthy human being"), the End of Evangelion shows a very unhealthy outcome (he succumbs to the pressure and believes that he is a victim that no one cares about), and the Rebuild series has a very different outcome again (that he needs to realise the cause of his issues, i.e. his relationship with his father, which was caused by the loss of his mother tearing them apart and making him feel worthless).
At the end of 3.0+1.0, Shinji removes all evidence of Evangelion from the world, and the scene changes to a slightly older Shinji, sitting at the bus stop. Rei, Kaworu and Asuka sitting on the opposite platform. This suggests two things:

Erasing Evangelion removes all links to the previous adventures. Everything that tie the characters together is removed, leaving them simply as classmates; if that.
Evangelion was actually only ever in Shinji's head; and Asuka, Rei, Kaworu, etc were always a part of his life, but played very different roles in his real life. Shinji's inclusion of them in the Evangelion adventure could be based in reality or simply fantasy.

Evangelion is an expression of Hideaki Anno's dealing with Depression
To focus on the idea that Evangelion is a creation of Shinji's mind, as an escape from reality to deal with his issues, this is very much what Hideaki Anno did with the series. Characters in the series are based on those in his own life. Even so far as to express his own developments in to the three endings of the series. The first being his own overcoming of his depression, the second being the effects of the retaliation he recieved for said ending, and the third potentially being the a new way that he has come to terms with his issues.
This is why (I believe) the end of the movie pans out into a live action shot (and, correct me if I'm wrong, why the original cuts had the dark live-action intros), as well as the seemingly "real" Rei that emerges from the event horizon of the Final Impact. This is where the imaginary collides with the real, and when Shinji and Gendo enter the Anti-Universe, their fights start to destroy the "sets". Walls are pushed away, lights are knocked over, building are pushed aside and tumble like nothing more than cardboard boxes. The metaphors for the fake scenery are actually showing that the "illusion" or the "imaginary world" of Evangelion is beginning to come apart.
How Evangelion and Director Hideaki Anno Changed Anime Forever
Evangelion Iceberg Explained: Thrice Upon an Iceberg
Mari is the catalyst that breaks the Loop
The only outstanding character to all of this, and potentially the most influential and most confusing is Mari Makinami Illustrious. Mari is the outlier to the rest of the Evangelion iterations, only being seen as a coworker to Shinji's parents (apparently being the one that introduced Yui and Gendo in the world of Evangelion), therefore implying she is the same age as them; but at the end of the movie, she seems to be the same age as Shinji. In addition to this, she seems to have in intimate knowledge of everything to do with NERV, WILLE and SEELE, shown by her interactions with Fuyutsuki.
At this point, I can only speculate as to what her role is in the story. It might be that after several iterations through the story in Shinji's head, he met with Mari, who has had a very different, and very impactful influence on him, allowing him to finally move on from the events he was dealing with. It is possible that she was included in the adventures in Shinji's "Evangelion stories", and had a proper understanding of what they meant, hence her "interaction" with the DSS Choker, as well as the line with the (odd) follow-up of smelling his neck

"The smell of an adult."

The only supporting evidence I have of this is the first interaction Shinji has with Mari, when she crashes into him on the roof of the school (at this point in time I don't know if this is actually in the movie or not)

In another storyboard, Mari would have pushed up her glasses in the same manner as Gendo.

Source
This apparent behaviour could be a trigger for Shinji to connect with Mari psychologically, in the same way that he is constantly attempting to seek his father's approval, but then developing a much healthier relationship with Mari, than he does with his father.

So with all that taken into account, and with the fact that this extremely deadly and dangerous collar is just taken off and put in her handbag and disregarded as something harmless, it's very likely that it isn't actually anything more than an anchor for Shinji and this world he made up in order to deal with his issues. This is a fairly common thing in real life, where people attach their trauma or coping mechanisms to an object. Sometimes when people are stressed, or anxious, or depressed, they need this item in order to deal with their issues.
Without more information from the Director/Writers however, this kind of speculation is most likely the best we're going to get.
Comment: This doesn't explain anything why choker still exists
Comment: Sorry, I forgot to add that. I've edited it in now.
Comment: There is too much copy and paste going on. It turned out I just need to master Japanese then watch the anime in Japanese. All the information is inside the anime itself not outsourced cannon anywhere else. The short answer is they've gone through circles and that's a different Shinji wears just a necklace.
Comment: Ultimately yes, but that would make for a very poor quality answer.


Top View,Front View,Left view and right view help

Question: I have to draw the front,top,left and right views of a given solid objects without scaling them i.e freehand. I am much beginner in this drawings. So I am getting no idea of how the given solid object is break into top,left,right and front view. So kindly please explain all the basics of how to break the figure into parts of the engineering drawing with few examples (without scaling).
Answer: When you have an object to draw, you must follow some simple rules to explain your drawing for anyone to understand it easily.
There are 2 example explanatory pictures below.
Example 1

Example 2

Hope these helps!
Comment: It's worth mentioning the Back/Front and Left/Right views of Example 2 are switched. Back/Front should be the "equilateral triangles", while Left/Right should be the right triangles.
Comment: Yes I noticed now. Should I remove the Example 2? Thanks for help!
Comment: And how to draw those drawing which a square base pyramid and a triangle base pyramid at top
Comment: We call these as Technical Drawings. You can use one of the CAD programs. Also you must include the dimensions.
Comment: somewhere i see that we have to use dotted lines, and i know that the dotted lines are for hidden  objects, but i actually don't get them. So  please can you explain the examples of objects with dotted lines in front or side views. Thanks!
Comment: It might be worth noting that there are 2 ways to layoit the views. The three rotation way and the one rotation way.
Answer: Speaking in Engineering Drawing terms, there are two methods to generate projections of an object. First angle projections and Third-angle projections.These projections are developed based on assuming how the object is conceptually viewed in a quadrant system.

In First Angle Projection we place our object in the First Quadrant
  (see above figure). This means that the Vertical Plane is behind the
  object and the Horizontal Plane is underneath the object.
In Third Angle Projection the Object is placed in the Third Quadrant.
  This means that the Vertical Plane is in front of the object and the
  Horizontal Plane is above the object.
These changes in the position of the views are the only difference
  between projection methods.

(Source)

So basically, visualize an object being viewed from these different planes. The  Frontal plane gives you the side view. Horizontal plane gives you the top or bottom views (based on the angle of projection).
And visualization is the key to becoming good in CAD drawings, 3D modelling etc. It takes a bit of practice and imagination; but it's easy to get the hang of :)
Answer: Look at the object in front of you, then the face you see is the front view and if you moved your position to the left side, again what you see is the left view etc.
Then there are two systems : do you draw what you see after (behind) the object or between you and the object but this won't change what you need at the moment.
Comment: Please could you illustrate with some example figures? Thanks!
Comment: Match my description with example 1 in the other answer.


How does light appear from electricity?

Question: I have a question and I was just thinking that you can help me out with that. I was studying how to create simple circuit, that is involving bulb, wire and battery and came up with question, how does actually electrons produce light energy in the bulb? What I know is there is so-called the filament, a thing with great resistance, and this thing heat-up when current is flowing and it produce light, but I still don't understand how it's possible. Light energy includes photons. Electrons can emit or absorb photons. Does that mean, that they already had photons?
Comment: Photons are not conserved. They can be created by the energy of charged particles moving in electric and/or magnetic fields.
Comment: Maybe [this is what you were really asking](http://physics.stackexchange.com/questions/202284/how-do-we-see-where-do-the-photons-disappear/202333#202333)?
Comment: I think this is rather a good question. The OP is clearly new to physics and is writing (very well!) in a second language. She is wondering how the light from a bulb is connected to the electricity that produces it. This is indeed a valid concern. The main point to take on board is that there is an intermediate process - heating - that converts the energy in the electric current into something else (hot filament) and it is this that produces the light.
Answer: The bulk matter of the wire is made of metal containing a "sea" of electrons. These act as a liquid in a sense, and in particular can vibrate due to thermal motions.  For nonmetals the electrons in bulk material (e.g. mineral grains) can vibrate in ways more free than the absorbing/emitting energy level thing: the phonons can take just about any energy.
This motion of electrons emits radiation.  It is the most straightforward way to get black-body radiation, though even in cases like neutral hydrogen gas it finds a way.
Black-body radiation at some hot femperature is why incandescent lightbulbs and candle flames and electric stove burners and the surface of the sun emit light.
Answer:
What I know is there is so-called the filament, a thing with great
  resistance, and this thing heat-up when current is flowing and it
  produce light, but I still don't understand how it's possible. Light
  energy includes photons. Electrons can emit or absorb photons. Does
  that mean, that they already had photons?

Think about how the filament heats up when the current flows through it. As the electrons move along through the filament, they are constantly bumping into the atoms that make up the filament, transferring their energy to them. The energy of each impact vibrates an atom -- in other words, the current heats the atoms up.
Now, the bound electrons in the vibrating atoms may be boosted temporarily to a higher energy level when they're hit by on-coming high-energy electrons that form the electric current. After the energy is transferred to the bound electrons, they fall back to their normal levels. This happens when the electrons release the extra energy, that they had absorbed via the collision, in the form of photons.
Note that the absorbed energy may be released in other forms energy than photons depending on the material in question etc. So the electrons(ones inside the filament) did not already have photons- they were given some energy, which for the choice of material in the bulb, leads to an emission of photons when the electrons relax from that excited high-energy state.
http://home.howstuffworks.com/light-bulb1.htm
Answer: Rather than looking at an incandescent bulb, let us consider an LED (light emitting diode). In terms of building a circuit out of it, it is no different from a light bulb (at least the differences are not relevant here). The point is, that in an LED, the microscopic mechanism simply is that an excited electron relaxes to its ground state, emitting light. From your question, I understand that this is a concept you are familiar with. In contrast, a filament emits light because it is hot. The microscopic description (with electrons and atoms) is much more complicated here.
Back to your question!
Upon emission, the photon is literally created. It did not exist before.
Your intuition tells you that 'the number of photons' must be conserved. Actually, the conserved quantity you are looking for is energy. Some quantum of energy (e.g. potential or electrical, or, in the case of an LED, it's the excited energy of an electron) is converted into a quantum of radiation. This quantum of radiation is called a photon. The same energy existed before! It was just present in a different form, but still in quanta. We just don't usually give special names to it. Still, sometimes physicists talk about phonons, vibrons, magnons, etc. They all describe quanta of some energy degree of freedom.
Answer: The simplest answer is that the filament heats up and gets so hot that it glows.
As to how it heats up; the electric field forces electrons to rush around the circuit. They encounter a lot of resistance in the filament and it is this "friction" that leads to heating.
As to why hot things emit light; heat is energy and the increase in energy in the filament means that electrons can jump to higher energy levels in the atoms (excitation). When they de-excite, they emit photons.
Comment: A comment to your last statement: Phononic excitations (vibrations of the atoms in the crystal) strongly contribute to this. for instance in insulating materials, you will not manage to excite electrons except at very high temperatures (>3000°C, which I agree, is reached in a filament).
Comment: So can we say that some of the kinetic energy of the electrons is transferred to the filament while the other remains on the circuit as current?

How does light appear from electricity?


Help me sex this Endler's livebearer

Question:
It looks like a female (no colors and round belly), but it seems to have a gonopodium organ, a dot on the tail-fin that other females lack and the gravid spots near its vent are fainter and higher up than other females.
Males occasionally display in front of it but they chase after it less than after other females.
Here's another picture:
Comment: i did not answer this question when it was first posted,because no answer will be correct.it is probably both genders at the same time and is most likely sterile,the reason for this happening is probably a result of a hormone imbalance during development,this can be caused by chemicals in the environment or by cancer in the mother fish(the same thing can happen in mamals too humans included).
Answer: The best way to discern male from female is by looking carefully for that gonopodium you spotted. That is a male sex organ and you'll not find it on a female.
In short, that is a male fish.
Late reply, I know. Hopefully he's still happily living in your tank and this helps somewhat.
Comment: Welcome to pets.SE! Would you please add some kind of source? Did you have one of them yourself? Do you have a website or book or paper where one could read more about this in fish?
Comment: @BlakeCass personal experience is also acceptable.

Help me sex this Endler's livebearer