Different pedals/effects for low strings/notes than high

Question: I'd like to put different effects on my low strings and high strings (or low notes and high notes), e.g. an octavizer and delay on the bass notes and vibrato and reverb on the treble. Is there a simple way to achieve this?
Could a low/high pass filtering solution work, or are the higher harmonics of the low notes too important? The only other solutions I can think of are either going through MIDI, which would change the sound too much, or using a custom guitar with two sets of pickups, which would be way too much effort.
Comment: Interesting idea. Most pups are wired so that all strings are accomodated in one unit. It would be expensive to have some 'custom wired', although if split, they could still be switcheed to work as standard. Or, mounting two pups so that each was under three strings - odd looking though!
Comment: I seem to recall somewhere seeing  a bass with 2-element pickups spaced both laterally and longitudinally such that each one only sensed two strings.
Comment: @CarlWitthoft They exist for 6-string guitar too, e.g. the "Z-coil pickups" from G&L. I assume you could rewire them, but you'd lose the noise-cancelling effect. You can buy them from G&L for $80, but they obviously aren't a simple drop-in replacement for other pickups without some DIY.
Comment: Never tried anything like this myself, so I can't expand this into an answer, but possibly the [Boss GP-10](https://www.boss.info/global/products/gp-10/) could work
Comment: What low pass & high pass filtering will do is process the upper harmonics lf the low strings along with the high strings. That said, people have done exactly that with guitar parts in the past.
Comment: Look up the "A Little Thunder" pickups that Mary Spender uses. They allow her to switch on a bass setting for the lowest 2 strings. https://www.alittlethunder.com/
Answer:
Could a low/high pass filtering solution work, or are the higher harmonics of the low notes too important?

It can have an interesting effect - in fact I have experimented a lot with this on bass guitar - but you are correct that the harmonics of the lower notes would be above the fundamentals of the higher notes, and so you wouldn't really get full separation of notes. Even with very low or high notes, parts of the 'noisy' initial transients will appear on both sides of the crossover filter output.
On the plus side, this technique should be easy to experiment with using a conventionally-recorded part. You can simply clone your track and pass differently-filtered versions of it through different effects. You might even be able to chop-up copies of the track in the time dimension too, to create a poor man's version of Todd Wilcox's suggestion.
One way you might get even more separation could be to load your recording into melodyne and see if you could use that to separate things out. You might even be able to achieve some effects that can't be achieved by treating things per string - e.g. you might be able to isolate runs and riffs that go across strings.

or using a custom guitar with two sets of pickups, which would be way too much effort.

This is likely to be a much more inspiring playing experience, IMO. You don't necessarily need two sets of pickups - If you google for hexaphonic pickups, polyphonic pickups, or divided pickups, you may find something that would fit in an existing guitar with only a rewiring job needed.
Comment: @luserdroog sneaky idea! But there would be a huge amount of work to do to generate harmonics accurately enough to do the phase cancellation - it's probably an easier job to just isolate the notes from the mix (I've just added a link to melodyne)
Comment: Hmm. What if you take the low-passed signal, add harmonics to it, and then use that to phase cancel the harmonics from the high frequency output signal? I wish I had the hw knowledge to just try it, sigh. ... But this much might be ok to peel off the lowest note, then a stack of these could collect several low notes and split off the highs.
Answer: I've done this before with a completely normal guitar but you won't like how I did it:
I simply learned to play the guitar part all over again, but I learned how to play the part only the bottom three strings and then only the top three strings and then I recorded two separate tracks so I could process them differently. Obviously this method can't be used live. Note that Matt Bellamy (Muse) did something like this on the recording of "Time Is Running Out".
Roland 13-pin pickup systems can do this live, but note that what's really happening in this case is you would be processing COSM modeled synthesized guitar sounds and not the actual magnetic pickup. There are also some rare "hexaphonic" pickups that do this, I think Line 6 guitars can do this. But those are all in the category of "MIDI" solutions.
I believe the Moog guitar might have done this out of the box with the magnetic pickups, but it was very expensive when in production and is no longer available, so buying one second hand would cost a mint.
Comment: You could probably do what you describe with a looper - then it could be played 'live'.
Answer: It's possible (and fairly easy) to selectively mute strings on a humbucker pickup by placing a piece of soft steel between the pole pieces serving the strings in questions.  If e.g. one mutes the upper four strings of the bridge pickup (which is what I often do), then the bridge pickup will just capture the bottom two strings.  While I just do this to get some extra brightness on the bass strings, it would be simple to wire in an extra jack and have a bass-strings-only signal which could be processed separately from an all-strings mix.  If there is adequate physical clearance, it might be possible to use a similar approach on single-coil pickups, but I would expect that for best results one would want to use "U-shaped" pieces of steel which reached around the sides of the pickup so as to provide a magnetic path most of the way from one end of the pole piece to the other.
Comment: For many single coils it is also possible to just _remove the individual magnets_ for the unwanted strings.
Answer: Filters are a good start for isolating low vs high parts of a signal, but as a observed in comments and other answers, the upper harmonics of the low notes will be in the high portion of the output.
But, we can refine this method by using phase cancellation as well. Start by taking the frequency spectrum with wide buckets to find the low note (this may be a cascade of FFTs to catch the low note). Next, we generate an envelope by adding harmonics of this note according to the expected spectra for the type of instrument (plucked string, bowed string, etc.). Then invert the signal and mix it with the input to phase cancel all of these frequencies. We can also use the envelope to control multiple band pass filters to extract the low note and (most of) its harmonic content.
A refinement would be to do the last two steps in reverse: use the generated envelope to band pass the signal to create a more accurate envelope for the phase cancellation.
In theory, this should give you two usable output signals: the low note and its harmonics, and the remaining high notes. By stacking several of these gizmos we could isolate the lowest two or three notes from a chord.
Answer: At that point, it might be easier to just split that into two parts and apply the effects separately. It could be interesting to split the signal, run it through two banded EQs configured as low-pass and high-pass filters heavily attenuated and set at the same cutoff frequency, and see what the output sounds like, but as mentioned elsewhere, the low-end channel of your signal is going to sound really odd without the harmonics that you're filtering out.


How to use MaxEnt (logistic regression) weights?

Question: I asked this question last night and Matt Krause explanation helped me a lot. (For more explanation please see my previous question). Now I have another problem. We are using RapidMiner studio and logistic regression classifier to train our model. And here is our new model and results :

weights:

I have two simple question:

