Expected number of minimum of heads and tails

Question: Flip a fair coin $n$ times. Let $H$ denote the number of heads and $T$ the number of tails. What is $\mathbb{E}[\min(H,T)]$?
We know that $\mathbb{E}[H]=\mathbb{E}[T]=n/2$, and that $H$ and $T$ are distributed according to a binomial distribution, which has mean $n/2$ and variance $n/4$. Also, $T=n-H$ always. How can we find $\mathbb{E}[\min(H,n-H)]$?
Comment: @A.S. I don't see a symmetry argument that would give $n/4$.
Comment: @A.S. I doubt $E(\max-\min)=n/2$ is true.. it is unlikely for the number of heads and tails to be far apart.
Comment: Maybe $\min(x, y) = x - \max(x-y, 0)$ can somehow be used, although I wasn't able to get any closed-form solution with that.
Answer: Observe that $H$ has binomial distribution with parameters $n$ and $p=\frac12$.
So expectation $\mathbb E[\min(H,n-H)]$ is found by calculating:$$2^{-n}\sum_{k=0}^{n}\binom{n}{k}\min\left(k,n-k\right)$$

addendum:
Hints for special case: $n$ is odd:
$$\sum_{k=0}^{2m+1}\binom{2m+1}{k}\min\left(k,2m+1-k\right)=2\sum_{k=1}^{m}\binom{2m+1}{k}k=2\left(2m+1\right)\sum_{k=1}^{m}\binom{2m}{k-1}$$
and:
$$2\sum_{k=1}^{m}\binom{2m}{k-1}=2\sum_{k=0}^{m-1}\binom{2m}{k}=\sum_{k=0}^{2m}\binom{2m}{k}-\binom{2m}{m}=2^{2m}-\binom{2m}{m}$$
Do check me on mistakes, though. This stuff is slippery.

closed form for odd $n$:$$n\left[\frac{1}{2}-\binom{n-1}{\frac{1}{2}n-\frac{1}{2}}2^{-n}\right]$$
closed form for even $n$:$$n\left[\frac{1}{2}-\binom{n}{\frac{1}{2}n}2^{-n-1}\right]$$
Comment: @JPCF Well, that sounds reasonable to me. the number of tails and heads will not be too far from eachother.
Comment: So the sum is roughly twice the sum $\binom{n}{0}0+\binom{n}{1}1+\ldots+\binom{n}{n/2}n/2$. Is there a closed form for this sum? It doesn't remind me of any binomial identity.
Comment: I have added something that might help.
Comment: See also http://math.stackexchange.com/questions/1134962/expectation-of-half-of-a-binomial-distribution
Comment: @drhab I tried plugging $n=20000$ to both the closed form and the equation in mathematica... both gave me very big numbers.: `n ((1/2) - ((Binomial[n, (1/2) n])*2^(-n - 1)))` and  `(2^(-n))*Sum[Binomial[n, i]*Min[i, n - i], {i, n}]`
Comment: @JPCF What number then? It is evident that it cannote exceed $\frac12\times20000=10000$.
Comment: @drhab sorry, I'm new to Mathematica too, so I forgot to use N[]. The value is $E[min(H,n-H)]=9943.58$
Comment: @drhab why $\mathbb{E}[\min(H,n−H)]$ is not taken directly to be $\frac{n}{2}$ instead of posing a formula?
Comment: @JPCF Simply because $\mathbb E[\min(H,n-H)]\neq\frac{n}2$. It is definitely smaller.
Answer: Given natural $\text{n}$, it suffices to show that $$\sum_{h\ =\ 0}^{\text{n}}\ \text{min}\left(h,\text{n}-h\right)\cdot\binom{\text{n}}{h}\ =\ \text{n}\cdot\left(2^{\text{n}-1}-\binom{\text{n}-1}{\left\lfloor\tfrac{\text{n}}{2}\right\rfloor}\right)$$
(note the minor typo in the accepted answer). The claim follows from a counting argument:
\begin{align*}
    \sum_{h\ \colon\ \text{n}+1} \text{min}\left(h,\text{n}-h\right)\cdot\binom{\text{n}}{h}\ &=\ \sum_{h\ \colon\ \text{n}+1} \sum_{\substack{H\ \subseteq\ \text{n} \\ \left|H\right|\ =\ h}}\ \sum_{\substack{i\ \colon\ \text{n} \\ i\ \colon\ H \iff \left|H\right|\ \leq\ \tfrac{\text{n}}{2}}}\ 1\\
    &=\ \sum_{H\ \subseteq\ \text{n}} \sum_{\substack{i\ \colon\ \text{n} \\ i\ \colon\ H \iff \left|H\right|\ \leq\ \tfrac{\text{n}}{2}}}\ 1\\
    &=\ \sum_{i\ \colon\ n} \sum_{\substack{H\ \subseteq\ \text{n} \\ i\ \colon\ H \iff \left|H\right|\ \leq\ \tfrac{\text{n}}{2}}}\ 1\\
    &=\ \sum_{i\ \colon\ \text{n}}\ \left(\sum_{\substack{H\ \subseteq\ \text{n} \\ i\ \colon\ H\ \land\ \left|H\right|\ \leq\ \tfrac{\text{n}}{2}}}\ 1\ +\ \sum_{\substack{H\ \subseteq\ \text{n} \\ i\ \not\colon\ H\ \land\ \left|H\right|\ >\ \tfrac{\text{n}}{2}}}\ 1\right)\\
    &=\ \sum_{i\ \colon\ \text{n}}\ \left(\sum_{\substack{H\ \subseteq\ \text{n}\setminus\left\{i\right\} \\ \left|H\right|\ \leq\ \tfrac{\text{n}}{2}-1}}\ 1\ +\ \sum_{\substack{H\ \subseteq\ \text{n}\setminus\left\{i\right\} \\ \left|H\right|\ >\ \tfrac{\text{n}}{2}}}\ 1\right)\\
    &=\ \sum_{i\ \colon\ \text{n}}\ \sum_{\substack{H\ \subseteq\ \text{n}\setminus\left\{i\right\} \\ \left|H\right|\ \neq\ \left\lfloor\tfrac{\text{n}}{2}\right\rfloor}}\ 1\\
    &=\ \boxed{\text{n}\cdot\left(2^{\text{n}-1}-\binom{\text{n}-1}{\left\lfloor\tfrac{\text{n}}{2}\right\rfloor}\right)}
\end{align*}
Where "$\text{n}$" is doubly interpreted as the natural it names and as the set $\left\{0,\dots,\text{n}-1\right\}$ and "$\colon$" serves as shorthand for "$\in$". $\blacksquare$
(If one carefully considers what each sum above is actually computing, I think they'll agree that there's essentially no algebraic manipulation involved despite the argument's presentation.)


How can i select the div from CSS?

Question: I want to select the div of following order:
div3,div4
div7,div8
div11,div12
div15,div16
and so on....

I was wondering, how can i achieve this order by nth child property of CSS?
Please help!!!
Comment: What is your HTML structure? Do you have classes on these div's? Also can we change your HTML structure to make it work better?
Answer: Without knowing your structure it's hard to be definitive but the nth-of-type selectors can help here.
div:nth-of-type(4n+3) {  /* every 4th div starting at 3 */
  background: red;
}
div:nth-of-type(4n+4) {  /* every 4th div starting at 4 */
  background:blue;
}

JSfiddle Demo
Comment: Just establish a base styling and it will apply to the rest automatically - http://jsfiddle.net/Paulie_D/3suyy9cu/
Answer: Use following:
div:nth-child(4n-1){} /* for 3,7,11,15... */

div:nth-child(4n){} /* for 4,8,12,16... */

Snippet Below:

div:nth-child(4n-1){
    background: red;
}
div:nth-child(4n){
    background: green;
}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Comment: Nice..I hadn't considered doing it that way.
Answer: In CSS,
div:nth-child(4n+3),
div:nth-child(4n+4){
   /*do something*/
}

Comment: Doesn't the "n" variable have to go first? As in "(4n+3)", not "(3+4n)". Also you're combining both selectors into one style list, not separating them. I didn't downvote you btw

How can i select the div from CSS?


A problem in a metric space involving limits

Question: Let $(E,d)$ be a metric space, $A,B\subseteq E$ and $a\in A$. If $A$ is compact and $B$ closed and I find a sequence $b_n$ in $B$ so that $d(a,b_n)\rightarrow 0 $, is there any way to conclude that $a \in B$?
Answer: $d(a,b_n) \to 0$ means $b_n \to a$. Since $B$ is closed $a \in B$.
Comment: But $b_n \rightarrow a$ implies $a$ is a limit point of $B$? Why?
Comment: If $b_n=a$ for some $n$ then it is obvious that $a=b_n \in B$. Otherwise, $a$ is a limit point.


Try to attach to a process in debug mode fails

Question: I have 2 solutions. Solution1 output type is exe and solution2 output type is class library. I open both the solutions in separate VS2008 editors.
Debug solution1 by clicking on F5. Now the solution1.exe is running. In the solution2 click on Debug and Attach to process. Select Solution1.exe for attaching.
I get the error as "Unable to attach to the process. A debugger is already attached.". May i know what is the issue and how can I come out this?
Comment: I have edited your title. Please see, "[Should questions include "tags" in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not".
Answer: This is happened because proces can have only one debugger attached like error says.
You can start your program without debuger (in vs start without debuging) and then attach debbuger from solution2, if pdb files are correct this should work.
Comment: Do I have any option of debugging both the solutions together?
Comment: unfortunately no.. if it's in separate solutions.


the form is always valid in symfony2

Question: I have a form with this validation:
# ITW/UserBundle/Resources/config/validation.yml

ITW\UserBundle\Entity\User:
    properties:
        name:
            - NotBlank: ~
            - Length: { min: 800 }

And i'm checking the form like this:
// ITW/UserBundle/Controller/UserController.php

    $entity = new User();
    $form = $this->createForm(new UserType(), $entity);

    $form->handleRequest($request);

    if ($form->isValid()) {
        echo "valid!";
    }

and in config.yml the validation is:
validation:      { enabled: true }

But while I'm submitting the form with empty name field , the $form->isValid() is always returning True !!!
I can't figure out what is wrong!
I'm sure that validation.yml is loading properly (as when I use invalid field name symfony gives exception)
Where is the problem?

Symfony version is 2.5.6 & I also tried with 2.5.5
I also tried with getters constraint target for field name and got the same result.

My UserType is:
namespace ITW\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use ITW\UserBundle\Entity\User;

class UserType extends AbstractType
{
    public function __construct(){}

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('name','text',array('required'  => true,'label'=>'name'))
        ->add('family','text',array('required'  => true,'label'=>'family'))
        ->add('tels','collection', array('required'  => false,'prototype'=>true,'type'=> 'text','allow_add'=>true,'delete_empty'=>true,'label'=>'Tel'))
        ->add('username','text',array('required'  => true,'label'=>'username'))
        ->add('password','password',array('required'  => true,'label'=>'password'));

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ITW\UserBundle\Entity\User'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'itw_userbundle_user';
    }
}

Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/63892/discussion-between-chausser-and-4r1y4n).
Comment: Accorded to [Symfony2 doc](http://symfony.com/doc/current/book/validation.html#configuration), Do you have this ? `validation: { enable_annotations: true }` in framework section of your `app/config/config.yml` ?
Comment: @AlexandreL. No as I'm not using `annotations` i'm using `validation.yml` ; anyway I have also tested with `annotations` & it fails too ; please check 3 last lines of my question
Comment: @Chausser: version 2.5.6
Comment: Have you tried with Validator (`$validator = $this->get('validator');`) ?
Comment: @AlexandreL. yes and it gives empty error too
Comment: @Chausser: still it is valid!!
Comment: What does your UserType look like?
Comment: @Chausser, I added `UserType` class to the question.
Comment: how are you submitting the form without a name if the name field is required?
Comment: I added `{'attr': {'novalidate': 'novalidate'}}` to the form but I also tried to set `required` to false and got same result
Comment: very strange, im using 2.5.6 and duplicated your setup and my validation works fine. Do you have any services that hook the validator? Or could otherwise interfere with validation?
Answer: Just for clarification, configuration validation is enabled by default if you haven't removed section form from your config.yml file.
framework:
    form: ~

Comment: Problem solved with the help of @Chausser ; the chat link is at the end of comments; Changing whitespace control of error theme solved it!!! (why?!)

the form is always valid in symfony2


Set ping_timeout with ssl on Flask-ScoketIO

Question: I´m trying to run flask-socketIO + Gevent with this config:
App.py
if __name__ == "__main__":
    socketio.run(
        flask_app,
        host='127.0.0.1',
        port=5000,
        ping_timeout =  10 * 60 * 1000,
        keyfile='key.pem',
        certfile='cert.pem',
    )

But I get this error:
File "C:\Users\XXXXXXXXXXX\anaconda3\envs\atrio\lib\site-packages\gevent\server.py", line 233, in wrap_socket_and_handle
    with _closing_socket(self.wrap_socket(client_socket, **self.ssl_args)) as ssl_socket:
TypeError: wrap_socket() got an unexpected keyword argument 'ping_timeout'

Is there any other way to send change ping_timeout value?
Answer: You are mixing the options that apply to the web server with the options that apply to Socket.IO.
The ping_interval applies to Socket.IO. You can pass it when you create your SocketIO() object, or if you prefer, in the socketio.init_app() call.
Side note: ping_interval values are given in seconds, not milliseconds. Also, for 99+% of applications the default value is the optimal one, so I recommend that you don't change it.


After term not significant difference-in-differences

Question: I ran a difference-in-differences model and I have an interpretation issue. My difference between treated and control is not significant before and after. In the same time, my interaction term is significant. How should I interpret these results? Given that the difference is not significant after does it mean I cannot make any conclusions?
Comment: If the interaction term is significant then you interpret that, interpreting main effects is no longer relevant at this point.
Comment: Could you add your model in the Question?
Answer: Difference-in-difference equation is:
$$Y_{i,t} = \beta_0 1(i \in treated) + \gamma_t T_t +  \delta 1(i \in treated)  * T2 +\epsilon_{i,t} $$
where $1(i \in treated) $ is the group specific effect, $T_t$ are the time fixed-effects, and T2 is the dummy for all the time periods of the treatments; hence $\delta$, the coefficient in front of the interaction term, is the coefficient of interest.
If I understand well, the coefficient in front of G2 is non significant. It means that, outside of the period of interest, there is no significant difference between your treated and control. This is neither necessary nor sufficient, but it is encouraging regarding the fact that your control group is a good control group.
What matters for your research question is whether $\delta$ is significant.
Comment: Based on the model you gave, could you write 4 $E(Y)$ for 4 different combinations of treatment and time, i.e., (treatment, time 0), (treatment, time 1), (control, time 0) and (control, time 1)?
Comment: (control, time 0): $\gamma_0$
(control, time 7): $\gamma_7$ (let us say that treatment start for instance at time 7.
(treatment, time0): $\beta_0 + \gamma_0$
(treatment, time 7): $\beta_0 + \gamma_7 + \delta$


Are asynchronous javascript HTTP requests sent before or after the main stack completes

Question: assume the following:
http.get('mycoolwebsite.com/somecontent', function(){
    console.log('printed');
}

doSomeReallyIntensive100Hourwork();

I understand that we will see the word 'printed' printed on the console after 100 hours.
The questions:
Does javascript delay the request after 100 hours and then execute the callback or does it send out a request immediately and schedule the callback to print later? Basically, do we immediately notice the network request or not?
Comment: Where is reference to "100 hours" derived from?
Comment: Network request will be fired right away because it's asynchronous (read about event loops). But even if there's a response ready to be printed it will be printed after that heavy function will finish its execution because console.log printing and this heavy function are doing the job on the same thread. Until `doSomeReallyIntensive100Hourwork` is finished the thread is blocked.
Comment: Thank you for your answer @jimmyweb.
Comment: @guest271314 it's the example function above.
Comment: Run this ->   (function(){
 console.log("initial Request");
 setTimeout((e)=>console.log("callback"), 0)
})();
(function(){
 let a = 1;
  while(a < 1000000000){a++}
 console.log("finished loop")
})()
//
 initial Request
 finished loop
 callback
Answer: The request is initiated immediately, and the response will possibly also have arrived, but your get callback function will be triggered by an event in the event queue which only gets processed in the next task.
From mdn on XMLHttpRequest.send(), the method that is executed under the hood of the http.get method:

The XMLHttpRequest.send() method sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.

Note the last part. See also the WHATWG standards, section 4.5.6:

The send(body) method must run these steps:
10.4.1 Wait until either req's done flag is set or

the timeout attribute value number of milliseconds has passed since these subsubsteps started
while timeout attribute value is not zero.

... so the method does wait to make sure the request has been sent (or a timeout occurred).
Here is a demo with an HTTP call to a service that answers after a 2 second server-sided wait. You can launch it in two ways: with or without the intensive work.
When using the option to not do the work, the response comes back about 2 seconds after the click. If using the other option (with the work), then the work is done after three seconds and the response is processed immediately afterwards (have some patience after clicking):

function work() {
    // Be busy for 3 seconds
    var until = performance.now() + 3000;
    while (performance.now() < until);
    console.log('hard work done');
}

function test(work) {
    $.get("http://httpstat.us/200?sleep=2000", function() {
        console.log('response processed');
    });
    if (work) work();
}

$('#without').click(test.bind(null, null));
$('#with').click(test.bind(null, work));

<button id="with">Request with 3 secs of work</button>
<button id="without">Reguest without that work</button>
Comment: Is there anything in the specs that *requires* the request to be initiated immediately? I'd think that after calling the XHR `send()` method, it's really out of our control what happens in the browser with it. E.g. DOM rendering waits until after the hard work is finished as well.
Comment: @Bergi, as I understand it 10.4 is not about waiting for the response (which indeed would make it behave as a synchronous request) but about the successful submission of the request itself. At least the mdn article seems to claim the sending happens before the JS call returns (but mdn is of course not the final authority)
Comment: I added some references, @Bergi.
Comment: Thanks, but it doesn't actually wait for 10.4 (or else all requests would be synchronous): "*Run these subsubsteps [in parallel](https://html.spec.whatwg.org/multipage/infrastructure.html#in-parallel):*".
Comment: I think it's 10.4 "*Fetch `req`"* that is actually sending the request (and MDN is right). That's the last step that happens synchronously, then `send` returns. The substeps about waiting for the response will happen in parallel, and lead to asynchronous events.
Comment: Yes that is also how I understood it.
Comment: @trincot, thank you for your answer. It is really informative. I believe that the main idea here is that once javascript hits the request line, it does trigger the browser/server to do something in a process that is *outside* of javascript. The external process will get the information and makes its way back and notify javascript and then javascript will get back to the results when no script is being executed. Am I on the right path here?
Comment: My understanding is that JavaScript will block briefly while the request is being sent (which on the lower TCP level [involves several steps](http://blog.catchpoint.com/2010/09/17/anatomyhttp/)), but once the HTTP send operation was performed (by the browser stack), the JS engine will continue its code execution. The browser internals will be monitoring the response (probably in parallel with JS execution) and as soon as that response is detected, an event will be injected in the JS queue. The JS engine will only process the event queue when its current task has finished.
Answer:
do we immediately notice the network request or not?

That's up to the browser. JS will immediately tell the browser that it should execute the following request, but it's up to the browser to decide wether it has the capacity to immediately start this request or wether to queue it untill there are ressources available.
Then, eventually the request is sent, the response is there, and the browser will notify JS that the request is done, and pass the recieved data. Then JS, as soon as JS is idle*, it will call the callback-function.
JS is single-threaded. It can't run two pieces of code at once, and it won't interrupt some other code to run your callback-function. It will call it as soon as there is no other pending Javascript to run.


Custom layout for a custom keypad

Question: I don't know if I'm doing it the wrong way but here's what I want to do :
I've designed a simple keypad with 12 buttons (3 columns, 4 rows) and I'd like to make it standard. I mean in any of my layouts I'd like to just write
<my.own.Keypad>
  ....
</my.own.Keypad>

And the Keypad take care of setting the 12 buttons and everything.
I think I have to extend an Layout but I'm not sure. I couldn't find any help on the Web.
My main problem is that I don't know if it's the good approach !
Please give me any keywords or hints that could put me on the good way !
Thanks a lot,
Julian
Answer: You can do it like this.

Make a saperate layout which having your layout with 12 button.

suppose the name of the layout xml file is keypad.xml

now in any other layout where ever you want your keypad layout do this
< include
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      layout="@layout/keypad" />

this will include your keypad layout to any layout you want.
Let me know if it is helpful for you
Comment: That's almost what I need ! I also need to implement some code behind the keypad (like OnCLickListeners, etc.), I think I might do it with a custom class that I link to the layout in my Activity.

I thought that I could do it in one shot with the XML part and the Java part already linked together. I don't know if I'm clear and I think that I don't understand Android enough for writing it down. Anyway, that was helpful, thanks a lot !
Answer: You can do it in both the ways what ever suits you. here is an example
the first code of sample is for your activity
Button keypad1_button = (Button) findViewById(R.id.key1_button);

keypad1_button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myMethod(v);
    }
});

//your method which should invoke on button press event
public void  myMethod(View v) {
    // write your logic here
}

the second way is you directly write it in your xml file to invoke the myMethod(v)
here is the code:
in yout keypad.xml layout suppose you have a button
< Button
                        android:id="@+id/key1_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="KEY 1"
                        android:onClick="myMethod"
                        />

both of this methods will work. Try it

Custom layout for a custom keypad


aws cli version 2 install - "command not found" error

Question: I am beginner to aws, i installed aws cli v2 on my linux machine using-
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

After the install if i run aws --version i get
"Command 'aws' not found,"
my path has usr/local/bin
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

If i do
$ sudo /usr/local/bin/aws --version
aws-cli/2.5.6 Python/3.9.11 Linux/5.4.0-107-generic exe/x86_64.ubuntu.20 prompt/off

it works fine.
I added
export PATH=/usr/local/bin:$PATH

to my .profile and ran . ~/.profile as well. But no luck.
Please help me.
Comment: could be a permission issue. What's the permission of `/usr/local/bin/aws`?
Comment: lrwxrwxrwx 1 root   root         37 Apr 17 11:07 aws -> /usr/local/aws-cli/v2/current/bin/aws
lrwxrwxrwx 1 root   root         47 Apr 17 11:07 aws_completer -> /usr/local/aws-cli/v2/current/bin/aws_completer
Answer: OP Here. What worked for me was
sudo chmod -R 755 /usr/local/aws-cli

Don't know why AWS bundler could not do it.


Touching muted strings with picking hand

Question: When I move across strings quickly (e.g. on arpeggios), I can feel bumping lightly into muted strings. For example when I inside-pick E and A, I will start with an upstroke on E and then slightly touch E again on the way down to A. I manage to mute the string of course, so there's no sound coming from it - but I'm wondering if its a sign that my technique is broken.
So I guess my general question is: When proficient guitarists move quickly across strings, are they constantly touching muted strings because it's unavoidable on higher speeds, or are they actually managing to only touch the strings they're playing? I can't tell from just watching videos. If its the latter then I have to go back to much lower bpm and start practicing again.
I'm fairly new to guitar and have no one to correct me, so that's why I'm asking here. Thanks a lot!
Comment: If you are playing the bottom E, then playing the A, why would you pick upwards for the E - you're going the wrong way. Unless I misunderstood.
Comment: @Tim I'm using inside picking if I'm not mistaken. So I pick E from the "inside" and then A as well. Inside here refers to the space between E and A. I can try to do it with outside picking, but I'd have to learn that specifically. The reason I learned it that way is because it aligns with the pattern I practice (triples where I'm going back and forth, starting with a down stroke on E)
Comment: Try resting your palm (nearest the pinky) on the bridge, almost as if playing muted. If your hand is floating instead, you're going to catch all sorts that you don't want. By anchoring, you may have more control. And use a small amount of picksticking out to pluck.
Answer: The rule is: if it sounds good, it's good.
I recall in one of his Youtube videos Troy Grady, who analyzed playing technique using slow motion camera, found, that when changing strings quickly one may hit two strings instead of one, and if the "wrong" string is muted, it doesn't affect the sound negatively.
His videos are a bit lengthy and I can't find that specific one right now, but it might might be interesting for you to watch them.
I don't want to discourage you from working on precision, and also such details may matter less or more depending on music style, context, guitar tone etc, but it's good to be aware that the mechanics of playing the instrument may differ from the most simple and naive imagination of it.
Answer: Proficient guitarists do NOT touch the string on the way down.  What mean by that is, with practice you will be able to avoid hitting the E with a down stroke on the way to the A in an inside picking pattern.
I never heard of anyone settling for that.  It's sloppy technique and anyone trying to play correctly will take the time to get it right.  All you need to do is practice.  Techniques are not magic.  Muted or not you will hear it.  If it's muted you wont hear a note but you'll hear the click and that's not what you want.
Comment: That technique actually works very well when playing octaves - mute the string in between. Wes seemed to do it quite well...
Comment: I don't think that's what the OP was referring to, but you are correct.  For chords etc we need to, but for fast alternate picking runs, even string skipping I would refrain.
Answer: So since the answers here are kind of contradicting, I've talked to other people and here's my takeaway so far:
Allthough I'm not supposed to bump into muted strings, at my level of experience I'm not gonna be able to avoid this at higher tempo. I still should practice with precision on lower speed, but also get a feel for faster runs and accept that it won't be perfect. Over time, my technique will improve eventually.
So I guess both sides are correct: Don't settle for sloppy technique, but also don't shy away from stretching into unknown territory with a certain degree of slopyness for a while.


Link href para id div

Question: Bom sei que conseguimos fazer links direcionando o click href para um id da pagina utilizando #.

#content1, #content2, #content3, #content4 {
  height: 50vh;
  border: 1px solid red;
}
 CONTEUDO 1
 CONTEUDO 2
 CONTEUDO 3
 CONTEUDO 4