What dose negative weights mean? Is it okay, or something is wrong?
How should we use this weights to predict new records? Consider that we are using logistic regression classifier. (For example a C# application to summarize news)

Edit 1
Here is RapidMiner logistic regression doc.
Logistic Regression
Comment: You should take a look at RapidMiner documentation for help with interpreting the model output. It appears that these "weights" correspond to the **coefficients** for the predictors in the model, but I can't be sure about that without looking at their documentation.
Comment: @Vishal http://docs.rapidminer.com/studio/operators/modeling/predictive/logistic_regression/logistic_regression.html  thanks
Answer:
The negative weights imply that these attributes have negative impact on the outcome, after controlling for all other attributes that are in the model. For example, all else being equal, as SimilarityToContent increases (from 0 to 1) the likelihood of the statement being true decreases. Interestingly, there's only one attribute in the model that has a positive coefficient. As SimilarityToTitle increase, the likelihood of a statement being true also increases. All other attributes lower the likelihood of true sentence.
Here's the formula that you can use to predict the probability that a sentence is true:

$$
p\ (statement=true) = 1 / (1 + exp(-z))
$$
$$
Where \ z = Constant -0.598 * SimilarityToContent - 0.113 * StopWordsEffect - 0.125 * SntcLengthEffect - 0.742 * SntcPositionEffect - 0.030 * CuePhrase + 0.022 * SimilarityToTitle
$$
Note that the attribute with a zero coefficient is excluded from this formula.
Update: Although the intercept (constant) term is not shown in the sample output in the original question, it was added in the formula above based on feedback to this answer.
Comment: thanks for your nice explanation, we balanced our dataset with Weka and smote algorithm, and relearned the model with Weka tools. now we have an intercept value , how should we include it in above formula ?
Comment: Glad you found it useful. I've updated the equation in my answer above to include the intercept (constant) term.
Answer: I am assuming the data is labeled +1 and -1 and the underlying model is linear logistic regression for classification.
It looks like 7 features are extracted from data (as listed in the "weights" table). During the training, 7 model coefficients will be learned. I assume that it is standard L2-norm regularization with some parameter set by user or set by default. The regularization parameter deserves a special discussion and will be left out of scope.
The learned model (the coefficients) are completely dependent on feature values and the labels. I am expressing my guess here.
It appears from almost all the learned model coefficients (except SimilarityToTitle and EsharePhrase) has more weight toward predicting the negative class. The only feature "SimilarityToTitle" relatively little contributes to decision in favor for the class +1. The feature "EsharePhrase" has no impact at all as it is 0.


Running Production WAMP

Question: I am building a new Windows Server 2008 R2 install to host my Joomla! 1.6 website. What are best practices of hosting a WAMP production server? What should I do for partition? A drive for logs, a drive for the OS and a drive for data? What would be the most ideal and secure setup?
Comment: Has anyone ever heard of the Uniform Server? They say it is a stack designed for production. Any thoughts on that?
Answer: The best practices are not to use it. It's best to pick tools native to your platform. If you want to run an *AMP stack, do it on Linux/Unix and install/configure the components individually, don't use a preconfigured package that's aimed at development.
The default configuration for WAMP/LAMP is extremely insecure, because it's meant to give a quick turnkey dev environment. It's not a production solution. If you really care about security, you'll install each component separately and follow the best practices for security for each product individually.
Comment: They're *all* well documented. apache.org, mysql.com, php.net, etc.
Comment: I wish. I want to run it on CentOS but its not my call.
Comment: Using a native platform is only a small part of my answer. You should still install and configure each individual component separately, even if you *must* use Windows, it's just less-than-ideal to run it on Windows.
Comment: So you're saying I should just install each component individually on Windows? That sounds feasible. Do you recommend any current/up-to-date documentation on each component?

Running Production WAMP


Oracle Instant Client installation woes - "HTTP proxy setting has incorrect value"

Question: When I run sqlplus I get the following error:
#sqlplus
Error 46 initializing SQL*Plus
HTTP proxy setting has incorrect value
SP2-1502: The HTTP proxy server specified by http_proxy is not accessible

I've just installed the oracle instant client on fedora 12 by doing the following:
I downloaded the rpms from http://www.oracle.com/technetwork/topics/linuxsoft-082809.html

oracle-instantclient11.2-basic-22.214.171.124.0-1.i386.rpm
oracle-instantclient11.2-devel-220.127.116.11.0-1.i386.rpm
oracle-instantclient11.2-jdbc-220.127.116.11.0-1.i386.rpm
oracle-instantclient11.2-odbc-18.104.22.168.0-1.i386.rpm
oracle-instantclient11.2-sqlplus-188.8.131.52.0-1.i386.rpm
oracle-instantclient11.2-tools-22.214.171.124.0-1.i386.rpm

I then installed them all using rpm
In addition I added this to my /etc/bashrc file and restarted the shell:
export ORACLE_HOME=/usr/lib/oracle/11.2/client
export LD_LIBRARY=/usr/lib/oracle/11.2/client/lib/

OS: Fedora 12, 126.96.36.199-150.fc12.i686.PAE
This is a VMWare vm - that doesn't have access to the internet.
Perhaps I be using the i686 versions?
Thanks SF
Answer: The only thing that worked for me was to set http_proxy to blank:
export http_proxy=

Then run SQL Plus
Answer: sqlplus uses the http_proxy and no_proxy environment variables to determine if proxy is used.  To bypass the proxy settings then both these values need to be unset.
unset http_proxy
unset no_proxy

or
export http_proxy=
export no_proxy=

Answer: Turns out I had set my password to the wrong value in profile.d/proxy.sh


Failed to retrieved directory listing

Question: I have set up an FTP Publishing Service on Windows Server 2008, but I cannot connect to it using FileZilla. I get this error: "Failed to retrieve directory listing".
Port 21 is open.
I also read the article which was linked here but I do not have FTP category in IIS Manager (I manage my FTP sites through IIS 6 Manager).
Comment: Are you connecting to the server from a different location or through a firewall of some kind (to include software)?
Answer: You should check this out, it might help
http://social.technet.microsoft.com/Forums/en-US/winservergen/thread/706e5104-325c-4c43-8c06-a20704569bf4
Comment: On ServerFault we prefer you to summarise the important parts of the page as well as linking to it.  Links go dead over time and it's not clear exactly which part of that page you think will help the OP.  (It's also worth noting that the question is more than a year old and should be closed as Not-A-Real-Question.)
Answer: This is just an assumption: Configure FileZilla from passive to active mode and activate the "Ask your operating system for external IP address." option. I hit this wall several times with my FTP server on CentOS.
Answer: Ask the system administrators to check also the MTU settings.
Improper MTU settings on server could cause wrong streams, if MTU is set to 1496 or some other splitting values (different from 1492 or 1500 for instance).
Comment: This answer has a lot of room for improvement.  *Why* would changing the MTU will help?  How will the OP know if the MTU settings are "wrong"?  What should the OP change the MTU to if it is wrong?  Should the MTU be changed on the client?  Are there any *other* reasons the OP could have received this error message?
Comment: Personal experience with Windows "servers". Flow fragmentation in case of wront MTU could disrupt proper FTP responses. Check that MTU is not set to 1496 or some other random values that split bytes.
Comment: Feel free to [edit more useful information into your existing answer](http://serverfault.com/posts/515766/edit).
Comment: Sorry. I fixed. I hope to provide some help.

Failed to retrieved directory listing


Why a common Trumpet is in B flat pitch ?

Question: Why is Trumpet mentioned as B flat pitch ? How it becomes suitable for C scale ?
Comment: Related: [What are the practical reasons for still having transposing instruments?](http://music.stackexchange.com/questions/7225/what-are-the-practical-reasons-for-still-having-transposing-instruments)
Answer: The first question already has an answer. The second is that one plays the notes in the key of D on the music, which come out sounding as if they belong to the C scale.


Truncating $p$-series

Question: Let $p \in \mathbb{R}$. Series of the form $$S_p = \sum_{k \in \mathbb{N^*}} \frac{1}{k^p}$$ converge if and only if $p > 1$. Let us define $$S_{p, n} \triangleq \sum_{k = 1}^{n} \frac{1}{k^p},$$ the truncation of the $p$-series at its $n$-th term. (It is evident that $S_{p, n} \space \xrightarrow{n\to\infty} \space S_p$.) Is there a closed expression for $S_{p, n}$, at least for some values of $p$ (integers must be easier)?
Comment: Here's a plausibility argument on why you're supposed to expect the polygamma functions (as shown in Robert's and Eric's answers) to pop up: recall the usual gamma function relation $\Gamma(n+1)=n\Gamma(n)$ and then derive from it $\log\Gamma(n+1)=\log\,n+\log\Gamma(n)$. As noted, the polygamma functions are derivatives of $\log\Gamma$, and through the identity $$\frac{\mathrm d^n}{\mathrm dz^n}\log\,z=\frac{(-1)^{n-1}(n-1)!}{z^n}$$, you'll find that a connection formula for $\psi^{(n)}(z+k)$ and $\psi^{(n)}(z)$ would necessarily involve a series of reciprocal powers.
Comment: \stackrel{n \to \infty}{\longrightarrow} should do the trick.
Comment: $\overset{n\rightarrow \infty }{\longrightarrow }$ can be obtained with \overset{n\rightarrow \infty }{\longrightarrow }
Comment: I deleted an answer because I replied to a different question (closed form for $S_p$, with $p$ even or negative)
Comment: It depends on what you mean by "closed form expression." It is surprisingly difficult to give a precise definition of this.
Comment: @Theo: Thanks for the explanation.
Answer: In Maple notation, for $p \ge 2$ integer, $$S_{p,n} = \zeta(p) + \frac{(-1)^{p-1}}{(p-1)!} \Psi(p-1,n+1),$$ where $\psi(m,\space·)$ is the $m$-th polygamma function.
Comment: For completeness: if $p=1$, $$\sum_{k=1}^n k^{-1}=\gamma+\psi^{(0)}(n+1)$$ where $\gamma$ is the Euler-Mascheroni constant. (The zeta function diverges for $p=1$.) For noninteger $p$, there has been research into analytically continuing the polygamma function such that Robert's expression still makes sense. See [this](http://22.214.171.124/~vhm/papers_html/genoff.pdf) for instance.
Comment: I could be wrong, but I doubt this is what Luke had in mind when he asked for a closed form.
Answer: Yes, there is.  These are called the generalized harmonic numbers.
With polygamma function: I suggest looking at this paper, they have many interesting things.  In particular, if we define
$$
H_n(z;r)=\sum_{k=1}^n\frac{1}{(z+k-1)^r}
$$
(even more generalized) then we have for integers $p$
$$
H_n(z;p)=\frac{(-1)^{p-1}}{(p-1)!}(\psi^{(p-1)}(z+n)-\psi^{(p-1)}(z))
$$
where
$$
\psi^{(k-1)}(z)=\frac{d^k}{dx^k}\left(\log\Gamma(x)\right) \biggr|_{x=z}.
$$
This is equation (1.14) of the paper, but I think they forgot a factor of $(p-1)!$ on the denominator. Taking the case $z=1$ gives what you are looking for.
With zeta function: we can write $$H_n(r)=\sum_{k=1}^n\frac{1}{k^r}=\zeta(r)-\zeta(r,n+1),$$ where $\zeta(s,a)$ is the Hurwitz zeta function. This $\space$ really clear, but by using identities regarding $\zeta(s,a)$ we can change the identity into $\space$ previous one, and other things.
Hope that helps.
Comment: In short, the (generalized) harmonic numbers and the polygamma function are essentially the same thing (differing only by a constant); and are tightly related to Hurwitz zeta.
Comment: @J.M. That is a nice way to put it!
Comment: A tiny tip, BTW: for linking to SD, it usually makes better sense to use the DOI instead of the actual SD link; for some reason they tend to go stale quickly. In your case, `http://dx.doi.org/10.1016/S0096-3003(01)00172-2` would be a better link to the paper in your answer.
Comment: I could be wrong, but I doubt this is what Luke had in mind when he asked for a closed form.
Comment: On the other hand, Luke did not seem to complain about Eric's and Robert's answers...
Comment: @Gerry @J. M. This is closed enough for me. It's neither recursive nor kept on being a truncated sum. I voted it up.
Answer: To the best of my knowledge, there is no closed form expression for $S_{p,n}$.
EDIT: Let me amend my answer to read, to the best of my knowledge, there is no closed form expression in terms of functions familiar to, say, students of 1st-year Calculus.

Truncating $p$-series


proof a mathmatical statement

Question:
If $\,\mathrm{gcd}(a,b)=1,\;d=ac,\;$ and $\,b\mid d,\,$  then $\,b\mid c.$

For example, $45=9\times 5$ is divisible by $3$ and $\mathrm{gcd}(3,5)=1$ and $3$ divides $9$. But it is easily noticeable that it just represents the natural property of a number and its multiple.
How can I proof it with mathematical formal way i.e using any sort of notation.
Answer:
Since $\gcd{(a,b)}=1$, you can always find integers $m$ and $n$ such that $$m \cdot a + n \cdot b=1$$ From the above you have $$m \cdot (ac) + n \cdot bc =c \qquad \cdots (1)$$
Use $d= ac$ and $b \mid d$ we have $d=k_{1}b$ in the above equation to get the answer.

proof a mathmatical statement


SUMO and TraCI, multiple clients - one connection

Question: I try to access the SUMO Server from to different points, both python scripts. Until now, if i want to get data from my running SUMO, it gives me an ERROR:
"Received answer 164,0, for command 164,67,car_0"
(car_0 is a vehicle obviously). I guess it's because it can't connect to the same SUMO.
Short: one running SUMO, multiple python scripts.
Any ideas? I hope it's clear what i want to achieve :-)
Answer: There are several possibilities to achieve this. If you know in advance how many clients will connect (and have sumo 1.0 or later) you can use the multi client functionality starting the server with e.g. --num-clients 2. Please note that in this case you need to set the order and every client has to send the simulationStep command, see http://sumo.dlr.de/wiki/TraCI. If you have clients connecting dynamically, you will need to use your own proxy where a small wrapper script accepts the connections of your clients and forwards them to sumo.


bayes theorem applied

Question: I've tried to apply Bayes theorem to the following question, but I think I'm using it wrong.
2000 people take an exam and 1 person is cheating. A lie detector that is accurate 99% of the time is used to screen the candidates one by one. At some point during the screening the lie detector beeps to signal that the person is lying. What is the probability that the person was actually cheating?
$$P(A|B)=\frac{P(B|A)P(A)}{P(B)}$$
Let A = the person is cheating
Let B = lie detector correct
$$\frac{(0.99).(0.0005)}{(0.9995).(0.01)}$$
$$P(A|B)=0.04952$$
This seems incorrect, I'm not quite sure where I am going wrong.
Answer: Until you get to be very comfortable applying Bayes theorem, I suggest you fill out this table.
$\begin {array}{cc|c}
\text {True Positive} & \text {False Positive} & \text {Measured Positives}\\
\text {False Negative} & \text {True Negative} & \text {Measured Negatives}\\ \text {Total Positive} & \text{Total Negative} & \text {Total} \end{array}$
Or in this case
$\begin {array}{cc|c}
\text {Cheater and Detected} & \text {Honest and Detected} & \text {Total Detected}\\
\text {Cheater and Not Detected} & \text {Honest and Not Detected} & \text {Total Not Detected}\\ \text {Cheater} & \text{Honest} & \text {Total} \end{array}$
Fill in what you know from the given information.
$\begin {array}{cc|c}
\text {Cheater and Detected} & \text {Honest and Detected} & \text {Total Detected}\\
\text {Cheater and Not Detected} & \text {Honest and Not Detected} & \text {Total Not Detected}\\ 1 & 1999& 2000 \end{array}$
Then use that the test is 99% accurate.
$\begin {array}{cc|c}
0.99 & 19.99 & 20.98\\
0.01 & 1979.01 & 1979.02\\
1 & 1999& 2000 \end{array}$
If you are detected, there is a $\frac {19.99}{20.98}$ chance that you are innocent.
Answer: I think you need to modify your denominator.  I believe the correct formulation is:
$P\left(\text{cheated}|\text{detected}\right)=\frac{P\left(\text{detected}|\text{cheated}\right)P\left(\text{cheated}\right)}{P\left(\text{detected}|\text{cheated}\right)P\left(\text{cheated}\right)+P\left(\text{detected}|\text{not cheated}\right)P\left(\text{not cheated}\right)}$
I believe you only computed the second term in the denominator.  You need to add the first term (which is the same as the numerator in this case).
I hope this helps.

bayes theorem applied


Add Form frields to View

Question: I'd like to generate a view of Employee names, but I'd like to embed it inside a form as well as add checkboxes next to each Employee name. I tried to use Rewrite the output of this field but my <input/> tag is getting stripped out when being displayed.
How would you recommend I do this?
Comment: VBO can be help full.
Comment: Yes, this appears to be close, but I don't want a drop down with multiple actions possible, I just want the checkboxes and the submit button. I don't see any way in VBO to do that. Am I missing something?
Answer: I ended up using Views Bulk Operations to generate the page content and then I added some javascript and css to hide certain things and to also add some extra fields, etc.
It was a total hack, but it got me through on a time crunch.
Comment: would you comment on how you added extra fields? I'm having a similar problem.
Answer: Maybe you would have benefitted from the Editable Fields module (http://drupal.org/project/editablefields).
You can add the checkbox as a boolean field to the employee, I suppose, and then in the view choose "Editable" as Formatter. Works for more sophisticated stuff as Text fields etc. as well.

Add Form frields to View


Create nested list from class C#

Question: I want create permission nested list like a treeView and create a class like this which has two subclass:
 public class Stuff
    {
        public const string _ = "Stuff.";
        public class Invoice
        {
            public const string __ = _ + "Invoice.";
            public const string Add = __ + "Add";
            public const string Edit = __ + "Edit";

        }
        public class Warehouse
        {
            public const string __ = _ + "Warehouse.";
            public const string List = __ + "List";
        }
    }

and now want something like this(TreeView or just an output doesn't matter):
Stuff
  |Invoice
      -Add
      -Edit
  |Warehouse
      -List

how can i do this?
Comment: @SamvelPetrosov sorry didn't get it, you mean a list of methods for each class?
Comment: @shingo TreeView or just an output doesn't matter
Comment: `typeof(Stuff)` is already such kind of thing, eg use `typeof(Stuff).GetNestedTypes()` you can get `Invoice` and `Warehouse`. and use `typeof(Invoice).GetFields()` to get `__, Add, Edit`...
Comment: Check this [link](https://social.msdn.microsoft.com/Forums/windows/en-US/dae1c72a-dd28-4232-9aa4-5b38705c0a97/populate-a-tree-view-in-c?forum=winforms)
Comment: @shingo, it works thanks
Answer: static void Main(string[] args)
    {
           Recoursive(typeof(Permissions).GetNestedTypes());
           Console.ReadLine();
    }

    private static void Recoursive(Type[] type)
    {

            foreach (var c in type)
            {
                Recoursive(c.GetNestedTypes());
                Console.WriteLine(c.Name);
                foreach (var f in c.GetFields())
                {
                    Console.WriteLine("\t-" + f.Name + ":" + f.GetValue(f));
                }
            }
    }

Thanks @shingo

Create nested list from class C#


Beginner difficulty in barre on higher frets on guitar

Question: I'm trying to play this song and the capo on 9th, 8th, 6th fret is killing me. I have to press so hard in irder to get clean good sound.
Of course I'm not an advanced guitar player, but it seems to be too hard. Does doing the manual capo become easier with time (as same happens with individual left hand fingers pressing individual notes) or does it have any special technique?
Thanks!
Answer: What you're referring to is the technique for playing barre chords. It is often one of the hardest techniques for anyone who is relatively new to playing guitar, but don't give up, as it doesn't necessarily take long to improve on. The problem is just that it's hard to mask and you end up getting frustrated as the sound it can produce when learning isn't particularly pleasing.
One important part of the technique is to make sure you're using the bony part of your finger rather than the fleshy part. This should produce a more consistent sound and will make it easier as you practice more.
In my personal experience however, the setup of your guitar can be the single biggest obstacle to learning the technique. If your guitar's action is too high you will find that you're having to put a lot of effort into getting the strings to press against the fret. You will know if your guitar's action is too high if the strings are not a consistent height above the fret board, particularly as you go further down. On cheaper guitars that haven't had any professional set up done on them, the action will often be far too high, and acoustic guitars are often the worst for this. Whist you can adjust your action relatively easily (electric guitars in particular), any guitar store will do this for you typically at a low cost. There are also some other adjustments that a technician might make (such as adjusting the truss rod), so it is often better to get a professional to do a full setup for your guitar. Also discuss with them  whether you may benefit from a lighter gauge of strings. All of these things combined can make the learning experience far less painful.
Comment: Before you pay for the setup, ask the repair technician if you might find it easier to play by switching to a *lighter gauge of strings.* Then get the full setup using whatever gauge of strings you select.
Comment: You could benefit by paying a repair technician for a **setup** on your guitar. This is what we call it when several different adjustments are made to multiple parts of the guitar to adjust the action and intonation to make the guitar easier to play all the way up and down the neck.
Comment: @WheatWilliams Agreed on both counts. Have added a note about the full setup.
Answer: What you are calling "manual capo" is actually called "barré" in case you want to look for more info.
Does doing the manual capo become easier with time (as same happens with individual left hand fingers pressing individual notes) or does it have any special technique?
can clearly be answered with "yes".  Or rather, both.  One part of the "technique" is actually selective application of force: you only need to press down fully on strings that are not covered by other fingers.  So for experienced players, the "simplest" barré covering all six strings with one finger may well actually be the most taxing and you might see the middle finger aiding with pressing down the index finger.  Depending on position, the middle finger might provide index finger help even while having its own task on the next fret by locking both together sideways.
Now you also state that barré on the higher strings is particularly strenuous for you.  That may well be the sign of a cheap or badly adjusted guitar with too much string clearance.  Obviously, the further you have to move the strings towards the fretboard, the more force will be required.
Try checking out an expensive guitar in a music store or from another player: that will give you a better idea just how much strength should be required from a good player in the long run.
Answer: The above answers pretty much nailed it, but I'd like to offer an additional tip that might be useful for getting the barres right: try moving your index finger a bit to find the position where you need to use the least force to get all strings ringing. I had plenty of difficulty with barres at first because of my skeleton-like bony fingers, and eventually I just wiggled the index around until I found the perfect position.


Best Way To Place SVG Content Within HTML

Question: From my research, i understand there are three ways to place an svg file inside HTML:
using embed:
<embed src="plot1.svg" width="500" height="320" type="image/svg+xml" />

using object:
<object data="plot1.svg" width="500" height="320" type="image/svg+xml" />

using iframe:

I've experimented with all three on a test rig (django built-in dev server, rendering the pages in Firefox 3.6). Under this obviously sterile environment, i haven't noticed any difference between the three--w/r/t performance or resolution.
My Question is whether one of these is better than the other two, and if so, which one. The answer might of course depend on the facts, which i've tried to limit to what's relevant:
We frequently display data (e.g, time series) on our website, usually created in response to some user action; based on that user action, a call is made to a database, the data returned is crunched and sent to the plotting engine, which renders a static image which is then embedded in the page--very standard stuff.
This works fine, but i would like to add some interactive features to these charts (e.g., tooltips, hyperlinked axis labels, highlighting a group of points w/in a plot). Some of the charts are fairly sophisticated (e.g., multi-panel conditioning) and i have not found a javascript chart library that includes these features. I finally settled on using the same plotting library (Lattice in R) but rendering each chart in svg and then adding the user-interaction features in a post-processing step, which consists essentially of javascript functions which manipulate the XML directly.
Comment: the  tag is not self closing you should add ``````
Comment: Just as a FYI, there are [several other ways](http://www.codedread.com/blog/archives/2010/09/21/start-chopping-off-heads/) to include svg on a page.
Answer: <embed> I would generally avoid. It's deprecated in HTML4, doesn't allow proper fallback content, and has had a selection of problems in IE.
<object> will allow you to include fallback HTML content for browsers without SVG support.  will fall back to prompting you to download the .svg file. Which of those is best probably depends on the application.
The other alternative, for modern browsers (including IE from version 9) is to serve your web page as application/xhtml+html and include the SVG elements in the page itself.
Comment: Whoa, IE supports SVG now? Never thought it would happen. Is VML still around too or what?
Comment: Well IE9 is still in beta but supports SVG (and pretty nicely, too). SVG boilerplate doesn't make SVG actually *work* down to IE6, it just makes it possible to put on a page without killing IE6. VML still exists, but would seem to be unwanted legacy; MS broke it quite badly in IE8, requiring another tedious round of workarounds for the people still using it.
Answer: for me the best way is this
<svg id="circle" height="60" width="60" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
  <image x="0" y="0" height="60" width="60"  xlink:href="huge-red-circle.svg" />
</svg>

You can see the example here
source: http://edutechwiki.unige.ch/en/Using_SVG_with_HTML5_tutorial


Packer.nvim: error running config for XXXX: attempt to call a nil value

Question: I have updated neovim to the latest version in the stable ppa (0.7.2)
However, I get some
Packer.nvim: error running config for toggleterm.nvim: attempt to call a nil value
Packer.nvim: error running config for nvim-cmp: attempt to call a nil value
...

I am not sure what could cause an error like this and how to debug it.
My plugins.lua (removing some unrelated plugins looks as follows)
local fn = vim.fn

-- Automatically install packer
local install_path = fn.stdpath "data" .. "/site/pack/packer/start/packer.nvim"
if fn.empty(fn.glob(install_path)) > 0 then
  PACKER_BOOTSTRAP = fn.system {
    "git",
    "clone",
    "--depth",
    "1",
    "https://github.com/wbthomason/packer.nvim",
    install_path,
  }
  print "Installing packer close and reopen Neovim..."
  vim.cmd [[packadd packer.nvim]]
end

-- Autocommand that reloads neovim whenever you save the plugins.lua file
vim.cmd [[
  augroup packer_user_config
    autocmd!
    autocmd BufWritePost plugins.lua source <afile> | PackerSync
  augroup end
]]

-- Use a protected call so we don't error out on first use
local status_ok, packer = pcall(require, "packer")
if not status_ok then
  return
end

-- Have packer use a popup window
packer.init {
  display = {
    open_fn = function()
      return require("packer.util").float { border = "rounded" }
    end,
  },
}

-- Install your plugins here
return packer.startup(function(use)
  -- My plugins here
  use "wbthomason/packer.nvim" -- Have packer manage itself
  use "nvim-lua/popup.nvim" -- An implementation of the Popup API from vim in Neovim
  use "nvim-lua/plenary.nvim" -- Useful lua functions used by lots of plugins
  use {"akinsho/toggleterm.nvim", tag = 'v2.*', config = function()
       require("toggleterm").setup()
  end}

  -- complete plugins
  use {'hrsh7th/nvim-cmp', config = function() require('cmp')
        end,
  }
    -- The completion plugin
  use "hrsh7th/cmp-buffer" -- buffer completions
  use "hrsh7th/cmp-path" -- path completions
  use "hrsh7th/cmp-cmdline" -- cmdline completions
  use "hrsh7th/cmp-nvim-lsp" -- lsp completions

  -- snippets
  use {"L3MON4D3/LuaSnip", --snippet engine
    after = 'nvim-cmp',
    config = function() require('luasnip.snippets') end,
  }
  use "saadparwaiz1/cmp_luasnip" -- snippet completions
  use "rafamadriz/friendly-snippets" -- a bunch of snippets to use

  -- Telescope
  use "nvim-telescope/telescope.nvim"

  -- Treesitter
  use {
    "nvim-treesitter/nvim-treesitter",
    run = ":TSUpdate"
  }

  -- Automatically set up your configuration after cloning packer.nvim
  -- Put this at the end after all plugins
  if PACKER_BOOTSTRAP then
    require("packer").sync()
  end
end)

and for toggleterm.lua as follows
local status_ok, toggleterm = pcall(require, "toggleterm")
if not status_ok then
  print("Toggleterm status not OK")
    return
end

toggleterm.setup({
    size = 20,
    open_mapping = [[<c-\>]],
    hide_numbers = true,
    shade_filetypes = {},
    shade_terminals = true,
    shading_factor = 2,
    start_in_insert = true,
    insert_mappings = true,
    persist_size = true,
    direction = "float",
    close_on_exit = true,
    shell = vim.o.shell,
    float_opts = {
        border = "curved",
        winblend = 0,
        highlights = {
            border = "Normal",
            background = "Normal",
        },
    },
})

function _G.set_terminal_keymaps()
  local opts = {noremap = true}
  vim.api.nvim_buf_set_keymap(0, 't', '<esc>', [[<C-\><C-n>]], opts)
  vim.api.nvim_buf_set_keymap(0, 't', 'jk', [[<C-\><C-n>]], opts)
  vim.api.nvim_buf_set_keymap(0, 't', '<C-h>', [[<C-\><C-n><C-W>h]], opts)
  vim.api.nvim_buf_set_keymap(0, 't', '<C-j>', [[<C-\><C-n><C-W>j]], opts)
  vim.api.nvim_buf_set_keymap(0, 't', '<C-k>', [[<C-\><C-n><C-W>k]], opts)
  vim.api.nvim_buf_set_keymap(0, 't', '<C-l>', [[<C-\><C-n><C-W>l]], opts)
end

vim.cmd('autocmd! TermOpen term://* lua set_terminal_keymaps()')

local Terminal = require("toggleterm.terminal").Terminal

local node = Terminal:new({ cmd = "node", hidden = true })

function _NODE_TOGGLE()
    node:toggle()
end

local ncdu = Terminal:new({ cmd = "ncdu", hidden = true })

function _NCDU_TOGGLE()
    ncdu:toggle()
end

local htop = Terminal:new({ cmd = "htop", hidden = true })

function _HTOP_TOGGLE()
    htop:toggle()
end

local python = Terminal:new({ cmd = "python", hidden = true })

function _PYTHON_TOGGLE()
    python:toggle()
end

Comment: You should at least provide your config of packer.nvim for these two plugins, otherwise, how would you suppose others to know your config magically :) ? At stackoverflow, always provide as detailed and relevant info as possible to increase your chance of getting anwsered.
Answer: :PackerUpdate (from inside nvim) fixed the issue for me.


Convergence of function sequence in $C([0,1])$

Question: I want to calculate limit of $f_n = (1-x)^n$ in $C([0,1])$
My work so far
Let's pick $f \equiv 1$. Of course $f \in C([0,1])$
Now I want to consider expression $\|f_n-f\|$
$$ \|f_n-f\|_{\infty}  = \sup_{x \in [0,1]}|(1-x)^n-1| = 0 \rightarrow0$$
So out of these facts I can claim that such defined $f$ is really a limit of $f_n$. Is my explanation correct ? If yes- could you please show me how to formally prove that $\sup_{x \in [0,1]}|(1-x)^n-1| = 0$ ? I see intuitevly that this supremum has to be zero, becuase $\sup_{x \in [0,1]}|(1-x)^n| = 1$, however I'm not so sure how to actually show this. Could you pleqae give me a hand ?
Comment: No, your calculations are not correct. Notice that for $x = 1$, we have $\left| \left( 1 - x \right)^n - 1 \right| = 1$. Therefore, $\sup\limits_{x \in \left[ 0, 1 \right]} \left| \left( 1 - x \right)^n - 1 \right| \neq 0$. Also, if you draw some graphs of the first few functions, you will understand that the sequence of functions does not converge in $\| \cdot \|_{\infty}$.
Answer: No, your answer is wrong. $(1-x)^{n} \to 0$ if $x>0$ and it tends to $1$ if $x=0$. Since the limit  is not continuous we cannot have uniform convergence. Thus,  this sequence is not convergent in $C[0,1]$.
Answer: Your answer is not correct. In fact $f_n(x)=(1-x)^n$ does not converge in $C[0,1]$, that is there is no $f\in C[0,1]$ to which $f_n$ converges uniformly. To wit:

The sequence $f_n$ converges point wise to $F(x)=\mathbb{1}_{\{0\}}(x)$, that is $F(0)=1$ and $F(x)=0$ in $0<x\leq1$.
As $F\notin C[0,1]$, convergence is not uniform.


Writing on MapPoint status bar

Question: I'm creating a MapPoint add-in with Visual Studio 2010. I would like it to write some log messages on MapPoint status bar, to make the user know what it is doing. Is it possible? In the reference status bar it's not even mentioned. Thanks!
Answer: The documentation is pretty complete. The reason it is not covered, is because the status bar is not exposed by the API.
The only way to do it, is to try and trap Windows messages, and directly manipulate the Status Bar control. This is definitely frowned upon from a security perspective, and "prohibited" by Vista and Win7. It is also undocumented, and could easily be broken by new releases of MapPoint.
Toolbar accessibility is similar, and an often requested feature. You can switch toolbars on/off, but you cannot add your own buttons.

Writing on MapPoint status bar


Using templates for creating PDF files

Question: I have some PDF template (with header and footer). I want to generate documents that are based on that template.
Is there any way to do that with iText? Thank you
P.S. Right now I am generate a document on-fly i.e. every time I generate header, footer and the context itself.
UPDATE: I have found incredible library called PD4ML. It's not free, but not such expensive, BUT it has really cool features such as HTML2PDF conversion on fly, supports a lot of HTML-CSS tags and has even its own jsp tags library! So I really suggest it when you need something instead of heavy and memory-eating JasperReports.
Answer: You can use JasperReports library and the iReport visual designer.
JasperReports use iText to produce PDFs from "jasper" templates, that are XML files (following the jrxml DTD) compiled in java classes, but allows you to use the template for generating MS Office files (with POI), html, etc.
Comment: Does JasperReports supports hibernate objects? I mean can I pass hibernate object as a datasource to jasperreports?
Comment: JR has a DataSource abstraction: it can query directly in SQL through JDBC or other various connectivity library, amongst which, if I remember well, hibernate with HQL. However you can pass a generic collection of JavaBeans, the more abstract datasource I think, at which at last evrything reconducts to.
Answer: Im not sure with iText, but you can use BIRT for this purpose. http://www.eclipse.org/birt/ Its too much using it just for PDF creation, you can do a lot (more than you can imagine) with it.
Answer: If you can choose your template format. I would go with JODReport and JODConverter.
JODReport use an ODT template and fill the mapping in the template with your java code.
JODConverter use LibreOffice to convert such template in PDF or whatever fortmat LibreOffice can handle to export.
You have to be able to use LibreOffice as a service installed remotely on a machine.
I used it back in 2012 but not sure if the project is still active

Using templates for creating PDF files


Infinite sets and arithmetic progressions

Question: If $S\subset\mathbb N$ is infinite, prove that we can find $p,q\in\mathbb N$, such that either whenever $ n\equiv p\pmod q$, we have$$
n\in S
$$
or else whenever  $n\equiv p\pmod q$, we have $$
n\notin S.
$$
Comment: This is not a well-posed question. Do you mean there are $p,q\in\Bbb N$ such that $\forall n\in\Bbb N$ satisfying $n\equiv p\mod q$ $n\in S$? If so, that's false if $S$ is just infinite.
Comment: Yes,if $S$ is infinite,I want find $p,q$, but I'm not sure if this conclusion is correct.Can you give me a counter example.thank you!
Comment: This has nothing to do with set theory, and it is not really number theory either.
Comment: Sorry,I'm not sure how to classify really!
Answer: This is false. Enumerate all pairs $(p,q)$ as $pair_1,pair_2,\dots$ Now build two disjoint sets $S$ and $T$ by stages. First, set $S_0=T_0=\emptyset$. Our construction will ensure that $S_0\subsetneq S_1\subsetneq S_2\subsetneq\dots$ and similarly with the $T_i$, while maintaining that $S_i, T_i$ are disjoint. At the end, we set $S=\bigcup_n S_n$ and $T=\bigcup_n T_n$ and note that, by construction, these sets are indeed disjoint. At stage $k$ we have $S_k,T_k$, the constructed sets so far, and consider $pair_k=(a,b)$. Find $n\ne m$, both large enough (larger than all elements in $S_k\cup T_k$) and congruent to $a$ mod $b$. Set $S_{k+1}=S_k\cup\{n\}$ and $T_{k+1}=T_k\cup\{m\}$.
The construction ensures that, for any $p,q$, both $S$ and its complement (that necessarily contains $T$) have elements congruent to $p$ mod $q$. This means that $S$ does not contain all these elements, but does not miss all of them either.
(By ensuring for instance that each pair is listed infinitely often, we may also arrange that both $S$ and $T$ meet each such congruence class in an infinite set.)


É aconselhável ter uma tabela de Usuários se relacionando com outras?

Question: sou iniciante em desenvolvimento de sistemas, e gostaria de saber se a tabela de usuários do sistema poderia estabelecer relações com outras tabelas, como por exemplo, a tabela de empresa.
Answer: Sim, sem problemas.
Por exemplo, eu poderia associar usuários a empresas usando chaves estrangeiras:
<code>CREATE TABLE EMPRESA (
    EMPRESA_ID INT PRIMARY KEY,
    -- Coloque aqui as colunas que você gostaria que EMPRESA tivesse
)

CREATE TABLE USUARIO (
    USUARIO_ID INT PRIMARY KEY,
    EMPRESA_ID INT FOREIGN KEY REFERENCES EMPRESA(EMPRESA_ID),
    NOME VARCHAR(255),
    -- Coloque aqui as colunas que você gostaria que USUARIO tivesse
);
</code>
As associações também podem ser feitas para outras tabelas. Tudo depende do objetivo desejado.
Note que não usei uma sintaxe SQL em específico. A ideia é apenas ilustrar o que pode ser feito.
Comment: É que eu quero fazer um sistema em que o usuário se relacione com a tabela de chamado e empresa. Aí fiquei na dúvida se desmembrava essa tabela, pois nela vai conter o usuário, tipo de usuário e campos afins, para alguma outra tabela específica.
Comment: No seu lugar, faria a tabela de chamados se relacionar com empresa e com usuário. Nada impede que isso seja feito na modelagem.
Comment: Modelei a tabela de chamados se relacionando com funcionários(contendo os campos para login) e usuarios(contendo todas as informações da empresa e os campos senha, e login). Caso eu queira adicionar uma tabela de comentários, como eu modelaria? Visto que o comentário pode ser feito pela usuário e por um funcionário, e as chaves estrangeiras não podem ser nulas? Por exemplo, como eu sei que foi o usuário quem comentou, e não um funcionário?
Comment: Isto já seria conteúdo para uma nova pergunta.
Comment: Vou fazer! Obrigado pela atenção


Web application on Local network

Question: This is the same question asked here. I don't know if this issue was resolved. I am unable to connect to my local server from other network PCs.
I am using Eclipse with Tomcat to run my web application. It is a simple demo html page with no server code. It is opening in my own system when I am using http://localhost:8080 or my static ip as http://220.127.116.11:8080. But if I try to access this page from another PC on the same network, I get network timeout error. I am using Ubuntu 11 whereas other network PCs are using Windows. Those PCs are able to ping my IP and get a reply, only the web page do not come in the browser. Are there any firewall settings or any other settings I need to do for Network PCs to be able to access my server?
Comment: Do you have any proxy settings in your browser?
Comment: There is no proxy setting in browser, and network is also not configured for any proxy server.
Comment: Are you able to connect to port 8080 from the client? i.e
nc 18.104.22.168 8080 ?, if not check to see if iptables is blocking that port in the INPUT chain
Comment: You mean like "ping 184.108.40.206:8080". If I am trying to ping the particular port, it does not reply. However, "ping 184.108.40.206" replies. Can you tell me how to check the iptables is blocking any port? Sorry if it sounds like a dumb question, but I am new to Linux also.
Comment: You can't use the ping utility to check a tcp port. And by default I believe Ubuntu uses UFW and not iptables. It really sounds like you've bitten off more than you can chew.
Answer: If they are getting a 404 error that means that the clients are connecting to a webserver somewhere.
I'm not overly familiar with tomcat, but it should be logging the access somewhere - even if it is a 404 response - so the first step is to check to see if the request is getting to your machine. After that, it s a problem with your code / config. Most likely you've not configured a vhost for the name.
What does your server.xml look like?
Comment: It's not exactly Page not found 404 error. It is rather getting timed out. Firefox says connecting to my IP, and after a few seconds, it says the request timed out and the resource may not be available or some such message. I haven't modified the server.xml. It's the same as when I downloaded Tomcat. I think it's not connecting to my server at all because I don't see any logs at the server console inside Eclipse.
Comment: "I get Page not found error" - we're only able to advise on the errors you report. Check your firewall config.
Comment: Sorry about that. Have edited my question now. Can you advise on what exactly am I looking for in firewall settings?
Comment: You're looking for whether port 8080 is open for those within your same subnet.
Answer: This is somewhat like a problem I experienced - I could connect locally just fine, but trying to hit it from another computer on the same network always failed.
Turns out my primary interface (eth0) was NOT automatically connecting when the system booted. When tomcat starts, it binds to all known interfaces - so it never bound to my external IP address, only 127.0.0.1. Later, when I started the interface and got an IP address from the DHCP server, tomcat was already running and unaware of the new IP.
Solution? Stop tomcat, make sure all of your interfaces are connected with valid IP addresses, and then restart tomcat.
Comment: To further investigate along these lines, in a terminal type `netstat -ant` and see if anything is listening on port 8080 for the desired IP address. If it's not listed, then you'll know that something is wrong with the tomcat config, or as stated above, just needs a restart.

Web application on Local network


JavaFX, Open a Screen in same Window

Question: I'm trying to implement an application, which has a simple navigation. One Main Menu, 3 Submenus, with another 3 Submenus each.
I need the application open every submenu recursively in the same Window with the Mainmenu as the root screen. I must be able to return to that menu by going via the "Back" Button on each Submenu.
I implemented a Main class, a Controller Class and a FXML-file for EACH (!) Menu and Submenu.
E.g. my Main Menu
<code>      package application;

import org.apache.log4j.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;

public class Main extends Application {

    // Initialize Logger
    private static final Logger logger = Logger.getLogger(Main.class);

    @Override
    public void start(Stage primaryStage)
    {
        try
        {
            AnchorPane root = (AnchorPane)FXMLLoader.load(getClass().getResource("MainFrame.fxml"));
            Scene scene = new Scene(root,1000,500);

            primaryStage.setScene(scene);
            primaryStage.show();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        logger.info("Starting application.");
        launch(args);
    }
}
</code>
My MainController
<code>    package application;

import org.apache.log4j.Logger;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class MainFrameController
{

    private static final Logger logger = Logger.getLogger(MainFrameController.class);

    @FXML
    private Button btn_random1;
    @FXML
    private Button btn_random2;
    @FXML
    private Button btn_random3;
    @FXML
    private Button btn_random4;

    public void initialize()
    {
        //mainService = new MainService();
    }

    @FXML
    private void onRandomButton1() throws Exception
    {
        logger.info("onRandomButton1Clicked");

        Stage stage = new Stage();
        AnchorPane root;
        root = (AnchorPane)FXMLLoader.load(getClass().getResource("RandomFXML1.fxml"));
        Scene scene = new Scene(root,1000,500);
        stage.setScene(scene);
        stage.show();
    }

    @FXML
    private void onRandomButton2()
    {
        logger.info("onRandomButton1");
    }

    @FXML
    private void onRandomButton3()
    {
        logger.info("onRandomButton2");

    }
    @FXML
    private void onRandomButton4()
    {
        Platform.exit();
        logger.info("onRandomButton3");
    }
}
</code>
Is there a way to simply change my code, so it does open in the same window?
I took a look at several tutorials with relatively complex ways of solving this, I'd like to stick to my code and not changing too much, otherwise I'd have to start all over again.
Pls note, that this is only one of many Main/Controller/FXML combinations, I have about 10 screens and "subscreens", which are being navigated like this (by java opening a new window).
Ideas anyone? Or maybe a relatively simple tutorial (for which I dont have to change my whole code)?
Thanks!
Answer: Have an empty controller at the root (or perhaps with a single empty anchorpane) and have it open the other controllers and add it to the current pane?
I currently have a similar setup but with a tab pane: each module is loaded into a separate tab. Each module itself has an fxml file, a controller etc. The core code dynamically creates new tabs etc for each module and loads them.

JavaFX, Open a Screen in same Window


Voicing Freddie Green-style rhythms in jazz arrangement

Question: I'm working on a jazz arrangement and i was thinking of a walking bass, brushes on the drums, some chord stabs and fills for the piano, but as for the guitar it's a bit difficult. I want to write in the style of Freddie Green. But I have one major problem, which is the chord voicings. I tried writing some but they were clashing with the bass, and I'm not sure if going higher in the fret board would give me the sound i might want. So I need advice on how to improve the voicings and if there is any other comping rhythm similar to Freddie Green I can use.
Here is an example of the arrangement similar to what i want to do:

.
A quick note if it helps you to answer: the song I'm arranging uses the circle of fifths chord progression.
Comment: The guitar player will know how to voice the chords.
Comment: You'll probably get a good answer here, but you'll also find some good resources by searching "Freddie Green voicings" on Google. There shouldn't be any clashing with the bass--it shouldn't be playing that high normally. These resources may help: [1](https://static1.squarespace.com/static/57c9744dc534a5c7c89a78c5/t/57d55e0b197aea516930bea2/1473601038255/Freddie+Green+Chord+voicings.pdf), [2](https://www.freddiegreen.org/technique/FGchordforms.html), [3](https://www.freddiegreen.org/technique/cervenka_numbering.html)
Comment: I was going to comment that Freddie was more rhythm than harmony, but the second link from @jdjazz really makes that point better than I could.
Comment: @DaveJacoby, is that true? I know people usually think of Freddie Green = 4-to-the-floor, but I think that's an oversimplification. I know he had a distinct approach to harmony. Doesn't the second link describes specific fingerings/ voicings? I don't play guitar and can't read tab--I'm asking in earnest.
Comment: @jdjazz Yes, as I understand it. Roughly, a whole lot of _thunk_ with a bit of chord tone. If both the bass and guitar are playing notes from the same chord, I don't see why they should be clashing.
Answer: Freddie Green had  fairly unique style. He would fret complete chord voicings but mute most of the strings and only have one string ringing (mostly the D string). With the right hand he would mostly play straight quarters.
This makes his contribution a mixture of rhythm instrument keeping the beat while at the same time playing single line.
I'm guessing that this was partly motivated by basic physics: He played only acoustic guitar which is a fairly soft instrument. You really need to optimize "audibility" to be heard at all inside a large big band. Complicated chords are rhythms would just be drowned out. Staying on the D-string helps to stay below most horn parts but above the bass, so it's relatively "sparsely" populated frequency range.
The most tricky part is what "line" to play. You want something that augments the melody without clashing with the other supporting voices or the bass and also "hints" at what the full chord would be. And then the whole thing needs to fit into the fairly limited usable range of the acoustic D-string (which is maybe an octave).
Playing guitar in a big band is an interesting experience: While pretty much every instrument's part is written out in excruciating detail, the guitar player just gets a chord sheet with some vague suggestions of what might work here or not. Most important info: "play something" vs "shut up" :-)


How to get the WebProxy used by existing instance of an HttpHandler?

Question: How do I write out the address of the WebProxy, that is used by my HttpHandler, when I only have access to that Handler and Client?
var CookieBox = new CookieContainer();
var Handler = new HttpClientHandler { CookieContainer = CookieBox, UseProxy = true, Proxy = GetProxy() };
var Client = new HttpClient(Handler) { Timeout = TimeSpan.FromMilliseconds(loop * 10) };

Result like 188.8.131.52:10045 is what I need.Handler.Proxy.GetProxy() seems not to be it.
Answer: I found out.
The IWebProxy Handler.Proxy is a WebProxy instance which does expose the Address member. Just cast it.
var tempProxy = (WebProxy)Handler.Proxy;
Console.WriteLine(tempProxy.Address);


Standard Deviation

Question:
For the genetics of a given plant, the probability of any seed it produces being brown is 3/4.  The plant produces 80 seeds.  Let $X$ be the random variable that counts the number of brown seeds.  Find the expected value and the standard deviation of $X$.

So... I figured the expected value of $X$ to be 80 x 3/4 = 60.  But what I don't understand is how do you figure the standard deviation of $X$ when you have a brown seed or not!  How do you get a mean from this?
Comment: Please add the `[self-study]` tag & read its [wiki](http://stats.stackexchange.com/tags/self-study/info).
Answer: Let $Y_i$ be a random variable taking the value $1$ if the seed is brown and $0$ otherwise. Moreover, I assume the all $Y_i 's$ are independent. As you already correctly stated, the expectation is
$E[X]  = E[\sum_{i=1}^{80} Y_i] = \sum_{i=1}^{80}  E[Y_i] = \sum_{i=1}^{80} 0.75 = 60$.
The standard deviation is defined as the square root of the variance of a random variable: $SD[X] = \sqrt{Var[X]}$. The Variance is defined as $Var[X] = E[X^2] - E[X]^2$. In your case,
$Var[X] = Var[\sum_{i=1}^{80} Y_i] = E[\sum_{i=1}^{80} Y_i^2] - E[\sum_{i=1}^{80} Y_i]^2$.
Now, since the all $Y_i$ are independent the variance of the sum is equal to the sum of variances. Moreover, you know already the expectation for one $Y_i$. It's $0.75$. In addition, $E[X^2] = E[X]$ because squaring 0 or 1 is again 0 or 1.  Hence, you get
$Var[\sum_{i=1}^{80} Y_i] = \sum_{i=1}^{80} Var[ Y_i]  \\
\qquad \qquad \qquad = \sum_{i=1}^{80}(E[Y_i^2] - E[Y_i]^2) \\
\qquad \qquad \qquad=  \sum_{i=1}^{80} (E[Y_i] - 0.75^2) = 80(0.75 - 0.75^2) = 15 $.
So, your standard deviation is eventually $SD[X] = \sqrt{Var[Y_i]} = \sqrt{15}$
Comment: You're welcome. If you like my answer, you can accept it by clicking on the check mark below the zero. :)
I mean, you see the vote score to the left hand side of my answer. Below is the check mark.

Standard Deviation


Calling C# static void methods with no parameters that require multiple Console entries

Question: I'm very new to C# and trying to call a static void method with multiple console input like this one here:
static void CustomerInfo()
{
    Console.WriteLine("Custom First Name: ");
    string firstName = Console.ReadLine();
    Console.WriteLine("Customer Last Name: ");
    string lastName = Console.ReadLine();
    Console.WriteLine("Customer Address: ");
    string address = Console.ReadLine();

}
static void PrintCustomerDetails(string first, string last, string
address)
{
    Console.WriteLine("{0} {1} address is: {2}", first, last, address);
}

This should return all required CustomerInfo but I'm getting just the Firt Name as input on the Console. Please help. Thanks in advance.
Comment: You dont show where you call `PrintCustomerDetails`. Apart from that, `CustomerInfo` does nothing because the strings are stored in local variables which cannot be accesssed from outside.
Comment: @skoye Variables are scoped inside the method how they can be visible at all outside `CustomerInfo` method?
Answer: call your method PrintCustomerDetails like this
static void CustomerInfo()
{
    Console.WriteLine("Custom First Name: ");
    string firstName = Console.ReadLine();
    Console.WriteLine("Customer Last Name: ");
    string lastName = Console.ReadLine();
    Console.WriteLine("Customer Address: ");
    string address = Console.ReadLine();

    PrintCustomerDetails(firstName, lastName, address);
}


Conversão de formato 0001-01-01T00:00:00Z de campo time.Time

Question: Estou utilizando o ORM gorm para um projeto, e nas colunas referente as datas, conforme documentação, é necessário setar o tipo time.Time nos campos das Structs que abstraem datas.
O retorno dessas colunas geradas pelo ORM, vem no padrão 0001-01-01T00:00:00Z (do tipo time.Time). Como exatamente consigo formatar essa estrutura para outro formato como 0001-01-01 00:00:00 e vice-versa (transformar outro formato para este que ele está usando por padrão)?
Tentei vários exemplos que encontrei na internet, mas nenhum trabalhava com esse formato em específico, e não tive sucesso com algumas dinâmicas que vi em alguns outros tópicos, trabalhando com o parse de outros formatos, já que não encontrei nenhum exemplo prático que tenha esse formato.
Answer: Se ele já é um time.Time você pode "mudar isso" usando o próprio .Format(). Você só vai mudar quando for exibir a data, no caso.

Considerando que tenha:
type SeuStruct struct {
    Data time.Time
}

Então bastaria usar o seuStruct.Data.Format, como:
func main() {
    // Considerando que o `SeuStruct` fosse o seu struct
    ss := &SeuStruct{Data: time.Now()}

    // Formata como quer exibir:
    fmt.Println(ss.Data.Format("2006-01-02 15:04:05"))
}

O 2006-01-02 15:04:05 define o formato, você pode ver a documentação em https://golang.org/pkg/time/#pkg-constants.
Comment: Se está preocupado com performance, nesse nível, não use `time.Time` em primeiro lugar, a conversão já ocorre ao tornar o TIME/DATE/TIMESTAMP/DATETIME em `time.Time`. Se não quer a conversão para `time.Time` remova o `parseTime=True` (ou equivalente, ao iniciar a conexão com banco de dados) e use `string`. Também pode usar o próprio `DATE_FORMAT()` do MySQL (ou equivalentes) e retornar como string, de qualquer forma conversão vai ocorrer. Eu uso `time.Time`, ele também implementa o `.MarshalJSON` e o `.GobDecode` então o `json.Encoder()`/`gob.Encoder()` funciona diretamente.
Comment: Entendi! Existe alguma maneira eficiente de eu padronizar esse formato no retorno de uma query por exemplo? Porque o que penso em fazer é iterar todo o slice retornado pela query e dar o `.Format()` no campo que é time.Time, mas não me parece eficiente isso.
Comment: Certo, me ajudou bastante sua explicação, muito obrigado!


Facebook Open Graph do link da postagem do meu site não aparece descrição e thumbnail é pequena

Question: Estou a trabalhar no Open Graph de uma plataforma Blogger. Quando publico algo no facebook, a apresentação do conteúdo de um artigo aparece desse jeito:

Quando colo o link da postagem do blog no Facebook não fica exatamente como gostaria, quero que a imagem fique maior, com título e descrição da postagem, exatamente assim:

As tags estão assim:

Já utilizei o Open Graph Object Debugger.
Alguém pode me ajudar, por favor?
Comment: Deves utilizar imagens que são pelo menos `600 x 315` para que a imagem apareça grande como no segundo exemplo mencionado na tua pergunta. Podes postar aqui o link da publicação que estás a tentar partilhar para poder ver o que se está a passar com a descrição?
Comment: Aqui o link http://www.futebolcomblush.com.br/2015/07/crise-no-cariri.html
Comment: Veja se te ajuda: http://pt.stackoverflow.com/a/67143/8493
Answer: Para que as imagens apareçam grandes como no segundo exemplo mencionado na sua pergunta, utilize imagens que têm pelo menos 1200 x 630 pixels para melhor exibição em dispositivos de alta resolução. O tamanho mínimo requerido para que as imagens apareçam grandes desta maneira, é de 600 x 315 pixels. E o tamanho mínimo requerido para a og:image é de 200 x 200.

Podes ler mais sobre o tópico - og:image aqui neste link

No entanto eu reparei que o problema da imagem aparecer pequena foi devido a uma falta de atualização, pois após ter inspecionado o link no Object Debugger eu vi que a imagem aparece grande após ter atualizado o link com o Object Debugger.
Sobre a descrição não aparecer, experimenta trocar a og:description da seguinte maneira.
Troca o código atual:

<meta expr:content='data:blog.metaDescription' name='og:description'/>

Para o seguinte:

    <meta expr:content='data:blog.metaDescription' property='og:description'/>

    <meta expr:content='"Ler artigo sobre " + data:blog.pageName + " em " + data:blog.title + ""' property='og:description'/>

Basicamente o que isto vai fazer é pegar a meta description caso esta exista e exibi-la como og:description, mas se não houver uma meta description disponível, então o texto Ler artigo sobre ... irá ser implementado como og:description em vez disso.
Meta description no Blogger
Para activar as meta description você tem que ir até:

Definições > Preferência de pesquisa > Meta tags > Descrição Clique em editar.
  E irá aparecer o seguinte:

Adicionar Meta description a publicações individuais
Simplesmente edite a sua publicação ou página e procure pela opção Descrição da Pesquisa, e é aqui que iremos adicionar a descrição de cada página que agora também vai ser exibida como og:description para o Facebook.
Comment: Funcionou perfeitamente! Muito obrigado :)    Pensei que já tinha marcado a resposta correta aqui, desculpa
Comment: Oi Chun!
Eu fiz o que você sugeriu, agora aparece a descrição e a imagem ta grande, só falta ser a descrição da postagem, olha como ficou:
http://oi59.tinypic.com/a2rsyq.jpg
Poderia me ajudar?
Comment: Oi @DiegoGomes , desculpa faltou mencionar a parte de - "ativar as `meta description` tags". Já atualizei a minha resposta. Ele agora deve funcionar na perfeição =)
Answer: Você não está escrevendo as meta tags do facebook, está? E para a imagem aparecer maior ela deve ter o tamanho 600x315 ou 1200x630.
<meta property="og:title" content="Lorem ipsum" />
<meta property="og:description" content="Lorem ipsum..." />
<meta property="og:image" content="URL_DA_IMAGEM" />

Link da documentação: https://developers.facebook.com/docs/sharing/best-practices#images
Comment: Oi, essa descrição que devo inserir é a do site, ou da postagem?
Essa é uma das dúvidas que tenho, porque se for pra escolher uma padrão, todas serão iguais?
Comment: @DiegoGomes a descrição é das postagens, será o que vai aparecer no dialog do facebook. O mesmo para title e image
Comment: Isso que o @KaduAmaral falou. Mas tipo na index do seu site você deixa o título, descrição e imagem do site mesmo. E interna das notícias você deixa com os dados da notícia, etc.


How best to coordinate parts spacing when composing by hand?

Question: Forgive my enactment, but it seems like the easiest way to explain: Let's say, hypothetically, it's a piano piece. I'm on a train, composing on paper, no piano in sight. I have a strong idea for a part in the bass clef. It's fairly simple rhythmically, spanning about 10 measures, but the notes vary in each measure. I then start working on the treble clef. I had a vague idea to start, and it evolves as I write. I want a complicated run in measure 5. Ooops! I don't have enough space to properly coordinate with the bass clef. Time for the eraser. Or, I re-write bar 5 on a different page and worry about it later when finalizing. Or, maybe next time, I space out the bass clef part extra-wide, just in case I decide to cram a bunch of notes above it. Ugh!
I assume this is a problem solved by others long ago (centuries ago), and there's probably a set of best practices somewhere. However, I can't find them. Notation software obviates the issue (obviously), but I'd really like to get more comfortable notating by hand, well.
Comment: Centuries ago, Beethoven wrote in pen and crossed out several measures or pages and rewrote them when he needed to fix something. So by using an eraser you've already achieved the state of the art in hand writing notation. There is a tactic that was used in musical theatre before everyone switched to software which was every line of a staff was always split evenly into four bars and you could fit 16 16th notes in each bar if you wanted to. You could also cut out bars from one page and paste them on another and they would line up. Doesn't help much for 64th note runs or cadenza style stuff.
Comment: Draft is different than final copy. Scratch out or erase what must go and rewrite somewhere else. Once you're all done, then put it in the computer.
Comment: Funny, I was right thinking about such kind of things as asking and giving inputs how to notate sheet music.
Answer: It doesn't matter at all!
It's the same as you have to edit a literary texture:
As this will not be the final layout of your composition just notate your idea with a short graphic sign, may be red coulored or by a *1), then number the specific bars and continue writing at the end of of your already finished phrases and notate the idea in the new measure, assigne it with 1) and in the final layout you can insert this measure in the part above. Don't forget to markup the place where it will be inserted.
Comment: Much appreciated. Thank you! And thanks all for the helpful comments above, as well.


Prove that f induces a unique homomorphism F/[F, F] → G and conclude that F/[F, F] ≅ Fab(A).

Question: Let $F = F(A)$ be a free group, and let $f : A \rightarrow G$ be a set-function from the set $A$ to a commutative group $G$, and where $[F,F]$ is the subgroup of F generated by all elements of the form $aba^{-1}b^{-1}$. I believe that is what is commonly referred to as the commutator subgroup.

Prove that $f$ induces a unique homomorphism $F/[F, F] \rightarrow G$ and conclude that $F/[F, F] \cong Fab(A)$.
Comment: What have you tried? This basically comes does to chasing the generators, although you should also realised that $F/[F, F]$ is abelian and moreover every abelian quotient of $F$ must pass through this...
Comment: I honestly wasn't sure where to begin. I'm trying to brush up on algebraic structures before I take the second course in it and I never truly understood a few concepts from the introductory course.
Answer: Hints:
== In any group $\;G\;$, the quotient $\;G/[G:G]\;$ is abelian , and the commutator subgroup $\;[G:G]\;$ is characterized for being the minimal such subgroup, meaning that if $\;N\lhd F\;$ is s.t. $\,G/N\;$ is abelian then $\,[G:G]\le N\;$ .
== The universal property of free groups tells us that any set function $\,A\to G\;$, with $\;G\;$ a group, can be uniquely extended to a group homomorphism $\;F(A)\to G\;$ .
Work out the above, which btw can be found in any decent group theory book.


Webform what is format required to prepopulate datetime element

Question: Sending default date format (medium) from VIEW rewrite results link, URL adding
?apptdatet={{ field_apptdatet }}
This never fills the webform datetime field. The value is shown in the url as medium formatted date. day mm dd yyyy hh:mm:ss
On the webform the apptdatet field shows the correct format mm/dd/yyyy hh:mm:ss, the value is always blank however.
in the view apptdatet shows as Mon 05-14-2018 15:30
Does anyone know what Webform is looking for?
Answer: You need to use an ISO date.
<code>?apptdate=2018-06-13T01:01:01-0400
</code>
Comment: Excellent, I will now try to figure out how to convert the default drupal date in the view field to the ISO format in the URL
Comment: The issue continues at: https://drupal.stackexchange.com/questions/263915/how-to-remove-the-added-underscore-views-adds-to-rewritten-link-d8


Contar elementos anteriores

Question: Bom dia senhores,
Preciso contar elementos de uma li e adicionar esses valores dinamicamente contando os elementos li anteriores:

1 - Conteudo 1

2 - Conteudo 2

3 - Conteudo 3

4 - Conteudo 4

5 - Conteudo 5

6 - Conteudo 6

A ideia é que os elementos 'i' da class ="indice" recebam o cada um seu índice dinamicamente. Como sou novo com jquery estou tendo dificuldades em realizar essa função, alguem teria uma ideia de como posso resolver isso? Abraço a todos!
Comment: usa o each e o addClass()

http://api.jquery.com/each/
http://api.jquery.com/addClass/
Comment: Bom dia periotto, o each conta os elementos corretos? se sim, a minha dúvida é como eu faria para ele contar apenas os elementos anteriores e passar esse valor para o .indice! Abraço!
Answer:

$(function(){

  $('#add').click(function(){
      var count = $("ul").children().length;
      $('ul').append('
'+(count+1)+' - Conteudo '+(count+1)+'
');
  });

});

1 - Conteudo 1

2 - Conteudo 2

3 - Conteudo 3

4 - Conteudo 4

5 - Conteudo 5

6 - Conteudo 6

  <button id="add">Adicionar</button>

Comment: Era exatamente isso, Valeu Jefferson! Abraço!

Contar elementos anteriores


Consequence of choosing wrong functional of covariates in GLM/GAM

Question: I'm modelling the mood of teenagers in a really big school. Response is 'good mood' and 'bad mood'. One of the variables that is used to explain the students mood is "Area of residence".
Explanatory variable "Area of residence" has 5 categories: Area1, Area2,...,Area5 and for the big school their coefficients are calculated to be $\hat{\beta_1}, \hat{\beta_2},...,\hat{\beta_5}$
I'm also modelling the students mood in a really small school, and we do not have much data. Some researcher says that for all the categorical explanatory variables we calculated before (for the big school), we can just use those calculated coefficients as restrictions in the analysis for the small school. E.g. in a lot of new statistical software one has the option to "save" a bunch of coefficients calculated for an explanatory variable, basically giving us a special function that can be used later in another GLM/GAM analysis (for the same categorical variables).
For the little school we a scarce amount of data such that that none of the categories (Area1-Area5) have significant p-values (we are a research group of "let's just evaluate p-values"). Using the restrictions we calculated for the big school, we have the model:
$log\frac{\pi}{1-\pi} = \beta_{new}[Area1=\hat{\beta_1}, Area2=\hat{\beta_2}, ... , Area5=\hat{\beta_5}]$
Only $\beta_{new}$ is estimated in the model for the little school, while the other betas are "restricted". The idea, or justification, is that the "Area of residence" variable affects the students mood exactly the same form (relationship between categories are the same) in both schools, except that the "effect" can be dampened or heightened depending on the MLE estimation of $\beta_{new}$.
Now, imagine if you do this with, say, 10 different variables and evaluate the p-values of the 10 coefficients $\beta_{new_1}, \beta_{new_2}, ..., \beta_{new_{10}}$. Some p-value in $\beta_{new_i}$ be significant due to chance and the wrong conclusion "the relationship between the categories of variable "x" is the same in the two schools" is drawn.
Question 1: Is this not another fancy version of data dredging from stepwise regression techniques (good answer here)?
Question 2: This is basically an attempt to be innovative, and be able to use information drawn from a big source, and extrapolate it towards a smaller source. Am I correct in thinking that this could be a good idea if one believed strong heartedly that e.g. "Area of residence" must behave the same in the two schools? But a disastrous idea when blindly fumbling in the dark trying to feel out p-values to determine which variables behave the same (have the same form) across the two schools?
Question 3:@Repmat points out in his answer that choosing the right functional is not critical. And, if I understand correctly, if it were critical, you would see it from your testing and validation sets. But what if the method described above would be used in the making of all the models (because it is common belief that it is a good method)? Then, would I not be comparing just bad models - leaving me with the least bad model?
Thoughts and reference request:Viewing this it made me think of how disastrous doing GLM/GAM analysis with the wrong functional of some covariate could be. For example, if one were able to fit $E[y] = x^2$, even though $E[y] = x $ were a more true model (like I tried to explain above), this would be horrible for future predictions of $E[y]$. Does any research exist on the consequences of choosing the wrong functional?
EDIT: fixed some of the structure of this question.
Comment: Just on your last point - the *range* of your data is crucial here.  If you are interpolating, then functional form doesn't matter so much - you'll get worse results (if you pick the wrong form), but still be "in the ballpark".  Extrapolation is where is matters much more.  Eg if you want to predict at $x=1000$ but your training data has values between $25$ and $100$ the choosing $x^2$ or $x $ will make a big difference.
Comment: Thank you for pointing that out. Can I draw from your comment (which I think revolves around the form of a continous explanatory variable) that this goes for *form* of a categorical explanatory variable as well (basically what I am asking in the first two parts)? I feel like there is a big difference here...
Comment: The equivalent for categorical variables is "new" categories.  For example, if you had to predict for a school that had students in "area 6".
Answer: You are asking the central question for any parametric type of analysis, what if my model (in casu the functional form) is wrong? This is not as depressing as one might think, you lose unbiasedness but can maintain consistency provided the regressors are truly exogenous. Therefore the relevant question is really if you have omitted variables. If you do the estimates are simply wrong, and nothing (in general) can bail you of that assuming you don't have an instrument.
You mention predictions, if this is your interest then consistency might be less important and the above should not worry you to much. Your test and validation sets will tell you, if you are doing well enough.
In any case there is little you can do, other than grab more data or make do with what you got.
Comment: Thank you for answering! I was actually just about to edit the question, but hope you understood what I tried to ask without too much effort! I'll try to follow up with a couple of questions here, if you don't mind:
1) wrt predictions, of course you are right, a test and validation set will clear things up. What bothers me is the method used. It feels to me like what @Frank Harell in his book talks against: data dredging and trusting p-values.
2) wrt wrong functional form not being critical, you are probably correct. ..ctd..
Comment: ...ctd.. but I'm just worried that by trusting a *form* by it's p-value (of $\beta_{new}$) is dangerous. What if the first half of the coefficients, say $\beta_1,\beta_2, \beta_3$ fit well to the new data (little school in my example), but $\beta_4$ and $\beta_5$ fits just horribly! The p-value of $\beta_{new}$ might be really small.

I'm trying to make do with what I got wrt little data, I did not quite understand what you wrote about exogenous variables, though, but found a nice explanation (http://stats.stackexchange.com/questions/59588/what-do-endogeneity-and-exogeneity-mean-substantively)
Comment: You can never test if a given form is right or not, but what you do is measure if one form performs better than another given some relevant criteria. Ofc, you should never blindly trust a pvalue, instead try and determine what the model should be able to do and see how well it works.
Answer: One way to think of what you're doing, that shows this is not data dredging.  If you consider the big + little schools as one data set (person $i $, area $a $, school $s $), then you have a general model of:
$$\eta_{ias}=\beta_{as}$$
And your restricted model corresponds to the following assumption (b=big school, l=little school):
$$\frac {\beta_{ab}}{\beta_{al}}=\beta_{new} $$
And you can write the restricted model as :
$$\eta_{ias}=\beta_{ab}\beta_{new}^{I\{s=l\}}$$
You can thus fit into the framework of likelihood ratio testing, as your hypothesis consists of restricting the parameter space of the full model (the full model is where the little school gets each area effect estimated separately).  This is one way to get an overall effect of whether the simplification is doing a good job.
However, this is a non-linear GLM, so the distribution under the null hypothesis may not be chisquare.  Might be good to use parametric bootstrap or something (see below for rough outline)
This non-linear GLM can be iterated between two linear GLMs.  Fix $\beta_{new} $ then estimate $\beta_{ab} $.  Then fix $\beta_{ab} $ and estimate $\beta_{new} $.  The method you've written is one cycle of this approach, setting the initial value for $\beta_{new}$ equal to zero.  The justification for only using one iteration is that the big school has more data - so the influence of the little school data has on estimating the common parameters is negligible.  The second iteration only involves the units in the small school.
Additionally, you don't need "restrictions" to estimate these models - just a modified design matrix for each regression.  In the first model ($\beta_{new} $ fixed) instead of 0-1 dummy variables for each area, you have $\beta_{new}^{I\{s=l\}} $ instead of the "1" (i.e. replace the "1"s in the design matrix with $\beta_{new}$ for the small school units).
For the second model, the design matrix is the linear predictor from the first model ($\beta_{ab} $) and the fitted model has no intercept.
But importantly, because the model is not strictly a GLM, you may not be able to rely on the standard normal approximation theory to get your p-values.  You should check that this is the case.  This is not hard to do:

simulate data from your model using the betas you estimated.  Keep the lop sided big/little school samples, and keep the same area distributions (i.e. only change the binary response you are modelling)
Refit the model using the simulated data in step 1, getting simulated parameter estimates
Repeat steps 1&2 many times (say $500$ or so)

The simulated betas should have an approximate normal distribution.  You should also check that the variance estimates for beta is close to the variance of the corresponding simulated betas.  You can also refit the alternative, more flexible model, and check the likelihood ratio distribution in the simulations.
Comment: Thank you very much! Wrt to data dredging, I was referring to the act of trying to fit many variables with restricted forms, not just one, without evaluating properly if the form should be the same in both schools. I'm not sure if that was clear in my question.

Wrt estimation of $\beta_{new}$ I just thought this was done by regular MLE like any other case - that is - when separating the big school and the little school. Anyway, I appreciate the explanation of the estimation procedure! Thank you!
Comment: should the definition of $\beta_{new}$ be the inverse of the fraction above? also, what you mean by non-linear GLM confuses me a bit to be honest
Comment: You are right - it should be inverted.  With regards to non-linear GLM, you can't write the predictor in the form $\eta_i=x_i^T\beta $ for some *known* vector $x_i $ and parameter vector $\beta $.  In terms of the hypothesis testing - the likelihood ratio test can incorporate testing multiple constraints simultaneously.  So you are not doing multiple tests - just one.  If it fails, then you can look at which components are driving the failed test.  Not data dredging, but providing some insight into a large and complex test (by breaking into smaller pieces).


Calibration of an individual-based model of an epidemic

Question: I am currently developing an individual-based (or agent-based) mathematical model (IBM) of an epidemic. I want to calibrate the transmission parameters in my IBM to match empirical data (epidemic curve time series) using least-squares. Suppose I have an epidemic curve that looks like this  and this epidemic curve is based on a population of 60,000,000 (roughly the population of England). The peak incidence of the epidemic from this graph are in week 8: 9,600 cases. This gives 0.016% of the total population.
In my IBM I am only looking to simulate a population of 10,000. If I were to calibrate my transmission parameters so that my IBM output matches the epidemic curve in the attached figure, I am looking at a peak incidence of 0.016% in week 8 which, in a population of 10,000 people is just 1.6 people. This proportion is far too small to sustain an epidemic in a population of 10,000.
I presume there is something wrong with my approach. What would be the best way to calibrate an IBM to check that model output matches empirical data?
Comment: You may want to indicate if they are incidence cases or total cases. If they are incidence cases you will have more than 1.6 people to work with?
Comment: These are incidence cases i.e. they are the total number of new cases each week. How would I have >1.6? Could you elaborate please? Thanks.
Answer: Technically, if your IBM treats individuals as discrete units, you won't even have 1.6 individual - you will have 2, maybe 1, individual.
A couple notes about your problem:

It's not self-evident that 1.6 individuals per week is too few to sustain an epidemic.
This is the problem with scaling down large population incidence estimates. If possible, you should look for smaller district/county/etc. level data to get an idea of what the dynamics are in smaller populations.
This is why, if you look at epidemic curves on those scales, they're often much noisier.

Fundamentally, smaller populations have noisier dynamics governed more by stochasticity than any underlying epidemic dynamics. This doesn't mean your approach is wrong. Just that the outcome of your approach isn't clean. Those are two very different things.


[Flutter]How to download video to app, and make it accessible only through the app (Similarly to Youtube/Netflix)

Question: i'm fairly new to Flutter and is currently working on a course app that requires downloading the videos to the app.
The downloaded video will only be accessible through the app just like Youtube and Netflix, and will be hidden/encrypted from gallery. Would greatly appreciate if someone if someone could point me in the right direction in building this feature.
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: On iOS and Android your app has it's own isolated folder for storing documents. Items stored there are not intended to be accessible to the user outside of your app. This folder isn't scanned by the Gallery or accessible to other apps on the device. (However, with a little effort a user can access the files so this is not a complete solution where security is an concern. You would need to add encryption if you didn't, say, want a motivated user to copy the video file to a PC and be able to play it.)
the path_provider plugin gives your Flutter app common file locations on a device. The private app folder location is retrieved with getApplicationDocumentsDirectory()

"Download video" is a vague requirement. Most video on the internet (Netflix, Youtube) is provided via HLS or DASH for streaming, which you do download but the video is split up into many files- sometimes thousands of files for a single video. The dart:http package is likely what you're going to want to use to get/download the files (unless the video files aren't available via HTTP/HTTPS, then you'll need a different transport-specific library, like FTP, RTSP, etc.)


ng-click not working inside of directive's template

Question: I am beginner to angular custom directive. I just render two html template based on the controllers scope value using custom directive. After rendering the html ng-click="myclick()" event not working for both templates.
view.html

Template

Template Rendering
app.run(function ($templateCache) {
        $templateCache.put(
            'tmpl-doc-list-wrapper', jQuery('#tmpl-doc-list-wrapper').html());
    });

My Directive
app.directive('docListWrapper', ['$timeout', function ($timeout) {
        return {
            restrict: 'C',
            priority: 500,
            replace: true,
            templateUrl: 'tmpl-doc-list-wrapper',
            scope: { docs: '=docs'},
            link: function (scope, element, attrs) {
            }
        };
    }])

Controllers
app.controller('ctrl1', function ($scope, $interval) {
    $scope.docs = [{"doc":"http://google.com","stageName":"Project 1"},
                        {"doc":"http://google.com","stageName":"Project 2"},
                        {"doc":"http://google.com","stageName":"Project 3"},
                        {"doc":"http://google.com","stageName":"Project 4"},
                        {"doc":"http://google.com","stageName":"Project 5"},
                        {"doc":"http://google.com","stageName":"Project 6"},
                        {"doc":"http://google.com","stageName":"Project 7"},
                        {"doc":"http://google.com","stageName":"Project 8"}];
    $scope.myclick = function(){
        alert('clicked me ')
    }
});

app.controller('ctrl2', function ($scope, $interval) {
    $scope.docs = [{"doc":"http://google.com","stageName":"Unit 1"},
                        {"doc":"http://google.com","stageName":"Unit 2"},
                        {"doc":"http://google.com","stageName":"Unit 3"},
                        {"doc":"http://google.com","stageName":"Unit 4"},
                        {"doc":"http://google.com","stageName":"Unit 5"},
                        {"doc":"http://google.com","stageName":"Unit 6"},
                        {"doc":"http://google.com","stageName":"Unit 7"},
                        {"doc":"http://google.com","stageName":"Unit 8"}];
    $scope.myclick = function(){
        alert('clicked me ')
    }
});

Answer: $scope.myclick = function(){
    alert('clicked me ')
}

is in your controller, but your directive is isolate scope, so you either you need to pass myclick via scope : {myclick: "&"} or you use directive controller method to define myclick.
Comment: The right answer :) @sanman read about isolated scopes of angular for more information, to really understand angular, this is a key point...
Comment: @sanman: how are you passing these values to docListWrapper can you show me that...
Comment: Read this stackoverflow, you would get better idea... check whether your directive docListWrapper is getting those two values passed from your html where you are using it... http://stackoverflow.com/questions/36455124/angular-js-directive-and-restrict-option
Comment: @Thalaivar app.directive('docListWrapper', ['$timeout', function ($timeout) {
        return {
            restrict: 'C',
            priority: 500,
            replace: true,
            templateUrl: 'tmpl-doc-list-wrapper',
            scope: { docs: '=docs', myclick: "&"},
            link: function (scope, element, attrs) {
            }
        };
    }]). I tried this but not working
Comment:

 You need to pass it from here....
Comment: @Thalaivar : How do pass parameter value in myclick() function?. I want to pass $index value. so i wrote myclick($index) but i got undefined value when clicked.
Answer: You need to use the injected scope to define both data and functions in your controller:
Scope.myclick = function(){
    alert('clicked me ')
}

should be
$scope.myclick = function(){
    alert('clicked me ')
}

Answer: Use:
onclick="angular.element(this).scope().myclick()"

Comment: `angular.element` will only work if `debugInfo` is available. It might fail in production.


error: Error -3 while decompressing data: incorrect header check

Question: My web scraping code shown here gives the following error:

Error -3 while decompressing data: incorrect header check

Why, and how can I fix it?
import urllib.request
import zipfile
import pandas as pd
from bs4 import BeautifulSoup
import requests
import os
head = {'Accept-Encoding': 'gzip'}
BHAVCOPY_URL = "https://www.bseindia.com/markets/MarketInfo/BhavCopy.aspx"
html = requests.get(BHAVCOPY_URL, headers=head)

Answer: In [36]:  headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gec
    ...: ko) Chrome/83.0.4103.97 Safari/537.36"}

In [37]: import urllib.request
    ...: import zipfile
    ...: import pandas as pd
    ...: from bs4 import BeautifulSoup
    ...: import requests
    ...: import os
    ...:
    ...: BHAVCOPY_URL = "https://www.bseindia.com/markets/MarketInfo/BhavCopy.aspx"
    ...: html = requests.get(BHAVCOPY_URL, headers=headers)