CONTEUDO 1 TEXTO

CONTEUDO 2 TEXTO

CONTEUDO 3 TEXTO

CONTEUDO 4 TEXTO

Desta forma sempre que se clica ele está indo para o top 0 px, teria alguma forma de mandar ele para um top diferente, porque dependendo do que tiver no topo, ele irá cortar um pedaço do texto.
Então o ideal seria mudar este top 0, por exemplo para top 5, cara click no link ele leva para o top - 5.
Teria alguma forma de produzir isso ?
Comment: @LeAndrade de boa, não é uma técnica muito elegante, mas resolve... Tmj JS tb é opção rss, ainda mais se for sem jQuery =)
Comment: Ou você dexia um padding-top maior nos elementos com CSS ou você utiliza Javascript(jQuery).
Comment: @LeAndrade não necessariamente... com CSS e jeitinho da pra resolver
Comment: Então tava pensando aqui, realmente tem mesmo @hugocsl. Acho até que no caso dele seria melhor só CSS mesmo. Posta aí, se não resolver pra ele eu posto uma com Js.
Comment: @hugocsl Jóia man.
Answer: Tudo bem que essa não é uma forma muito "elegante", mas pode resolver apenas com CSS.
A técnica consiste em criar um elemento de 1px e cor transparente que vai funcionar como uma ancora oculta, com o position: absolute vc vai tirar esse elemento do fluxo da página e ele não vai interferir nos outros elementos. Então a ancora será nesse elemento oculto que está 50px antes do conteúdo que vc quer chamar quando clica no link, mudando esse valor de px vc define onde a ancora deve parar.
OBS: Deixei comentado no código onde vc define a altura em que a ancora deve parar antes do topo da página
Segue um exemplo prático para vc entender melhor:

/* casso queira abilitar um scroll suave durante a rolagem de tela
html {
    overflow-y: scroll;
    scroll-behavior: smooth;
} */
body {
    min-height: 2000px;
}

.content1 {
    height: 50vh;
    border: 1px solid red;
}
#content1, #content2, #content3, #content4  {
    position: absolute;
    width: 1px;
    height: 1px;
    left: 0;
    margin-top: -50px; /* esse valor varia de acordo com a altura do seu Header, se ele tiver 200px de altura coloque aqui -220px por exemplo */
    background-color: transparent;
    z-index: -1;
}
 CONTEUDO 1
 CONTEUDO 2
 CONTEUDO 3
 CONTEUDO 4

CONTEUDO 1 TEXTO

CONTEUDO 2 TEXTO

CONTEUDO 3 TEXTO

CONTEUDO 4 TEXTO

Comment: Exatamente o que pereciso.
Comment: @RenanRodrigues massa jovem, essa técnica é até bem usada, apesar de não seu tão elegante como falei... :D
Comment: A questão é a propriedade CSS que não é tão suportada pelos navegadores: https://caniuse.com/#search=scroll-behavior
Comment: @DiegoSouza sim Diegão, mas essa propriedade foi apenas um *plus* pra resposta, na verdade ela não tem nada a ver com a solução para a ancoragem. De qualquer forma deixei comentado essa propriedade no CSS, agora ela não faz mais parte da resposta... Se o autor quiser usar basta ele descomentar quando for usar.
Comment: É. Então, é que essa propriedade dá o efeito que o JavaScript faria no caso de browsers mais antigos. O JS poderia server de fallback para o efeito de rolagem suave, caso a propriedade não funcione.
Comment: @DiegoSouza com certeza, fazer um JS como fallback seria o correto mesmo. Mas como não estava dentro do escopo da pergunta é melhor nem usar nada de smooth scroll, vou deixar isso para outra resposta rss
Answer: Só sei de um jeito fazendo com Javascript. Estou usando jQuery abaixo para facilitar.

$('.anchor').on('click', function(event){

   event.preventDefault();

   var section  = $(this).attr('href');
   var top      = $(section).offset().top - 35;

   $('html').scrollTop(top);
});
.content1{
    height: 400px;
    background-color: #000;
    color: #FFF;
    margin-top: 10px;
}

 CONTEUDO 1
 CONTEUDO 2
 CONTEUDO 3
 CONTEUDO 4

CONTEUDO 1 TEXTO

CONTEUDO 2 TEXTO

CONTEUDO 3 TEXTO

CONTEUDO 4 TEXTO

Comment: Diego, isso aí está errado. Não é o que ele queria. Acredito que ao invés de + 5 é: - 5.
Comment: Exato, ele tem que parar aparecendo uma parte da div anterior como o @JoãoPedroSchmitz mencionou
Comment: Então é só trocar o operador e o valor, gente.

Link href para id div


Style to dynamically created elements

Question: I am trying to do something like this:
Suppose before the page is loaded, the structure of page is like this:

div1

div2

div3

showmore

Now I am using jQuery and overriding the href of the links like this
$('document').ready(function(){
    $('.divlink').attr('href','www.facebook.com');
});

So after the loading, the page the will be like this.

div1

div2

div3

showmore

It's OK till now.
Now when someone will click on the showmore link, the next three items will be appended to maindiv. This link will be deleted and a new showmore link will be created after the all six divs. The overall page will be like this now:

div1

div2

div3

div1

div2

div3

showmore

That all this functionality is standard means I can't do anything will all this. I can only write some jQuery code to override the href of links. Due to my jQuery onready event of the document, the href of only the first three elements will be overridden. But I want to override the href for all the links that will be generated on clicking the showmore button also.
Is there a method to do so?
(This is only one case that I explained to you. I also want to change some more CSS. Is there a method by which I can change all the things?)
Comment: Does the next 3 link will have the same href  value ?
Comment: Are you not allowed to modify the `somefunctiontoloadmoreitems()` function?
Comment: does this really matters??
Comment: yes i cant modify somefunctionloadmoreitems()
Answer: Just write it in some other function
function somefunctiontoloadmoreitems()
{
  $('.divlink').attr('href','www.facebook.com');
}

Tell if this you wanted? I am not sure.
function appendvalues(href, classname)
{
   var maindiv = document.getElementById("maindiv").childNodes;
   for(var i=0; i<maindiv.length; i++)
   {
      maindiv[i].setAttribute("href",href);
      maindiv[i].setAttribute("class",classname);
   }

}

Try to implement this in your code.
Comment: No this is not what i want. please read the question again. thanks.
Comment: ok you want a parametrized function which append to main div in with passed class and href?
Comment: i want to apply some css to elements. problem is that by ready method i can apply that css only to those elements which are present already not to those which are creating dynamically. i want to add that css to dynamically created elements.
Comment: How you want to give css and class name then?
Answer: Edited as per your request, now runs every second for the duration of 10 seconds, after clicking the 'showmore' link.
A more 'elegant' solution would be to stop the interval when the new elements are added, by comparing the count of the elements in the set every cycle run.
var modify_links_cycle = 0;
var modify_links_interval = null;

$('.maindiv').on('click', '.showmore', function() {
  clearInterval(modify_links_interval);
  modify_links_interval = setInterval(function() {
    // your modifications to the links
    $('.maindiv .divlink').attr('href', 'http://www.facebook.com');
    // /end
    modify_links_cycle++;
    if (modify_links_cycle === 9) {
      clearInterval(modify_links_interval);
    }
  }, 1000);
});

Comment: this is not a single case i have to override some more settings also.
Comment: so please tell me any method so that all the css and other things of dynamically generated elements will also be change.
Comment: Can you modify somefunctiontoloadmoreitems?
Comment: Does that function load the extra items via an AJAX call?
Comment: i think it dont. it loads only these divs and append them here.
Comment: I modified my solution, please see if it answers your needs, somehow at least.
Comment: i am already doing the same thing buddy. but the problem is that if the net speed of user is slow then what will happen?? :)
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/35221/discussion-between-sachin-kadian-and-timenomad)
Comment: i think i can run it every second for next 10 seconds.. :)
Comment: can you provide me the code so that i can repeat it every second for next 10 seconds?

Style to dynamically created elements


Creating a Pivot Table in Pandas (SqlAlchemy)

Question: I am trying to create a pandas dataframe that combines all children into one row
class Parent(Base):
  __tablename__ = 'parent'
  id = Column(Integer, primary_key=True)
  name = Column(String())
  class = Column(String())

  all_distance = relationship('Distance', back_populates='parent')
  all_weight = relationship('Weight', back_populates='parent')

class Distance(Base):
  __tablename__ = 'distance'
  id = Column(Integer, primary_key=True)
  distance = Column(String())
  finished = Column(String())

  parent_id = Column(Integer, ForeignKey('parent.id'))
  parent = relationship('Parent', back_populates='all_distance')

class Weight(Base):
  __tablename__ = 'weight'
  id = Column(Integer, primary_key=True)
  weight = Column(String())
  height = Column(String())

  parent_id = Column(Integer, ForeignKey('parent.id'))
  parent = relationship('Parent', back_populates='all_weight')

Tables with some data:
parent
ID | Name | Class
1  | Joe  | Paladin
2  | Ron  | Mage
3  | Sara | Knight

distance
ID | distance | finished | parent_id
1  | 2 miles  | yes      | 1
2  | 3 miles  | yes      | 1
3  | 1 miles  | yes      | 1
4  | 10 miles | no       | 2

weight
ID | Weight | height | parent_id
1  | 5 lbs  | 5'3    | 1
2  | 10 lbs | 5'5    | 2

The goal is to create a pandas dataframe that would look like this:
1 | Joe  | Paladin | 2 miles  | yes  | 3 miles | yes  | 1 miles | yes  | 5lbs  | 5'3
2 | Ron  | Mage    | 10 miles | no   | None    | None | None    | None | 10lbs | 5'5
3 | Sara | Knight  | None     | None | None    | None | None    | None | None  | None

How would I do that?
I've gotten somewhat close
df = pd.read(db_session.query(Parent, Distance, Weight).join(Distance).join(Weight).statement, db_session.bind)

which gives me the data frame of everything joined together.
list(df.columns.values)

['id', 'name', 'class', 'id', 'distance', 'finished', 'id', 'weight', 'height']

How do I prevent the same column headers? ie - id is now 3 times
However when I try to make a pivot table:
df.pivot(index="id") it is returning an error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 5194, in pivot
    return pivot(self, index=index, columns=columns, values=values)
  File "/anaconda2/lib/python2.7/site-packages/pandas/core/reshape/reshape.py", line 400, in pivot
    indexed = self.set_index(cols, append=append)
  File "/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 3909, in set_index
    level = frame[col]._values
  File "/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 2688, in __getitem__
    return self._getitem_column(key)
  File "/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 2698, in _getitem_column
    result = self._constructor(self._data.get(key))
  File "/anaconda2/lib/python2.7/site-packages/pandas/core/internals.py", line 4130, in get
    raise TypeError("cannot label index with a null key")
TypeError: cannot label index with a null key

Comment: Pandas pivoting is not related to SQLAlchemy. Since you have no issue with sourcing the joined data, consider removing class lines not directly needed for your question. Also, did you look into [`pivot_table`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html)?
Comment: I've just spent an hour trying to look into this for you.  Thanks for that!  But I was getting somewhere with pandas.merge().  It connects dataframes much like sql's join() functions.  Using Inner/out/left/right approaches.
Answer: you are trying to pass 'id' as index so the pivot fails. It should be:
df.pivot(df.index,"id")


Prove Inf A = 0 where set $A = \{m + n\omega: m + n\omega > 0, m, n \in \mathbb{Z}\}$, $\omega$ is a positive irrational number.

Question: I found a solution of this question but the solution seemingly showed that there is only $0$ in set $A$ and this is obviously impossible. Where I am wrong? And in the last part of this solution, it says $1 = m_0\alpha$. Is it because we can set $n = 0$, and $m = 1$, then $1$ is in $A$ and every member of $A$ is equal to some multiplication of $\alpha$?
Comment: The first sentence "inf A exists and is positive, i.e., $\inf A \geq 0$" is problematic, as "positive" is not the same as "greater than or equal to zero."  It just shows the writer is comfortable with awkward wordings.
Comment: Nice proof in your post. The conclusions in the proof are based on assumption $\alpha>0$ so is not true that $A$ consists of $0$ alone.
Comment: @Whocares It's a problem book in real analysis, by Asuman G. Aksoy, Mohamed A. Khamsi. Sorry for late.
Comment: (1) Where is the problem from?  (2) Is it easy enough to replace this image with the text itself? (3) Can these tags be improved upon?
Comment: Actually in every other language than English, positive means superior or equal to 0.
Comment: $\forall$ languages $\neq$ English? That seems like hyperbole... and also a good reason to use another word in this forum. "Non Negative" is the unambiguous way English speaking mathematicians have resolved this.
Comment: May I ask which book is this from?
Answer: Given $x\in\mathbb{R}$, we denote the largest integer that is not
greater than $x$ by $[x]$. That is, $[x]=\max\{n\in\mathbb{Z}\mid n\leq x\}$.
Define a function $\theta:\mathbb{R}\rightarrow[0,1)$ by $\theta(x)=x-[x]$.
For each $n\in\mathbb{N}$, define $x_{n}=\theta(n\omega)$. Firstly,
observe that $x_{m}\neq x_{n}$ whenever $m\neq n$. (For, suppose
the contrary that there exist $m\neq n$ such that $x_{m}=x_{n}$.
Then $m\omega=N_{1}+x_{m}$ and $n\omega=N_{2}+x_{n}$ for some integers
$N_{1}$and $N_{2}$. Now we have: $m\omega-N_{1}=x_{m}=x_{n}=n\omega-N_{2}$
which implies $\omega=\frac{N_{1}-N_{2}}{m-n}\in\mathbb{Q}$, which
is a contradiction)
Let $\varepsilon>0$ be given. Since the sequence $(x_{n})_{n}$ is
bounded, by Bolzano-Weierstrass Theorem, it has a convergent subsequence.
In particular, there exist distinct $n_{1},n_{2}\in\mathbb{N}$ such
that $0<|x_{n_{1}}-x_{n_{2}}|<\varepsilon$. Without loss of generality,
we may assume that $x_{n_{1}}>x_{n_{2}}$ (otherwise, swap $x_{n_{1}}$
and $x_{n_{2}}$). Note that $x_{n_{1}}=n_{1}\omega-N_{1}$ and $x_{n_{2}}=n_{2}\omega-N_{2}$
for some integers $N_{1}$, $N_{2}$. Hence $x_{n_{1}}-x_{n_{2}}=(n_{1}-n_{2})\omega-(N_{1}-N_{2})\in A$.
This shows that $\inf A=0$.
Comment: Choose a convergent subsequence $(x_{n_{k}})_{k}$. Then there exists
$K$ such that $|x_{n_{k}}-x_{n_{l}}|<\varepsilon$ whenever $k,l\geq K$.
Choose distinct $k,l\geq K$. Then $n_{k}$ and $n_{l}$ will serve
as the integers $n_{1}$ and $n_{2}$ in my original proof.
Comment: Since $A$ is a subset of $[0,\infty)$, obviously $\inf A$ exists and $\inf A\geq 0$. The difficult part is to show that $\inf A=0$.
Comment: Thanks! Why there exist distinct $n_1, n_2 \in \mathbb{N}$ such that $ 0 < |x_{n1} -x_{n2}| < \varepsilon$?


Global convergence with Newton method for nonlinear systems

Question: Let $f:\mathbb{R}^2\rightarrow \mathbb{R}^2$ a function for which we seek a fixed point,
$$f:(x,y)\mapsto\begin{pmatrix}
-5x+2\sin x+2\cos y\\
-5y+2\sin y+2\cos x
\end{pmatrix}.
$$
I made a python program to solve this with the Newton's method $$X_{k+1}=X_k-(J_{X_k}f)^{-1}f(X_k)$$ and it worked with a random $x_0$ (so there maybe is global convergence).
How can I prove that in this case the Newton's method is globally convergent (or not) ?
Comment: You have $X_{k+1} = \phi(X_k)$ so it is sufficient to show that $||\phi|| < 1$ in  $\mathcal{R}^2$
Answer: So, thanks to Cesarea I was able to visualize the answer to my question (to calculate $||\phi ||$ was not really interesting by hand), and there is indeed a global convergence.


Change arguments in view

Question: I have a view with arguments in the page and attachment displays.
When I go to the view page, I see a list of arguments (links) because in "Action to take if argument is not present" I selected  "Summary, sorted ascending."
How do I sort arguments (in this case is term) by weight? I don't see any option to do this. Where can I change the query "ORDER BY term ASC" to "ORDER BY weight ASC" in code?
When I click an argument, I have another page with a list of arguments again, because I have an attachment. How do I only show the argument name I have clicked?
Answer: you are using drupal 6, or drupal 7?
If I understand well your questions:
you can change the query used to generate view results (Order BY, Where, etc) using query_alter hook. here one example: Making a field sortable in Views
About weight of arguments, I think that you can control order of precedence in 'rearrange' option:

If your question is related with weight of taxonomy terms, in your View settings > Add sort criteria > Taxonomy: Weight seems will be useful to sort according weight of each term:

regarding shows argument clicked, you can get argument from the current url easily using arg() http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/arg/7:
example URL: http://example.com/node/12345/edit
in this example
arg(0) is node
arg(1) is 12345
arg(2) is edit
here some experiences in Drupal forum to review, with or without using arg():
http://drupal.org/node/180589
http://drupal.org/node/283945
you can add a php code to get respective argument, for example using arg() in a view header or in a drupal php node/page/block:
<?php echo arg(0); ?> or <?php echo arg(1); ?> according your target argument.
I hope information be useful.
Comment: I think that you can use `query_alter` hook to review if you can alter the query according your needs. here is some guidance about what is `query_alter` hook http://drupal.org/node/1029634
Comment: i use drupal 6. about "weight of arguments, I think that you can control order of precedence in 'rearrange' option:" i see one "taxonomy:term" no term list to sort.
Comment: I have updated my answer with a comment about sorting results of your view, according weight of taxonomy terms.
Comment: thank u but it sort nodes, not arguments. i want to sort arguments (in this case taxonomy term) order by term weight.
Comment: then `query_alter` will be useful for you.

Change arguments in view


WiX built-in WixUI Dialog Sets have horizontal lines that are just a little too short (picture included)

Question: I am creating an installer for my program using WiX (Windows Installer XML). I have used the following code to begin using the built-in WixUI Dialog Sets:
<code><Product ...>
  <UIRef Id="WixUI_FeatureTree" />
</Product>
</code>
This, however, creates a dialog set with horizontal lines that are just a little bit too short on every dialog as shown here:
Wix Horizontal Lines Too Short http://img156.imageshack.us/img156/2421/wixhorizontallinestoosh.png
I understand that I could create my own set of dialogs to use instead by using software such as SharpSetup and WixEdit but I like the dialogs that WiX creates and only want to make a very small change to them.
Is my best option to download the WiX source code and try to modify it? Is there a more simple solution? Perhaps I should contact the developers of WiX to list it as a bug? Maybe they like it that way though. I however think it looks out of place and would like to change it.
I am using the latest weekly release of WiX 3.5.
Answer: Seems like a reasonable bug to open. I never noticed before. A fix will require updating the original source.
Comment: Thanks Rob. I have listed this as a bug.
Comment: @Coder7862396: I've noticed this bug is still present in the newest WiX (version Jan 31 2011). Could you please provide a link to your bug report, so I can see its status? Thanks.
Comment: @Paya Here's the link (I know it's been 10 years but the bug still exists): https://github.com/wixtoolset/issues/issues/2691


Smoothing a 2-by-2 contingency table

Question: I am trying to implement a system for automatic document categorization, where each document of a corpus belongs to some class. I define the following contingency table for every class C and every word W:
$\begin{array}{c|cc}
& W & \bar{W}\\
\hline
C & \frac{nb\_docs(C,W)}{nb\_docs}  & \frac{nb\_docs(C,\bar{W})}{nb\_docs}\\
\bar{C} & \frac{nb\_docs(\bar{C},W)}{nb\_docs} & \frac{nb\_docs(\bar{C},\bar{W})}{nb\_docs}\\
\end{array}$
where $nb\_docs$ is the total number of documents in the corpus, $nb\_docs(C,W)$ is the number of documents of class C that contains the word $W$, $nb\_docs(C,\bar{W})$ is the number of documents of class C that does NOT contain $W$, and so on.
I need to smooth this table to avoid zero values, ideally something simple similarly to Laplace smoothing (i.e., add-one smoothing) while keeping well-defined probabilities/normalized frequencies.
I can't figure out how to do that... Any idea?
Edit: My goal is to extract the most "important" terms to reduce the dimensionality of the space during classification. There are many functions to identify those important terms, some being undefined with zero probabilities. Undefined values could be simply ignored but there should be some way to deal with this :)
Comment: Why do you need to avoid zeros?
Comment: Question edited :)
Answer: You might see Jeff Simonoff's 1996 book "Smoothing Methods in Statistics" (Springer) that devotes a chapter to this subject:
In effect, one 'shrinks' the empirical cell probabilities to the 'overall' or 'uniform' cell probabilities using kernel weighting for discrete outcomes. This is designed exactly for the sparse settings you envision. To avoid the zeros you only require a very minimal amount of smoothing by the way.
Hope this helps!

Smoothing a 2-by-2 contingency table


How can I replace all instances of * in a dataframe?

Question: I'd like to remove all instances of '*' from my dataframe, pitcher, specifically in the 'Name' column.
     Rk     Name                  Team    IP   R
887  888.0  Huascar Ynoa\ynoahu01  ATL   3.0   6
888  889.0  Alex Young*\youngal01  ARI  34.2  10

I've tried the snippets below, as well as anything I could find only (regex=True and other variations). Also tried using a for loop on the strings individually, but each time I print either the new Series/Dataframe, the * are still there
pitcher = pitcher.replace('*', '')

pitcher['Name'] = pitcher['Name'].replace('*', '')

newdf = pd.DataFrame()
newdf['newname'] = pitcher['Name'].replace('*', '')

The simplest idea would be great. I'm sure there are many ways to do this.
Comment: Something like `pitcher['Name'].str.replace('*', '')`?
Answer: To replace '*' anywhere in the dataframe we'll first have to find all string columns and then replace the '*' there. Strings have the object type, so this will work in most trivial cases:
for c in pitcher.select_dtypes(['object']).columns:
    pitcher.loc[:,c] = pitcher.loc[:,c].str.replace('*','')

Please note that mixed type columns or other object type columns (dicts, lists etc.) are of object type too. In these cases we can use:
pitcher = pitcher.applymap(lambda x: x.replace('*','') if isinstance(x,str) else x)


uninitialized constant SessionsController ROR rails 4

Question: Hi I am beginner to Ruby on rails. I am trying to some experiments. I am trying to implement user login. I am not using any gem. I tried that in following way :
get "log_out" => "sessions#destroy", :as => "log_out"
  get "log_in" => "sessions#new", :as => "log_in"
  get "sign_up" => "users#new", :as => "sign_up"
  root :to => "users#new"
  resources :users
  resources :sessions

class SessionController < ApplicationController
  def new
  end

   def create
    user = User.authenticate(params[:email], params[:password])
    if user
      session[:user_id] = user.id
      redirect_to root_url, :notice => "Logged in!"
    else
      flash.now.alert = "Invalid email or password"
      render "new"
    end
  end

   def destroy
    session[:user_id] = nil
    redirect_to root_url, :notice => "Logged out!"
  end

end

when I tried to hit http://localhost:3000/log_in It showed
uninitialized constant SessionsController
routing error

Am I doing anything wrong? Need some Help. Thank you.
Answer: You have SessionController not SessionsController. Either change it to SessionsController or edit your routes as below.
get "log_out" => "session#destroy", :as => "log_out"
get "log_in" => "session#new", :as => "log_in"
get "sign_up" => "users#new", :as => "sign_up"
root :to => "users#new"
resources :users
resource :session

I suggest changing the SessionController to SessionsController.
IMP Note:
While changing SessionController to SessionsController, don't forget to change the file name to sessions_controller.rb


Access denied on admin/structure

Question: I have defined a new user role "Webmaster", and assigned it the permissions to administer forms, menu & menu items and taxonomy terms (all). Going to the admin/structure url still yields an "Access denied".
What permissions do I need set to allow my webmasters access to the admin/structure url?
Answer: The user needs the permission "Use the administration pages and help".
Then the user can access /admin and /admin/structure.
If the user has no other admin rights, the admin menus will be rather empty. They will fill up if you assign more permissions.

Access denied on admin/structure


Is there a way for a beginner in jazz to learn how to play tritone substitutions?

Question: Is there a way for a beginner in jazz to learn how to play tritone substitutions?
Or is this something that you should only try after you have played jazz for some time.
Comment: I think there is not enough data to answer this question. For instance, we do not know what instrument you are playing and whether you are having trouble with the concept, the application thereof to your particular instrument or both.
Comment: Are you asking what it is?  Where to apply it?  Or how to pay on a particular instrument?
Comment: I think answer is yes. It will help the beginner to understand the basic concept of a dominant chord and its substitution. Play from the chord or the associated dominant/altered scales. What is your actual "how to play" problem?
Comment: I think you should try researching what tritone substitutions are, and then of course playing/using them. The amount of time you've played jazz music shouldn't be a factor, but make sure you figure out what you're doing with them tritone subs. Experience helps a lot, though!
Comment: I don't understand what is not clear in this question ... The tts is a very simple and useful concept, and easier to apply than to understand.
Answer: Tritone substitutions are used instead of the preceding V chord to reach the next. As in G7>C, tts would be D♭7>C.
The point of them is that their 3rds and 7ths are swapped over. In the case above, G7 has B and F as 3 and 7, while the tts (D♭7) has F and B (actually C♭) as 3 and 7.
In jazz, it's often the case that chords are thinned out, and 3rds and 7ths are the only notes played. That actually falls right into your hands: play 3 and 7 (or 7 and 3!) and you're effectively doing it.
In order to find any tts, it's pretty straightforward: establish target chord (say C here). Tts is one semitone above that, so tts of G7 (the V of C) D♭7.
If it's on piano or guitar, you may want to include the other two notes, but bear in mind it works better if all those playing with you use the same tts. If they continue with the original V>I, it (really) won't (really) work well.
Answer: Forget jazz, you can do it in pop and rock just as well. Instead of a dominant 7th (or 9th or 13th etc) chord, play a 7th or 9th (or many other things) a tritone higher (or lower, it's the same thing).
Sometimes, all it takes to do a tritone substitution is to move the bass. The bass player can do it without consulting others.
A special case is when others (except the bass) are playing a completely symmetric chord like dim7. Then the bass can take the tritone step, and the chord stays the same, just with a different root.
Example: Bdim7/G - C.
Tritone-substituted it becomes: Bdim7/Db - C.
Comment: or opposite: the bass plays the circle of 5ths while the chords pass chromatic down step.
Answer: The simplest way to play tritone substitution is training the V7 chords the chromatic scale down instead of the circle of fifths. Learn the circle of fifths:
B,E,A,D,G,C,F,E ....
Now play
B,Bb,A,Ab,G,Gb,F,E  (all chords 7b9)
you will see that each second chord (colored in right circle) is the tritonus substitution of a secondary dominant in the circle of 5ths (left).

The colored chords in the circle right (chromatic progression) are the tritone substitutions of the chords in the progression of fifths.
e.g.
F7 (FACEb) is substitution of B7 (BD#F#A)
adding b9 and flatting the 5th: F b9 b5 => B b9 b5 (because
F = b5 of B
A = 7 of B
Cb = B
Eb = D#
Gb = F#
FACbEbGb = BD#FAC
so the colored  V7 chords of the chromatic circle can be used as substitutions of the chords in the left circle - where all 5ths are secondary dominants.

Is there a way for a beginner in jazz to learn how to play tritone substitutions.

So you first have to know how to build triads, seventh and ninth chords and to learn the circle of 5ths if you are a pianist.
A guitar player can play e.g. E, then play the barré E7 shape in fret vii (B7) and slide down fret by fret back to E.  (B7,Bb7,A7,Ab7,G7,F#,F7,E). But if he doesn't analyze the chords he will be playing without knowing what he's doing.
Comment: I do not really understand your answer.
Comment: Well, let's look at a song with the progression C-E-A-D-G-C (left circle o 5ths). When you look at  the circle on the right side you see C-E-Eb-D-Db-C (chromatic scale). Eb is trit.sub. of A, Db is t.s. of G.
Comment: Umm, wouldn't it be easier to just "look across" the circle of fifths (just draw a diameter between 2 opposing notes)? It seems overly complicated to me (am I missing something?). What of the other notes from the 1st progression in your example? C, E and D? They are not substituted in the 2nd one.
Comment: No. It makes sense to do so, but mind the fingering patterns you play on the instrument: semitone down is easier to imagine than *across the circle*.
Comment: In the beginning of your answer, you propose one "learn the circle of fifths". If one already has the progression of 12 notes memorised, what's so problematic about counting the 6th note from the one you need to substitute? It's equivalent to getting a note from "across the circle" (which might be even quicker for someone with a good visual memory - I wouldn't know for sure). Most woodwind/brass players don't have linear fingerings, so it's kind of pointless for us to think in semitones when it comes to fingerings. I understand your method now, but it still relies heavily on visuals, I think.
Comment: This is te simplest way? What about considering the target chord (call it C for now). The tts for the dominant (G7) is just one semitone above the target chord. Thus Db7 in this case. Tts to get to Eb? E7. Tts to get to G? Ab7. Simple!
Comment: @ Tim: 1. I never said it is the simplest way. 2. *Semitone above the target chord* is exactly what I mean by chromatic progression of (V7). I'm only explaining a chain of secondary (V7) but this includes the final V7-I of course.
Comment: @ Pyromonk: I don't agree. This is not primarily a visual approach, I just posted the circles to illustrate what I mean. It is a haptic-tactil technique as described by the E7 barré (sliding fret by fret lower). You can do the same on the keyboard or with any wind or brass instrument - without thinking or reflecting what you do, but this is not my aim.


How to display a solution with using timelimit in CPLEX for scheduling(CP)

Question: Now I am trying to get a solution within a specific time-limit in my code.
Actually, my problem(scheduling) is NP-hard.
It spends lots of time to get a solution or out of memory.
So, I set a time-limit in my code(60s) and I'd like to get a solution(scheduling) solved for 60s.
Is it possible?
If possible, please let me know.
Thank you, sir.
Answer: yes you can stop after a time limit
In OPL you would write
<code>execute {
        cp.param.timelimit = 60;
}
</code>
You have the same parameter for all APIs
Comment: Hi, if you use OPL and CPLEX , in the postprocess part you may print any results through writeln functions in execute blocks See https://www.ibm.com/developerworks/community/forums/html/topic?id=1fb27039-328b-48eb-8be0-b73cdfbd69c3
Comment: Sir, I used that code in my iteration mod file. But it doesn't give a solution(real schedule), but only give an Objective function value.

I mean, simply, I want to get a solution 'OP-value like 23.254", I want to get a solution schedule with decision variation like

[1 0 1 0 1 1 1 0]

Thank you, sir.
Comment: Additionally, it could be a little fundamental question,
if it is possible, why do we use a technique of heuristic for that kind of problem?

I mean, most of the timelimit solutions by MILP(CPLEX) better than a heuristic solution.

Thank you, sir.


What is the best interval size to consider in calculating the probabilities of a normally distributed sample?

Question: I have a sample of size 80 which is normally distributed. I want to calculate the probabilities on different intervals. Is there any way or method of finding the most optimum interval size?  Meaning that how should we know how many intervals should we consider between Min and Max of the sample?
Another question is should we remove outliers first and then make decisions about the number of intervals?
Answer: If you divide the domain into intervals separated by a standard deviation $\sigma$:

then you get 8 intervals separated by a commonly used statistical measure.
Comment: Thanks, this is really helpful.


Como fazer com que o menuItem (RadioButton) seja seleccionado de acordo com o tipo de mapa?

Question: Tenho um Fragment que dá erro sempre que eu inicio ele.
Ele gera o seguinte erro:
java.lang.NullPointerException: Attempt to invoke virtual method 'int com.google.android.gms.maps.GoogleMap.getMapType()' on a null object reference
        at mz.co.bm.bmtrack.MapFragment.onPrepareOptionsMenu(MapFragment.java:175)
        at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:2475)
        at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:3295)
        at android.support.v4.app.FragmentController.dispatchPrepareOptionsMenu(FragmentController.java:331)
        at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:480)
        at android.support.v7.view.WindowCallbackWrapper.onPreparePanel(WindowCallbackWrapper.java:98)
        at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onPreparePanel(AppCompatDelegateImplBase.java:359)
        at android.support.v7.view.WindowCallbackWrapper.onPreparePanel(WindowCallbackWrapper.java:98)
        at android.support.v7.app.ToolbarActionBar$ToolbarCallbackWrapper.onPreparePanel(ToolbarActionBar.java:522)
        at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:456)
        at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:57)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
        at android.view.Choreographer.doCallbacks(Choreographer.java:686)
        at android.view.Choreographer.doFrame(Choreographer.java:618)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Nesse código:

Mesmo colocando essas verificações no onCreateOptionMenu, gera o mesmo erro.
Esse erro é gerado quando clico sobre o Location na BottomNavigationView.
O Listener da BottomNavigation é a seguinte:
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {

                case R.id.btm_route:
                    // TODO

                    getSupportFragmentManager()
                            .beginTransaction()
                            .replace(R.id.fragment, new RotaFragment())
                            .commit();

                    return true;
                case R.id.btm_localizacao:
                    // TODO

                    getSupportFragmentManager()
                            .beginTransaction()
                            .replace(R.id.fragment, new MapFragment())
                            .commit();

                    return true;
                case R.id.btm_fuel:
                    // TODO

                    getSupportFragmentManager()
                            .beginTransaction()
                            .replace(R.id.fragment, new FuelFragment())
                            .commit();

                    return true;
            }
            return false;
        }

Comment: Você diz que dá erro quando inicia o Fragment mas depois diz que é quando clica no botão. Qual das duas é?
Comment: É quando clico no botão e, logo dá erro! Me desculpe pela confusão!
Comment: O erro indica que a variável `map` é nula.
Comment: É! Mas, ela foi incializada! Tanto que, quando eu inicio a app, ela abre normalmente, o problema é quando cliclo nesses botões! Não entendo o que está errado!
Comment: Adicione na pergunta o código completo relevante ao seu problema
Comment: Adicionei o Listener da BottomNavigationView, não sei ainda preciso adicionar mais alguma coisa.
Answer: Já consegui resolver.
Era só criar um método para verificar se o mapa é nulo e configurar o menu posteriormente.
public boolean isMapNull() {
     if (map != null) {
         return false;
     } else {
         return true;
     }
}

E colocar ele no onPrepareOptionMenu()
 @Override
 public void onPrepareOptionsMenu(Menu menu) {

     if (!isMapNull()) {

         terreno = menu.findItem(R.id.terreno_maptype);
         satelite = menu.findItem(R.id.satelite_maptype);
         hibrido = menu.findItem(R.id.hibrido_maptype);

         int t = GoogleMap.MAP_TYPE_TERRAIN;
         int s = GoogleMap.MAP_TYPE_SATELLITE;
         int h = GoogleMap.MAP_TYPE_HYBRID;

         if (map.getMapType() == t) {

             alterarTipoParaTerreno();
             terreno.setChecked(true);

         } else if (map.getMapType() == s) {

             alterarTipoParaSatelite();
             satelite.setChecked(true);

         } else if (map.getMapType() == h) {

             alterarTipoParaHibrido();
             hibrido.setChecked(true);
         }
     }

     super.onPrepareOptionsMenu(menu);
 }


Task under SYSTEM won't run Win Srv 2k8R2

Question: My company has a software that updates our installers on clients' servers. During the setup, a environment variable is created along with a task with the following lines:
Variable:
setx ccloud "C:\Capela\CCloud" /M

Obs.: the path used is the "install path" defined during the setup.
Task:
schtasks.exe /Create /RU SYSTEM /SC DAILY /TN CCloudUpdater /TR "cmd.exe /C C:\Capela\CCloud\ccloud-updater.bat" /ST 02:00 /F >

The bat file has the following arguments:
@echo off
cd /d "%CCLOUD%"
ccloud.exe cache -c
ccloud.exe logs -c
ccloud.exe installers -d ccloud --w
if exist "installers\ccloud\ccloud-setup.exe" (
    START /WAIT "CCloud Setup" "installers\ccloud\ccloud-setup.exe" /S
)
ccloud.exe auto -t -i -s
timeout 60 > nul
ccloud.exe auto -t -i -s
timeout 900 > nul
ccloud.exe auto -t -i -s

After running it, our softwares and services are downloaded and extracted to a folder. The packages are defined by an online manager.
However, there is ONE server (2k8R2, just like many others) that just can't read the variable, no matter what we do. The task runs as intended, but since the variable is somehow unavailable, it can't download the packages.
We tried using

echo "%ccloud%" > path.txt

inside the bat, the TXT returns only "" like that variable is undefined.
We don't know what else to do. Can anyone help me find out what's happening?
Comment: Does the server got a antivirus which block macro/script ? Please check your AV log. I used to have such difficulty with mcafee in the past, as it blocked the script to create variable.
Comment: Do you really need the environment variable?  Since the batch file itself is in the same folder that the environment variable points to, `cd /d %~dpn0` should work.
Comment: The `setx` command doesn't work reliably, by the way.  Not sure from your description whether or not that might be your problem, but FYI.
Comment: @HarryJohnston I just saw how to use %~dp0 and it should work, but we actually use the e.v for easy access to that folder. Not essential, but useful. Anyway, thank you for this!
Answer: A simple restart solved the problem. Apparently the OS didn't fully mapped it during setup, although it was recognized when manually calling from CMD.
We don't know why it worked on other servers without restarting, though.


Can you set SQL Server permissions from a Silverlight app?

Question: Is it possible to create a Silverlight application which can be used to provide a nice user interface for managing SQL Server permissions?
We want to create a simple admin app to allow certain users to create new users, disable old users, and manage specific permissions for those users, but we feel that SQL Server Management Studio is perhaps too complex.
Comment: You could use the free Express version of SSMS, its less daunting to look at and should be able to the basics.
Answer: In simple terms yes - every function you perform in management studio is executing SQL at the back end, and virtually all, if not all actions allow you to script out that SQL if you are unsure as to what the SQL syntax for a given action is.
SL will not make a direct connection to the SQL server, you will need to have the SL call a WCF web service which exposes methods / properties for the functionality you wish to implement.
Answer: I agree with Andrew but would add that your WCF service could make use of SMO to manage Logins, roles and permissions.   See http://msdn.microsoft.com/en-us/library/ms162175.aspx


Proving an estimate of Weyl

Question: I'm working through some problems of Fourier Analysis by Stein, Shakarchi and I got stuck trying to solve the following problem:

Let $S_N = \sum_{n=1}^N e^{2\pi i f(n)}$. Show that for $H\le N$, one has
$$|S_N|^2 \le c \frac NH \sum_{h=0}^H\,  \left|\,\sum_{n=1}^{N-h} e^{2\pi i(f(n+h)- f(n))} \right|$$
  for some constant $c>0$ independent of $N$, $H$, and $f$.

There is even a hint: Let $a_n = e^{2\pi if(n)}$ if $1\le n\le N$ and $0$ otherwise. Then write $H\;\sum_n a_n = \sum_{h=1}^H \sum_n a_{n+h}$ and apply the Cauchy-Schwarz inequality.
Well, I'm realy horrible at this stuff, but I'll write down at least a beginning
$$\begin{align}
|S_N|^2 &= \frac 1{H^2} \left| \sum_{h=1}^H \sum_n a_n \right|^2 \\
&\leq  \frac1H \sum_{h=1}^H \left|\sum_n a_{n+h} \right|^2 \\
&= \frac1H \sum_{h=1}^H \sum_{n,m} a_{n+h}\overline{a_{m+h}}
\end{align}$$
and after this I already get lost. =( (Of course, I have scribbed down much more than just this, but it all lead nowhere, so I won't expose you to that...)
I would really appreciate some help. Cheers!
Comment: I just have to say that your LaTeX looks like perl. Short, concise, impossible to decipher. (You were missing a | somewhere there. Also the *-environments don't exist here.
Comment: @AsafKaragila: I apologize if my edit overrode yours.
Comment: @Asaf: Sorry, normally others don't need (want?) to read my code, so I might have developed some bad habits there ^^. Thanks for correcting!
Answer: Here's a route to the solution. I tried to be detailed with the sums, so the computations get a little messy. By the way, this inequality is a form of van der Corput's Inequality. You can see more at Terry Tao's blog, but the version he talks about is a little less obviously related.
As for the computation, you have
$$
HS_N=H\sum_na_n=\sum_{k=1}^H\sum_na_{n+k}=\sum_n\sum_{k=1}^Ha_{n+k}.
$$
The inner sum vanishes except for $n$ in the range $1-H\leq n\leq N-1$. It follows by the Cauchy-Schwarz inequality that
$$\begin{align*}
H^2|S_N|^2
&=
\left|\sum_n\sum_{k=1}^Ha_{n+k}\right|^2\leq
(N+H-1)\sum_n\left|\sum_{k=1}^Ha_{n+k}\right|^2\\
&=
(N+H-1)\sum_n\sum_{k=1}^H\sum_{j=1}^Ha_{n+k}\overline{a}_{n+j}\\
&=
(N+H-1)\sum_{k=1}^H\sum_{j=1}^H\sum_na_{n+k}\overline{a}_{n+j}.
\end{align*}$$
To evaluate the sum, group the terms $a_{n+k}\overline{a}_{n+j}$ by the value of the difference $k-j$ (I've included a detailed computation below in case it's not clear what I mean). In the end, you'll find that
$$\begin{align*}
\sum_{k=1}^H\sum_{j=1}^H\sum_na_{n+k}\overline{a}_{n+j}
&=
H\sum_n|a_n|^2+
2\text{Re}\,\left(\sum_{h=1}^{H-1}(H-h)\sum_na_{n+h}\overline{a}_{n}\right)\\
&\leq
2\sum_{h=0}^{H-1}(H-h)\left|\sum_na_{n+h}\overline{a}_{n}\right|.
\end{align*}
$$
Combining everything from here (I've adjusted this to reflect @process91's comment), you get
$$
\begin{align*}
|S_N|^2&
\leq
2\left(\frac{N+H-1}{H}\right)\sum_{h=0}^{H-1}\left(1-\frac{h}{H}\right)\left|\sum_na_{n+h}\overline{a}_{n}\right|\\
&\leq 4\frac{N}{H}\sum_{h=0}^{H}\left|\sum_na_{n+h}\overline{a}_{n}\right|.
\end{align*}
$$
Now just delimit the above sum and insert $e^{2\pi i(f(n+h)-f(n))}$ for $a_{n+h}\overline{a}_n$ to get the inequality the book wants.

Here's a detailed computation of the sum I referenced above. Write
$$\begin{align*}
\sum_{k=1}^H\sum_{j=1}^H\sum_na_{n+k}\overline{a}_{n+j}
&=
\sum_{1\leq j\leq k\leq H}\sum_na_{n+k}\overline{a}_{n+j}\\
&\qquad +
\sum_{1\leq k<j\leq H}\sum_na_{n+k}\overline{a}_{n+j},
\end{align*}
$$
and observe that
$$
\begin{align*}
\sum_{1\leq j\leq k\leq H}\sum_na_{n+k}\overline{a}_{n+j}
&=
\sum_{1\leq j\leq k\leq H}\sum_na_{n+k-j}\overline{a}_{n}\\
&=
\sum_{0\leq k-j\leq H-j\leq H-1}\sum_na_{n+k-j}\overline{a}_n\\
&=
\sum_{0\leq h\leq H-j\leq H-1}\sum_na_{n+h}\overline{a}_n\\
&=
\sum_{h=0}^{H-1}\sum_{j=1}^{H-h}\sum_na_{n+h}\overline{a}_n\\
&=
\sum_{h=0}^{H-1}(H-h)\sum_na_{n+h}\overline{a}_n.
\end{align*}
$$
Similarly,
$$
\begin{align*}
\sum_{1\leq k<j\leq H}\sum_na_{n+k}\overline{a}_{n+j}
&=
\sum_{h=1}^{H-1}(H-h)\sum_na_n\overline{a}_{n+h}.
\end{align*}$$
So it follows that
$$\begin{align*}
\sum_{k=1}^H\sum_{j=1}^H\sum_na_{n+k}\overline{a}_{n+j}
&=
H\sum_n|a_n|^2+
2\text{Re}\,\left(\sum_{h=1}^{H-1}(H-h)\sum_na_{n+h}\overline{a}_{n}\right).
\end{align*}$$
Comment: Nice =). Thank you so much for taking the time to write up this clear and detailed answer! Also, thanks for the references.
Comment: @Sam My pleasure :)
Comment: Great answer, two comments - I think there is a small mistake on the second line after "Combining everything from here", the 2 should become a 4 otherwise I believe it is false. The other point is that getting the answer for $H-1$ is not quite enough to conclude it for $H$, instead we can use the following:
$$\begin{align*}
|S_N|^2&
\leq
2\left(\frac{N+H-1}{H}\right)
\sum_{h=0}^{H-1}\left(1-\frac{h}{H}\right)\left|\sum_n a_{n+h}\overline{a}_{n}\right|\\
&\leq 4\frac{N}{H}\sum_{h=0}^{H}\left|\sum_na_{n+h}\overline{a}_{n}\right|.
\end{align*}$$
Comment: @process91 Thank you for noticing that after all this time—I've now fixed the answer!

Proving an estimate of Weyl


Access VBA copyobject error

Question: I am trying to write a simple VBA in access that copies one table into another access Database and renames it.
Here is my code:
sub copy_table ()

    dim destDB as string
    destDB = "Y:\GDA_files\MI1.mdb"

    docmd.copyobject destDB, "Progress tracking 1", acTable= acDefault, "Progress tracking " & date

end sub

However I receive message

Run time error '2501':
The CopyObject action was cancelled

I have no idea why this error occurs.
Any ideas?
Answer:

DoCmd.CopyObject(DestinationDatabase, NewName, SourceObjectType, SourceObjectName)

You probably have mixed up the NewName and SourceObjectName parameters.
And acTable= acDefault makes no sense.
Try:
' this will sort table names chronologically
strNewName = "Progress tracking " & Format(Date(), "yyyy-mm-dd")

DoCmd.CopyObject destDB, strNewName, acTable, "Progress tracking 1"

Answer: Have you tried put table name between back quotes?

Table names can contain any valid characters (for example, spaces). If
  table names contain any characters except letters, numbers, and
  underscores, the name must be delimited by enclosing it in back quotes
  (`).

in https://learn.microsoft.com/en-us/sql/odbc/microsoft/table-name-limitations

Access VBA copyobject error


Is this a correct solution to the linear congruence?

Question: I want to solve this linear congruence:
$$2x \equiv 5 \pmod{9}$$
Backward substitution:
$$9 = 4 \cdot 2 + 1$$
$$4(-2) + 9 = 1$$
Therefore, the inverse is: $-2$
Now multiply the linear congruence with $-2$
$$(2)(-2)x \equiv (-2)5 \pmod{9}$$
$$x \equiv -10 \pmod{9}$$
So:
$$x = 8 + 9k$$ for an integer $k$
EDIT:
With the answers given below, the solution is:
Therefore, the inverse is: $-4$
Now multiply the linear congruence with $-4$
$$(2)(-4)x \equiv (-4)5 \pmod{9}$$
$$x \equiv -20 \pmod{9}$$
$$x \equiv 7 \pmod{9}$$
So:
$$x = 7 + 9k$$ for an integer $k$
Comment: With $x=8$ we get $2x=16\equiv 7 \pmod{9}$, so something went wrong in your solution. This is why it's good to check solutions.
Comment: You were trying to find the inverse of $2$, not $4$.
Answer: No, here goes something wrong. The inverse of 2 is 5 rather than -2.
You should compute the inverse by the Extended Euclidean algorithm or perhaps you can guess it in a simple case with small numbers like this one.
Comment: My mistake is that the inverse should be -4 and not -2, right?
Comment: @Julia Yes $-4 \equiv 5 \mod 9$, so -4 is an inverse.
Comment: Thanks, I updated my question to include the correct solution. Is it correct now? @wythagoras
Answer: $$
2x\equiv 5\pmod 9 \Longrightarrow 2x=9n + 5, n\in\mathbb Z
$$
We can solve linear diophantine equation now, but LHS divides by $2$; hence,
$$
0\equiv 9n + 5 \equiv 1 \cdot n + 1\pmod 2\Longrightarrow n = 2m + 1, m\in\mathbb Z
$$
So,
$$
2x=9(2m+1)+5\Longrightarrow x = 9m + 7
$$
If you know that $2^{-1}\equiv 5 \pmod 9$, then it's much more simpler:
$$
5\cdot 2x\equiv 25\equiv 7\pmod 9\Longrightarrow x\equiv 7\pmod 9
$$


Prove that this Markov chain is irreducible if and only if there exist infinitely many $k\geq0$ such that $q_{k}>0$

Question: We consider the Markov chain $\left(X_{n}\right)_{n\geq0}$
  on $\mathbb{N}$
  whose transition matrix $P=\left(p_{k,l}\right)_{k,l\geq0}$
  given by
$$\forall k\in\mathbb{N}
  p_{k,k-1}=q_{k},p_{k,k+1}=p_{k}$$
with $p_{k}+q_{k}=1$
  and $p_{k}>0$
  for any $k\geq0$
 .
Prove that this Markov chain is irreducible if and only if there exist infinitely many $k\geq0$
  such that $q_{k}>0$
 .
How to prove it? I need some hints. Thanks a lot.
Comment: @AleZok A more urgent task than embarking the OP in the considerations in your comment, seems to be to mention that the result does not hold.
Comment: Suppose by contradiction that there is a finite number of indices $k$ such that $q_k>0$. Let $k^*$ be the biggest of these indices. What happens if my Markov chain jumps to state $k^*+1$?
Comment: $p_{k^*+1,k^*}=0$ right?
Answer: This is false. The chain is irreducible only if all $q_k\gt0$. If $q_j=0$, there is no way to get from state $j$ to states $\lt j$.
Comment: The answer starts by "This is false" because the author of the answer claims that the result the question asks to prove ("this Markov chain is irreducible if and only if there exist infinitely many k≥0 such that qk>0.") does not hold. (Needless to say, the author of the answer is right.)
Comment: @user109584: But I did! Please explain what part of the argument in my answer isn't clear.
Comment: @user109584: Look, I've replied three times now that I gave the reason in the answer. I'm not going to reply to further questions before you point out what part of that you find unclear or unconvincing, and why.
Comment: @user109584: If it does, you should throw that book away. "Infinitely many" does not mean "all". (Also, even if the book is bad, your interpretation seems unlikely since "infinitely many" is preceded in the question by "there exist", and "there exist all" makes no sense.)
Comment: Funny to see user @joriki *almost* raising their voice... This requires some. :-)
Comment: Why do you talk "This is false"?
Comment: @user109584: I don't understand the question. I justified my claim that your statement is false in the remainder of the answer.
Comment: Do you mean the statement "if" is false?
Comment: @user109584: Yes, you could put it that way.
Comment: Why? I think it's true. Can you give me a counterexample?
Comment: I mean if the chain is irreducible then there exist infinitely many k≥0 such that qk>0 .
Comment: You think that's false right?
Comment: @user109584: No, that's correct. That's the "only if" part. You summarized correctly above that I'm saying that the "if" part is false.
Comment: If there exist infinitely many k≥0 such that qk>0 then the chain is irreducible, I think this statement is also true. Why do you think it's false?
Comment: I agree with you that The chain is irreducible only if all qk>0. But the "if" part, I think it's also true.
Comment: @user109584: That's an immediate contradiction. For those two statements to be consistent, "infinitely many" would have to imply "all". It clearly doesn't.
Comment: I think by "infinitely many" the question means "all".


Basic question: Is a subversion server necessary in this scenario?

Question: Right now:

I have a few personal software projects I develop (just me, and on just one PC)
extensively use TortoiseSVN for version-control
run CollabNet Subversion Server on the same PC

Is there really any advantage in having a server instead of just pointing to the repository directory?
For example: instead of commiting to svn://localhost/projectname, I could just commit to C:/development/projectname and get away with it.
Could someone advice me on what the best practice is in this kind of senario?
Answer: No, in that situation it is not necessary to run a Subversion server. You can tell TortoiseSVN to access the repository files directly (using the file:// protocol) and everything will work fine.
However, using a separate server will make your life easier if you:

want to move your Subversion server to another machine
start using a laptop or netbook separate from your server machine
want to share your work with anybody else
Comment: @jay: If you run have a Subversion server on a separate machine, you would need some kind of network connection to that machine in order to check in files. Note that this limits the times you can do Subversion operations to those times when you're connected to a network (eg. if you have a laptop and you're on the train, you probably can't access your server). This is the exact problem that DVCS like Git and Mercurial are designed to solve.
Comment: Awesome! Just out of curiosity (possibly another question) but what would be involved with putting the repository files back to a server?
Answer: Yes it is - for the purpose of redundancy, not collaboration. You don't want to lose both your active working directory and also your repository. However, you could always institute some other form of backup procedure.
Answer: I'm a one-man show as well, with a network of computers in my home/office. I had to set up a Windows 2008 server anyway, so I put Subversion on it, and use Tortoise on my laptop client.
I like having the master on a separate machine, makes for better backup. Also, I'm prepared in case a second programmer comes to work in the shop.
Answer: You will probably find it simpler to use Mercurial or another DVCS.
Answer: I don't think it's necessary to run a server. As you wrote, you can as well commit to your local repository using a file:// url.
If I remember correctly, using a file:// URL is not recommended if your repository is stored on a network share and/or accessed by more than one users. But as long as you are working alone and locally, there is no problem.
Should you ever have the need to move the repository to a server computer, that should not be a problem (just move the repository and point svnserve to it).
Answer: Setting up the server is trivial and you only do it once.  So why not?
But it's not 100% necessary.  Why bother?
I think it doesn't really matter.  Just pick one and stick with it.
Personally, I have CollabNet running as a service on my Windows development machine at home.  I commit all my own stuff and back up the repository on a regular basis.
I don't see what the benefit would be to not use the server.  Set it up, use it faithfully, back it up, forget about it.
For me it's about practice and developing habits.  I'd recommend that you do it the same way all the time.
Answer: Although I would now recommend a DVCS such as git or Mercurial, I always used a server.  This way I could access my repository from my computer at school as well as from the desktop which hosted the repository.
Answer: Personally, I use Mercurial, and free hosting at bitbucket.  I don't feel very secure if data exists in only one place.
(Only mentioning Mercurial as they offer free, private hosting for non-open-sorce work)


Docker container connection in macvlan network

Question: I have a CentOS 7 Hyper-V VM running on Windows Server 2012 R2 that acts as my Docker host.  I'm trying to place my containers in a LAN with other VMs by using Docker's macvlan network driver.
Network:
docker create network -d macvlan --subnet=10.1.0.0/24 --gateway=10.1.0.1 -o parent=eth0 macnet

Container:
docker run --net=macnet -it --ip=10.1.0.2 ubuntu bash

From the container, I'm unable to ping the gateway.  I did tcpdump -n -i eth0 on the Docker host and saw arp requests from the container but no replies.  The Docker host VM's NIC is an external network virtual switch which I suspect is the cause.  Is there some configuration that I'm missing?
Answer: You need enable promiscuous mode in Hyper-V.
Hyper-V > VM > Settings > NIC (click plus) > ADVANCED FEATURE > Enable MAC Address Spoofing


How to exploit periodicity to reduce noise of a signal?

Question: 100 periods have been collected from a 3 dimensional periodic signal. The wavelength slightly varies. The noise of the wavelength follows Gaussian distribution with zero mean. A good estimate of the wavelength is known, that is not an issue here. The noise of the amplitude may not be Gaussian and may be contaminated with outliers.
How can I compute a single period that approximates 'best' all of the collected 100 periods?
I have no idea how time-series models work. Are they prepared for varying wavelengths? Can they handle non-smooth true signals? If a time-series model is fitted, can I compute a 'best estimate' for a single period? How?
A related question is this. Speed is not an issue in my case. Processing is done off-line, after all periods have been collected.
Origin of the problem: I am measuring acceleration during human steps at 200 Hz. After that I am trying to double integrate the data to get the vertical displacement of the center of gravity. Of course the noise introduces a HUGE error when you integrate twice. I would like to exploit periodicity to reduce this noise. Here is a crude graph of the actual data (y: acceleration in g, x: time in second) of 6 steps corresponding to 3 periods (1 left and 1 right step is a period):

My interest is now purely theoretical, as http://jap.physiology.org/content/39/1/174.abstract gives a pretty good recipe what to do. It does not address periodicity.
Note: I have asked this question on stackoverflow but it seems to be off-topic there.
Answer: I'm not sure I totally understand what would be best, but I believe that looking at Dynamic Linear Models, State Space modeling, and the Kalman Filter would be helpful. In R, the package dlm is fairly accessible.
Edit: Describe DLM's simply, eh? One explanation I've seen is that DLMs are regression where your coefficients are allowed to change with time. Doesn't really give me much intuition.
So, here is my I-realize-I-don't-understand-DLMs-well-enough-to-do-this-well-but-you-asked answer, which I hope others will correct as necessary. Let me use a situation that's similar to how they were invented...
Say you were controlling a remotely-piloted vehicle. You could summarize the vehicle's actual state (speed, direction, altitude, fuel, etc, etc) as a vector in a state space. You can't directly observe the actual state, but you do have sensors that observe linear combinations of the actual state, with some (gaussian) noise added in. That is, your sensors are not perfect.
Further, the vehicle has a program that determines how it changes states, as a linear combination of the current state, also with some (gaussian) noise. That is, your controls are not perfect.
Say you want to know the most likely and most accurate path possible for the vehicle -- that is, the states it actually went through: how it actually moved. What you observe is noisy, but you can use a Kalman filter on this system you model and the filter models the variances in the system and outputs the most likely actual states. At each time step, it forecasts what it believes the state will be, then observes what the sensors say, calculates the variances of the different parts, and comes up with a final estimate of the state as a weighted sum of the forecast and the sensor readings. Then the process is repeated for the next time step.
The whole concept is basically a continuous Hidden Markov Model, if you're familiar with those. The model is several equations which involve several matrices that are multiplied together, and you can add columns to the matrix to reflect trend, seasonal, and other types of components of the time series.
The R package dlm makes it particularly easy to define and combine components.
Comment: Thanks! Could you expand on the 'dynamic linear model'? In your own words to someone who has no idea about dlm. I did google it and found a bunch of PDFs but I would happy to read an explanation in plain English.
Comment: +1 I appreciate your efforts to answer my question. DLM does not seem to be the method I am looking for but it may be useful in one of my other projects. Thanks anyhow!
Comment: I'd recommend looking at http://en.wikipedia.org/wiki/Particle_filter and http://en.wikipedia.org/wiki/Kalman_filter and noting the similarity. If your noise is Gaussian, the DLM/Kalman approach will serve you well.
Comment: Thanks. As I write in the question "The noise of the amplitude may not be Gaussian and may be contaminated with outliers." Please give me some time to come up with more results, I am interested in closing this question by accepting an answer.
Comment: From what I've read, "Without the assumption of normality, uncorrelatedness of the disturbances is sufficient for the Kalman filter to yield optimal linear foreasts." The particle filter is more general though...
Answer: This video (especially the part starting at 23:20) describes the same problem you have with double integration, which amplifies low frequency noise to unbearable levels quickly. They solve the problem by sensor fusion, effectively using other sensors (like magnetic field sensors and gyroscopes) simultaneously to infer a more robust estimate of the acceleration coming from gravity alone and the acceleration coming from the movement of the sensor.
To help you with the drift from the double integration you could also try a particle filter to estimate the true position of the accelerometer over time.
There is an interesting Tech Talk about a more robust version of this idea.
Perhaps you could also use characteristic points in your time series as a kind of position anchor, e.g. if you can infer with some confidence the times when the pivot is lowest (or highest) and just assume a fixed height over ground for these times. Then, instead of an initial value problem resulting in onesided double integration, you would have a boundary value problem, where you can additionally integrate backwards from the next anchor position. This reduces the time where errors can grow down to half of a period.
Comment: There is also an [accompanying paper](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.65.2585&rep=rep1&type=pdf) for the particle filter talk
Comment: +1 and thanks for your answer. I know the first video by heart :) As for your idea in the last paragraph, they perform essentially the same approach in the paper "Force platforms as ergometers" I refer to just below the graph.
Answer: You may want to check out Functional Data Analysis, which permits characterization of functional (temporal) phenomena with noise in the wavelength, amplitude, etc.


What is the last nonzero digit at the end of 10!?

Question: What is the last nonzero digit at the end of $10!$ ? What is the last nonzero digit at the end
of $100!$ ? What is the last nonzero digit at the end of $1,000,000!$?
Is there a formula to find out the pattern?
Comment: @Dr.SonnhardGraubner :anyway, it is an interesting question, don't you think so? I doubt that is an homework, so why not enjoy the question?
Comment: The last digits of $100!$ are $\cdots 85210916864000000000000000000000000$.
Comment: what have you done so fare?
Comment: note that $$10!=3628800$$
Comment: http://learningroots.in/cat-and-omet/quant/last-non-zero-digit/
Answer: I'll demonstrate with $100!$. This is not so much a formula as it is an algorithm that works in $\operatorname{O}(\log(n))$ time for $n!$.
Let $n!!$ denote the product of all odd positive integers less than or equal to $n$.  Let $n\tilde{!!}$ denote the product of all odd positive integers less than or equal to $n$ that are not divisible by $5$.
The idea is to extract all powers of $5$ and $2$ from 1000!, and write it as $10^A2^BC$ with $C$ odd and not a multiple of $5$.  Then $A$ is the number of trailing zeros.  And whatever $2^BC$ is modulo $10$ is the preceding digit.  To that end, these two reduction formulas (which you should verify) are useful:
$$
\begin{align}
n! & = \left\lfloor\frac{n}{2}\right\rfloor! \times n!! \times 2^{ \lfloor\frac{n}{2}\rfloor}\\
n!! & = \left(2\left\lfloor\frac{n+5}{10}\right\rfloor-1\right)!! \times n\tilde{!!} \times 5^{\left\lfloor\frac{n+5}{10}\right\rfloor}\hspace{2pc}n\geq5
\end{align}
$$
The first of these is something you may have seen before.  The second is the result of trying to find a similar formula that excludes multiples of $5$.  A number of the form $n\tilde{!!}$ is even and not diviible by $5$, and is only important to us mod $10$, and its reduction rule is $$n\tilde{!!}\equiv (1\times3\times7\times9)^{\left\lfloor\frac{n}{10}\right\rfloor}\times\epsilon\equiv 9^{\left\lfloor\frac{n}{10}\right\rfloor}\times\epsilon$$ where $\epsilon$ is either $1$, $1(3)\equiv3$, $1(3)(7)\equiv1$ or $1(3)(7)(9)\equiv9$ depending on $n$.
We have:
$$
\begin{align}
 100! &\equiv 50!\times100!!\times2^{50}\\
 100! &\equiv 50!\times19!!\times100\tilde{!!}\times5^{10}\times2^{50}\\
 100! &\equiv 50!\times19!!\times9^{10}\times5^{10}\times2^{50}\\
 100! &\equiv 50!\times19!!\times5^{10}\times2^{50}\\
 100! &\equiv 50!\times3!!\times19\tilde{!!}\times5^2\times5^{10}\times2^{50}\\
 100! &\equiv 50!\times3!!\times9^{1}(1)(3)(7)(9)\times5^2\times5^{10}\times2^{50}\\
 100! &\equiv 50!\times3(1)\times1\times5^{12}\times2^{50}\\
 100! &\equiv 50!\times3\times5^{12}\times2^{50}\\
 100! &\equiv 25!\times50!!\times2^{25}\times3\times5^{12}\times2^{50}\\
 100! &\equiv 25!\times50!!\times3\times5^{12}\times2^{75}\\
 100! &\equiv 25!\times9!!\times50\tilde{!!}\times5^5\times3\times5^{12}\times2^{75}\\
 100! &\equiv 25!\times9!!\times9^5\times5^5\times3\times5^{12}\times2^{75}\\
 100! &\equiv 25!\times1(3)(5)(7)(9)\times9\times3\times5^{17}\times2^{75}\\
 100! &\equiv 25!\times3\times5^{18}\times2^{75}\\
 100! &\equiv 12!\times25!!\times2^{12}\times3\times5^{18}\times2^{75}\\
 100! &\equiv 12!\times25!!\times3\times5^{18}\times2^{87}\\
 100! &\equiv 12!\times5!!\times25\tilde{!!}\times5^3\times3\times5^{18}\times2^{87}\\
 100! &\equiv 12!\times1(3)(5)\times9^2(1)(3)\times3\times5^{21}\times2^{87}\\
 100! &\equiv 12!\times7\times5^{22}\times2^{87}\\
 100! &\equiv 1(2)(3)(4)(5)(2\cdot3)(7)(8)(9)(2\cdot5)(11)(4\cdot3)\times7\times5^{22}\times2^{87}\\
 100! &\equiv (3)(5)(3)(7)(9)(5)(11)(3)\times7\times5^{22}\times2^{97}\\
 100! &\equiv (3)(3)(7)(9)(11)(3)\times7\times5^{24}\times2^{97}\\
 100! &\equiv 7\times5^{24}\times2^{97}\\
 100! &\equiv 10^{24}\times7\times2^{73}\\
 100! &\equiv 10^{24}\times7\times2^{5\cdot14+3}\\
 100! &\equiv 10^{24}\times7\times2^{14}\times2^3\\
 100! &\equiv 10^{24}\times6\times2^{14}\\
 100! &\equiv 10^{24}\times6\times2^{5\cdot2+4}\\
 100! &\equiv 10^{24}\times6\times2^{2}\times2^4\\
 100! &\equiv 10^{24}\times6\times4\times6\\
 100! &\equiv 10^{24}\times4\times6\\
 100! &\equiv 10^{24}\times4\\
\end{align}$$
So there are 24 zeros, and the preceding digit is a 4. This agrees with a calculation printed in the comments.
Comment: The result in the comments has a $4$, not a $6$ as first non-zero digit.
Comment: @FabioSomenzi Thanks, I don't know how I missed that. The issue is that I forgot the powers of $9$ that come into play from the values of $n\tilde{!!}$. I will add those in now.
Comment: @FabioSomenzi Corrected now, thanks again.
Answer: For $10!$:
The last non-zero digit is formed as the product of the digits in the unit places (note that $2\cdot 5$ has to be left out):
$$3 \cdot 4 \cdot 6 \cdot 7 \cdot 8 \cdot 9 \equiv 8 \mbox{ mod } 10 \rightarrow \mbox{last non-zero digit: }8$$
For $100!$:
Here the last non-zero digit is formed by $10$ blocks of $(3 \cdot 4 \cdot 6 \cdot 7 \cdot 8 \cdot 9)$:
$$(3 \cdot 4 \cdot 6 \cdot 7 \cdot 8 \cdot 9)^{10} \equiv 8^{10} \equiv 4 \mbox{ mod } 10 \rightarrow \mbox{last non-zero digit: }4$$
For $1000000!$:
Here you have $10^5$ blocks of last digits $(3 \cdot 4 \cdot 6 \cdot 7 \cdot 8 \cdot 9)$:
$$(3 \cdot 4 \cdot 6 \cdot 7 \cdot 8 \cdot 9)^{10^5} \equiv 8^{10 \cdot 10 \cdot 10 \cdot 10 \cdot 10 } \equiv 4^{10 \cdot 10 \cdot 10 \cdot 10} \equiv \ldots \equiv 6 \mbox{ mod } 10 \rightarrow \mbox{last non-zero digit: }6$$
Comment: Note: From $n= 3$ on the last non-zero digit of $10^n!$ is always $6$.