awk to parse input with multiple conditions

Question: This post in a continuation of:
using awk to parse specific condition and apologize if I should have added to the thread, should I have added it to that post?  I have tried to modify the below awk script, but with no luck
awk 'NR==2 {
  split($2,a,"[_.>]");b=substr(a[4],1,length(a[4]-1));
  print a[2]+0,b,b,substr(a[4],length(a[4])),a[5]}' \
OFS="\t" ${id}_position.txt > ${id}_parse.txt

I have multiple possible condition that a user could input resulting in different output.  One of those conditions is in the data sample, with the field in bold needed to be parsed:
` parse rules:
1. 4 zeros after the NC_  (not always the case) and the digits before the .
2. g. ### (before underscore)  _### (# after the _)
3. TG (letters after del)
4. -  (hyphen used in this spot)`

Data Sample
 Input Variant  Errors  Chromosomal Variant Coding Variant(s)
 NM_004004.5:c.575_576delCA     **NC_000013.10:g.20763145_20763146delTG** NM_004004.5:c.575_576delCA    XM_005266354.1:c.575_576delCA XM_005266355.1:c.575_576delCA XM_005266356.1:c.575_576delCA

Desired Output
13     20763145     20763146     TG     -

Thank you :).
Comment: your current code only works on the 2nd record read. Is that as you intend? If you're trying to skip a header record, and then process everything after that, you'll want `NR>1`. And, sorry to say, but as is, this question is high on the incomprehensible scale. You say " I have multiple possible conditions", but then the next sentence is "One of this conditions is ...". Well so are you only interested in solving that one case? If so, the "multiple possible conditions" doesn't help our understanding. Until you understand awk better, I'd recommend solving one problem at a time. Good luck.
Comment: Maybe rather than have these obfuscating strings (your data sample), post I have `NC_000013.10:g.20763145_20763146delTG` and I need to extract just the `13` from the leftmost `NC_000013`. Get all of those translations working, then we can add logic to process or skip records as needed. Put another way, simple examples of sample input and the required output, along with your attempt to solve, your current output and exact text of any error messages, make it easier to help.  Good luck.
Comment: I don't really understand the question but you can use match in awk to pull out strings. For example the NC string awk 'match($0,/NC_0000(..)\./,NC){print NC[0]}' would print 13. Change and repeat as needed :)
Comment: Yes, I am intending on on skipping the header and the posted code works great for one condition or data format.  However, if that format is different, as posted, then the `awk` does not work.  I am trying to redo the code to get it work on condition 1 (already working) and also on condition 2.  Thank you :).
Answer: TXR Language:
Input Variant@(skip)
@(skip)NC_@{nc-raw}.@(skip)g.@{g-left}_@{g-right}del@{letters 2}@(skip)
@(bind nc-num @(int-str nc-raw))
@(output)
@{nc-num 6} @{g-left 12} @{g-right 12} @{letters 6} -
@(end)

Run:
$ txr nc.txr data
13     20763145     20763146     TG     -

All in the command line:
$ txr -c 'Input Variant@(skip)
@(skip)NC_@{nc-raw}.@(skip)g.@{g-left}_@{g-right}del@{letters 2}@(skip)
@(bind nc-num @(int-str nc-raw))
@(output)
@{nc-num 6} @{g-left 12} @{g-right 12} @{letters 6} -
@(end)' data
13     20763145     20763146     TG     -


RabbitMq Consumer on AWS Lambda

Question: From what I know, Lambdas are for listening to events and running a piece of code on response to those events.
The events need to be AWS services or HTTP endpoints.
If I have a RabbitMq service running on an EC2 server (Not using SQS), is it possible to have a consumer deployed on Lambda?
If possible, would this be the right thing to do?
Also, since lambdas are billed on compute time, I shouldn't be billed for when the queue is idle, right?
Comment: It might not be general thing but i guess combination of SNS & Lambda you can use http://docs.aws.amazon.com/lambda/latest/dg/with-sns-example.html
Comment: I don't know of any way for RabbitMQ to trigger an AWS Lambda invocation. You would have to schedule your Lambda function to run every minute or so and check the queue for messages. Also the last sentence in your question makes no sense.
Comment: @MarkB Sorry. Update the last question.
Answer: You can probably install this on the same server as the rabbitMQ, and make it trigger the lambdas. I haven't tried myself though
https://github.com/AirHelp/rabbit-amazon-forwarder
As far as I understand, lambdas are billed by the running time, and you pay based on amount of memory (per gigabyte/second). So making a lambda wait all the time will probably be pretty expensive and hard to manage since it will time out. If you already have a server with RabbitMQ, use that for consuming the queue and calling the lambdas.
Answer: You can now configure Amazon MQ for RabbitMQ as an event source for AWS Lambda.
Check the AWS blog.
https://aws.amazon.com/blogs/compute/using-amazon-mq-for-rabbitmq-as-an-event-source-for-lambda/
Comment: how would you handle the possibility of dynamically generated queues as the event source for the lambda? In my setup queues are generated dynamically when a new user joins, so I wouldn't be able to specify the queue name ahead of time. Do you have any idea how to handle that? Thanks!

RabbitMq Consumer on AWS Lambda


A simple probability question but seemingly 2 answers, which one is the best?

Question: A fair spinner with digits  1,2,2,3 marked on it is spun three times. The three numbers are added to give a score. Find the probability that the score is even.
Answer 1 : There are 32 even outcomes eg 3,2,1.......
so P(even score ) is 32/64  = 1/2.
Answer 2: There are 13 even scores eg. 2+2+2 therefore 13/64.
Is this a case of equally likely or not? Any ideas?
Answer: No matter whether the score after two spins is even or odd, the probability for an even or odd score will be $\frac{1}{2}$ each at the last spin.
Hence $\frac{1}{2}$ is the correct result.
Answer: I don't know how  you counted the scores, but since there are Two odd numbers and two even ones, the answer is $\frac12$.
Answer: The different possible scores aren't equally probable. And there aren't 64 of them either (you can get anywhere from $3$ to $9$, which makes it $7$ different possible scores, and three of them are even). So that approach is not going to work without massive changes.
The first approach is better, because each of the $64$ outcomes (assuming you, for a moment, pretend like the two $2$'s are different $2$'s) are equally likely. You just have to be careful when adding them up so that you are certain that exactly $32$ of them result in an even sum.
My preferred approach: After the first two spins, the last spin will decide whether the sum is even or odd. It has an equal probability of deciding either way, so the probability of an even sum is $\frac12$.


Test for difference between 2 empirical discrete distributions

Question: I have test data where I have several large samples from discrete distributions which I am using as empirical distributions. I am wanting to test whether the distributions are actually different and what the difference in means is for those distributions which are actually different.
Since they are discrete distributions my understanding is that the Kolmogorov-Smirnov test is invalid due to the underlying continuous distribution assumption. Would the Chi-Squared test be the correct test for whether the distributions are actually different?
What test would I use for the difference in means?  Would a better approach be to sample from the distributions and take the difference and then perform analysis on the distribution of the difference?
Comment: Yes, the $\chi^2$-test is the correct one. The accepted answer to [this question](http://stats.stackexchange.com/questions/76898/test-whether-two-multinomial-samples-come-from-the-same-distribution) elaborates on that. _distribution 1 = urn 1_ and _distribution 2 = urn 2_. There, the values of the random variables are colours and in your case probably something else, e.g. discrete numbers.
Comment: Thank you for the feedback. Is there a test for what the difference in means for when the chi-squared test confirms that the distributions are different?
Comment: Would a better approach be to sample from the distributions and take the difference and then perform analysis on the difference?
Answer:
The Kolmogorov-Smirnov can still be used, but if you use the tabulated critical values it will be conservative (which is only a problem because it pushes down your power curve). Better to get the permutation distribution of the statistic, so that your significance levels are what you choose them to be. This will only make a big difference if there are a  lot of ties. This change is really easy to implement. (But the K-S test isn't the only possible such comparison; if one is computing permutation distributions anyway, there are other possibilities.)
Edit: Alexis kindly supplies a reference in comments below,
"Article detailing exact distribution of K-S test statistic when accounting for ties:
Schröer, G., & Trenkler, D. (1995). Exact and randomization distributions of Kolmogorov-Smirnov tests two or three samples. Computational Statistics & Data Analysis, 20, 185–202."
I have not yet had a chance to look at it, but it sounds directly relevant and I thought I should highlight its existence for anyone not inclined to read the valuable comments.

vanilla chi-square goodness of fit tests for discrete data are generally, to my mind, a really bad idea. If the above potential loss of power stopped you using the K-S test, the problem with the chi-square is often much worse - it throws out the most critical information, which is the ordering among the categories (the observation values), deflating its power by spreading it across alternatives that don't consider the ordering, so that it's worse at detecting smooth alternatives -- like a shift of location and scale for example). Even with the bad effects of heavy ties above, the KS test in many cases still have better power (while still lowering the Type I error rate).

The chi-square can also be modified to take account of the ordering (partition the chisquare into linear, quadratic, cubic etc components via orthogonal polynomials and use only the low order few terms - 4 to 6 are common choices). Papers by Rayner and Best (and others) discuss this approach, which arises out of Neyman-Barton smooth tests. This is a good approach but if you don't have access to software for it, it may take a little setting up.
Either modified approach should be fine, but if you're not going to modify either approach, it's not necessarily the case that the chi-square will be better than the KS test -- in some situations it might be better ... or it may be substantially worse.
If the ties are light (i.e. there are lots of different values taken by the data), I'd consider the KS as-is. If they're moderate, I'd look to calculate the permutation distribution. If they're very heavy (i.e. the data only take a few different values), the plain chi-square may be competitive.
Comment: Article detailing exact distribution of K-S test statistic when accounting for ties: Schröer, G., & Trenkler, D. (1995). Exact and randomization distributions of Kolmogorov-Smirnov tests two or three samples. *Computational Statistics & Data Analysis*, 20, 185–202.
Comment: Thank you for the warning. I'll take that into consideration when I decide to use either the K-S test or the Chi-Squared


Tomcat 7.0.42 crashes with grails app

Question: i have an exception in tomcat 7.0.42. The only thing i am doing is deploying a grails app in the webapps directory. I have changed nothing in the config... and tomcat was working fine until recently.
i really havent find what was making trouble between my war and tomcat.
I searched in the archive, and found that some jars could probably conflict. i've found that jetty.jar and servlet.jar which are present in the WEB-INF could a source of conflict, but didnt find any of them in my WEB-INF directory...
this is my stacktrace:
org.apache.jasper.JasperException: java.lang.ClassCastException: org.apache.jasper.el.ELContextImpl cannot be cast to org.apache.jasper.el.ELContextImpl
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

does anybody here have an idea of the cause of this problem when its not due to conflicting jars?
Comment: You JSP file may have an invalid EL expression. Check syntax!
Comment: Do a dependency report on your grails app, I suspect you might have something that's pulling in the `tomcat` Grails plugin in compile scope rather than build scope, which would put tomcat JARs in your WEB-INF/lib when you build a war.
Comment: Did you find a solution to your problem? For others in the same situation please accept an answer or provide your own answer.
Comment: Sorry i let this post without answer. I found a solution using the embarqued tomcat in netbeans. I tried to analyze the code using the tools you gave to me but foung nothing, i removed some jars too but it did not change anything!
Answer: Search for the Class org.apache.jasper.el.ELContextImpl in your classpath. I am quite sure you will find more then one entry. Also this Class might be located in the tomcat libs dir. Check there as well if otherwise not found.
Here is a list of some tools that can assist you analyzing the classpath. Some of them need maven.
http://www.jboss.org/tattletale
http://mojo.codehaus.org/extra-enforcer-rules/banDuplicateClasses.html
https://github.com/ning/maven-duplicate-finder-plugin
hope this helps to track down your problem.
Another option during runtime is to do following:
Start tomcat with the jvm option -verbose:class. This will print out all the classes that are loaded and the jars they are coming from. Grep for ELContextImpl to find out the jar. Remove the jar and see if it is working again.
Comment: Thanks Vadimo for the help.

i've search in the jars in apache/lib but didnot find more than one entry. What i've done is :
find path/to/libs -name '*.jar' -exec grep -Hls ClassName {} \;

Tomcat 7.0.42 crashes with grails app


Acos & Asin substitute in Access

Question: How can I calculate track & distance & wind vectors  in Access. Many thanks
Answer: Fortunately you have Arctan in Access, so you can use the fact that if
x = sin(y) then tan(y) = x/sqrt(1-x^2).  In access:
 Const PI As Double = 3.14159265359
 aSin = Atn(val / Sqr(1 - val * val))
 aCos = PI / 2 - aSin

Hope this helps.

Acos & Asin substitute in Access


How to pass data from filter to action?

Question: Let's suppose this filter:
public function execute ($filterChain)
{
    if ($this->isFirstCall())
    {
        $loggeduser = array();
        .
        .
        .
        $this->getContext()->getResponse()->setSlot ('loggeduser', $loggeduser);
    }
}

I want to pass this loggeduser array to every action, even to ajax actions. This variable stores the logged user informations. the get_slot(); function doesn't work. How to solve this? Session must not be used this time.
Answer: This should work:
$this->getContext()->getRequest()->setParameter('loggeduser', $loggeduser);
Comment: You can also store it in session: `$this->getContext()->getUser()->setAttribute('loggeduser', $loggeduser)`
Comment: He said "session must not be used this time."
Comment: You can also store that in some user property. Something like `$this->getContext()->getUser()->blabla = $loggeduser;`. And get it in actions with something like `$this->getUser()->blabla`.
Comment: looks OK, but im not convinced that a general data should travel among "request parameters".
Answer: There is no getSlot() method on the sfWebResponse but there is getSlots() so you can retrieve an array of all the slots you have passed to the response.
In any controller:
$slots = $this->getResponse()->getSlots();
print_r($slots['loggeduser']);

As @Vlad Jula-Nedelcu stated, if you don't want use the session and really need to only pass a variable between controllers in one script run you can set a property on any object kept in the sfContext.
Unfortunately in Sf 1.4. you're not able to add your own objects to the sfContext, you have to use the ones which are already there.

How to pass data from filter to action?


Por que esta estrutura de repetição que deveria voltar uma palavra ao contrário não volta nada?

Question: phrase = str(input("Type your phrase: ")).upper().strip()
words_phrase = phrase.split()
words_together = ''.join(words_phrase)
phrase_inverse = ""
for letra in range(len(words_together) - 1, -1, -1):
    phrase_inverse = words_together[letra]
print(phrase_inverse)
if words_together == phrase_inverse:
    print("Esta frase é um palíndromo")
else:
    print("Não é um palíndromo")

Este programa tinha a finalidade de fazer uma frase ficar ao contrário, mas quando eu executo o código e o programa tenta mostrar a frase ao contrário ele só retorna a primeira letra, sendo que a phrase_inverse tá dentro do loop, seria mais fácil deixar:
phrase_inverse = words_together[letra:]

Mas o exercício não permite.
Answer: O problema está na linha que você inverte a palavra:
phrase_inverse = words_together[letra]

Perceba que você sempre atribui o valor da última letra lida na variável, porém não acumula os valores, com isso você acaba tendo no final somente a primeira letra da frase digitada.

Para corrigir isso, basta acumular as letras durante a inversão, isso pode ser feito utilizando += que concatena o valor já presente da variável com o novo inserido:
phrase_inverse += words_together[letra]

O código completo ficaria mais ou menos da seguinte forma:
phrase = input("Type your phrase: ").upper().strip()
words_phrase = phrase.split()
words_together = "".join(words_phrase)
phrase_inverse = ""

for letra in range(len(words_together) - 1, -1, -1):
    phrase_inverse += words_together[letra]

if words_together == phrase_inverse:
    print("Esta frase é um palíndromo")
else:
    print("Não é um palíndromo")

Obs.: Perceba que remove o str da função input, isso porque a função input já retorna uma string, portanto não é necessária essa conversão

Veja online: https://repl.it/@Dadinel/BelatedMeanWordprocessing


AngularJS: How do i capture the value of selected option in the function?

Question: I am working on cordova application that consist of angularJS. I have a code snippet as follows:

                    Select Team

                <select>
                    <option ng-repeat="deviceEach in devices" id="{{deviceEach.id}}">{{deviceEach.name}}</option>
                </select>

                <input type="text" placeholder="Enter user Email" ng-model="newuser.username">

            <button ng-click="userSubmit(newuser)" class="button button-calm">
                Add User
            </button>

When user click on add User button it should capture the value of selected option Id and username entered. I can capture the value of input tag but how to capture the value of select tag selected option?
Comment: Try
Answer: on the select element use ng-model
<select ng-model="selectedValue" >
   <option ng-repeat="deviceEach in devices" id="{{deviceEach.id}}">{{deviceEach.name}}</option>
</select>

Comment: yes if you want after you can store it in another variable but if you you want to post your newUser, yes it could be newUser.device


If I buy an "MP3", is that equivalent to getting a CD or is it lower quality?

Question: On Amazon I can buy "MP3s" of individual songs. Is that equivalent to buying a standard music CD, or am I getting lower quality if I buy an MP3 and I need to buy the CD if I want the highest quality of sound?
Not sure if this is a subjective question, but how much is the quality difference? For example, can an expert musician tell the difference between an MP3 and the same song being played from a CD?
Comment: I'm voting to close this question as off-topic because it's not about music practice or theory as outlined in the help center.
Comment: https://musicfans.stackexchange.com/questions/21/what-is-the-quality-threshold-for-recordings-sounding-better-truer may be of interest. Note that if you want a download that's equivalent to CD in compression terms, look for services offering FLAC download (as FLAC is losslessly compressed).
Answer: Despite this being off topic, I think that the question deserves an answer. MP3 files are compressed and so will not sound as good as WAV files. That said, there is no such thing as a standard mp3 file - it depends on the bitrate used in conversion. A low bitrate such as 128 kbps will sound demonstrably worse than the original, as the file will have been compressed to about 10% of its original size. A high bitrate such as 320 kbps will sound much better and will be difficult to differentiate from the original.
The ability to differentiate between uncompressed and compressed files also depends on the equipment used to play the files: the difference will be less apparent using a smartphone and earbuds, whereas it will be more apparent using a cd player, amplifier and good speakers.
Comment: Other variables include the actual nature of the material being compressed (some things 'survive' high compression factors better than others) and  the precise algorithm used when doing the compression.


How i can change page with "next" previous" buttons in the same node

Question: i want create something like that
:

and after clicking next page , the node doesn't change :
Comment: I don't understand your question. What's the problem?
Answer: Have you considered smart_paging module
Answer: The node from your screenshots is using the Webform module to create a multi-step form. The URL doesn't change because it's still the same node, the form's current step is just changing when you submit the form.
Without more information, I'm unsure if this is the same kind of functionality you're looking for, but when setting up a webform, I believe there is a "page break" component that you can add, which is what determines which components belong to which page. You could also use something like the Webform Steps module to create a clickable progress bar for your form.


Is there is a way to select or filter the list of UDT in Cassandra table?

Question: From the below select response. How can i add where clause to filter the flights between the requested arrival time.
cqlsh:api_itl> select * from generic_response_1;

 trace-id                             | result-index | api | base_price | fare_selection | fare_type | flights                                                                                | sale_price | special_instructions | total_duration
--------------------------------------+--------------+-----+------------+----------------+-----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+----------------------+----------------
 39485363-cc22-4eff-a502-6d860931c3fb |         IB56 | tbo |       8400 |         Retail |       ADT | [{arrival_date_time: '23-03-2019 14:10', carrier_iata: 'UK', carrier_id: 'UK 816', carrier_name: 'Air Vistara', class_code: 'Q', departure_date_time: '23-03-2019 11:30', flight_duration: 160, field_7_: 'BLR', to: 'DEL', via: ''}, {arrival_date_time: '23-03-2019 22:40', carrier_iata: 'UK', carrier_id: 'UK 835', carrier_name: 'Air Vistara', class_code: 'Q', departure_date_time: '23-03-2019 19:55', flight_duration: 165, field_7_: 'DEL', to: 'MAA', via: ''}] |       9485 |                 null |            670
 39485363-cc22-4eff-a502-6d860931c3fb |          OB4 | tbo |       1000 |         Retail |       ADT |                                                                                [{arrival_date_time: '08-03-2019 14:55', carrier_iata: '6E', carrier_id: '6E 119', carrier_name: 'Indigo', class_code: 'Q', departure_date_time: '08-03-2019 13:55', flight_duration: 60, field_7_: 'MAA', to: 'BLR', via: ''}] |       1770 |                 null |             60

(2 rows)
cqlsh:api_itl>

Database structure for the given output

CREATE TYPE api_itl.flight (
    arrival_date_time text,
    carrier_iata text,
    carrier_id text,
    carrier_name text,
    class_code text,
    departure_date_time text,
    flight_duration int,
    "from" text,
    "to" text,
    via text
);

CREATE TABLE api_itl.generic_response_1(
    "trace-id" uuid,
    "result-index" text,
    api text,
    base_price float,
    fare_selection text,
    fare_type text,
    flights list<frozen<flight>>,
    sale_price float,
    special_instructions list<text>,
    total_duration int,
    PRIMARY KEY ("trace-id", "result-index")
)

Comment: change your data model to have clustering keys by arrival time
Comment: Possible duplicate of [how to filter cassandra query by a field in user defined type](https://stackoverflow.com/questions/33840105/how-to-filter-cassandra-query-by-a-field-in-user-defined-type)
Comment: @ChrisLohfink How to model? If my model is wrong, suggest me how to structure it?
Comment: @picadoh What u have suggested is dictionary, In my case the column flight is a list. Could you suggest me How to create like suggested UDT. Because My Udt is list of UDT
Answer: Data which is part of TYPE can't be filtered using CQL. Instead, consider changing the data model.
First, make TYPE to a TABLE.

Consider changing datatype of arrival_date_time to timestamp.
Also, add trace-id, result-index to maintain a reference to the main table.

CREATE TABLE api_itl.flight (
    arrival_date_time timestamp,
    carrier_iata text,
    carrier_id text,
    carrier_name text,
    class_code text,
    departure_date_time text,
    flight_duration int,
    "from" text,
    "to" text,
    via text,
    "trace-id" uuid,
    "result-index" text,
    PRIMARY KEY ("carrier_id", "arrival_date_time") );

Next, remove flights list<frozen<flight>> from original table.
Now you could use two queries to get your desired result.


Show a page with child Terms when parent Term clicked in block?

Question: I want to Display child terms when a parent Term is clicked with Views in Drupal 7.
         Example
<code>     Parent1
          .child11
          .child12

      Parent2
          .child21
          .child22
          .child23
</code>
So when Parent1 page is Visited, i will display the content of parent1 but with a block showing
<code>          .child11
          .child12
</code>
Any insight in Achieving this will be Appreciated. Thank you.
Comment: are you using D7 or D6?
Comment: Drupal 7, i have edited the Question.
Answer: Try the Views tree module. It is great for taxonomy trees.

This module provides a tree-based style plugin for Views. It is equivalent to the tree-based style template from Views 1.
It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.

There is also a patch for adding collapsible support but I'm not sure how complete it is. See http://drupal.org/node/1538414
Answer: Download and install the Taxonomy menu module, it will exactly match your requirement. More details from the module's project page:

Custom Menu per vocabulary
Uses the default taxonomy term path or custom paths
Integrate with Views
Integrate with Pathauto: use URL/path aliases
Does not interfere with other menu modules

See the demo http://taxonomymenu.davidstoline.com/ (click the terms and you can see the term highlighted in the block)
Hope it will help you!


Change Color of PNG Image on hover with css?

Question: I want to change image color on hover.
I've tried with this css
.white:hover .img-white{
       color:white;
}

And html is

please tell me about my question how to change png image color on hover.
Comment: Does this answer your question? [How to change color of png on hover?](https://stackoverflow.com/questions/28707466/how-to-change-color-of-png-on-hover)
Comment: If in doubt, always have a quick google of what you're currently using, MDN is a good source, so "color css MDN" google will give you: https://developer.mozilla.org/en-US/docs/Web/CSS/color - which states: `sets the foreground color value of an element's text` - you can't use this to change the colour.  You either need a different image or an overlay.
Comment: "*change image colour to white"* - what does that even mean? An image usually contains many colours - do you want all of them to be white? ie become a white box?
Answer: You may not be able to change color, but you can change opacity of the image:

.img-white:hover{
       opacity:0.5;
}

Edit:
Here's a version that makes the image "white":

.img-white:hover{
       opacity:0;
}

Comment: but i want to change png  image color.
Comment: @Farhan what does that even mean?  An image *usually* contains many colours - do you want *all* of them to be white?  ie become a white box?
Comment: When you say color, what exactly that mean? you want that to complete white?
Comment: If so, change the opacity in this answer to 0:  `opacity:0;` - while not "white" it will be the same as the background (which in this case is white) so just make your background white.
Comment: If not image then yeah you can do something on that, unfortunately since it is image, as @freedomn-m said above it contains many colors and you cannot specifically dim some colors, however there are some cheatcodes which can help you  to make in a bit light but again it comes to the field of `opacity`. Hope you got what I mean.
Comment: @freedomn-m yeah making `opacity:0;` will be complete white or invisible, @Farhan is that what you need? if so then change opacity 0.5 to 0.
Answer: Use the transition to give a more effect.  In the image hover uses this.
webkit-filter: grayscale (0%); transition: 1s;
And in the image: -webkit-filter: grayscale (100%)
Comment: Hi, welcome to SO - please note this is an English only site - questions *and* answers in English please.


Handicap is tee-based or just man/woman?

Question: I am ultra-beginner to golf and trying to develop a mobile application around it. I am trying get along with golf game and scoring rules, I have few doubts so posting away my first of series of questions. Looking forward to your helpful responses just like in other stack exchange networks.
Is handicap defined according to tee or according to man/woman. I read somewhere that course handicap is different for different tees, is this correct?
Or its different for man and woman only but same for all tees. I drew this conclusion from this sample data http://golftraxx.com/view_scorecard.php?course_name=Heather+Gardens+Golf+Course&zipcode=80014.
Thanks in advance.
Comment: Welcome to Sports SE. [This answer](http://sports.stackexchange.com/a/4878) for a different question may help you determine how handicap is measured.
Comment: You should read the answer @edmastermind29 pointed out, and if you have any doubt about it, edit your question according. The tee is based on your handicap, better handicap usually has a tee further away than worst handicap.
Comment: @gbianchi - Not really. It's dependent more on swing speed and thus your average drive distance. The hole is designed to play a certain way, so in casual play you choose the tee that gives you the best opportunity to get the ball where you're supposed to. Ladies, for instance, can be scratch golfers without having to hit from the "tips". Same for senior men. Now, a young man with a low handicap will typically have a strong swing, so it generally follows that lower 'cappers will play back, but except in competitions where *everyone* hits off the same tee, there's no rule forcing use of any tee.
Comment: @KeithS In casual play, you can even move your ball if you want ;). But I think OP has more interest in a tournament view (pro or not pro).
Comment: Even in tournaments, the tee box you hit from is still typically chosen based on your age and gender and thus your expected physical ability, independent of your skill. The change is that everyone tees back one box from their "traditional" box; men tee from the Tourney Men's tee (typically black, sometimes gold), senior men tee from the blues, women tee from the senior men's tee (or sometimes from a special "tournament ladies" tee).
Comment: All the tourney rules usually mean compared to casual play is that you can't "tee it forward"; if you're a high-handicap young man that usually plays from the whites, and you want to play in a tourney, it's back to the tips for you.
Comment: @KeithS At least tournament in argentina are tee based on handicap. Is different on other countries? Do you have any ruling about it?
Comment: The USGA allows the organizers of a competition to set rules for both use of handicaps and for tee boxes as they see fit. However, it can be a huge bother to keep track of, especially in scrambles and other group formats where there's one score among two to four people all with different handicaps and who might hit off different tees. In addition, because competitions are played to strict rules, hitting from the wrong tee area is severely penalized.
Comment: So to simplify things for everyone involved, most tournaments in the U.S. specify the tee box to be used based on age group and gender, whether or not handicaps are used.
Answer: You're confusing a few things, which is natural.
First off, understand that there are two officially-sanctioned ways to score golf in individual play; stroke play and match play. In stroke play, every stroke you take is added up to your final score, allowing you to compete against any number of people including your own past scores. Most rounds of golf are scored this way. In match play, you compete directly against one or more people during the round for the best score on each hole, and you win, lose or "halve" the hole; the person with the most won holes wins the match. This can be used for friendly competitive play in pairs, and also to play for money such as in "skins" games.
So, the handicap system for golf has to be able to be used for both methods of scoring. This is done by applying the handicap in different ways. In stroke play, your own handicap is simply deducted from your raw total score (the sum of all strokes made and all penalty strokes) to produce your final score. So, if you're just going out to see how you hit 'em, all you have to know is your Course Handicap, which itself is complex to calculate according to the Rules (because it's designed to facilitate applying a handicap to a course you've never played, based on your play on other courses which might be more or less difficult), but you usually get close enough just averaging the number of strokes over par of your last few rounds at a course.
For match play, it's a little different. First, you have to know both yours and your opponent's Course Handicaps, because it's the difference between those two that will be applied. Let's say you're playing me, and you have a 19 'cap while I have a 26 'cap (I wish). That gives me 7 handicap strokes for this round. I assign those strokes, one at a time, in the order of the holes' Handicap ranking; the hole ranked 1 is the most difficult to score par on, while the hole ranked 18 is the easiest. So, on the 7 most difficult holes of the course, I would either deduct one stroke from my score for that hole, or add one stroke to yours, before comparing scores to determine who has won that hole.
Picture = word * 103:

The line titled "Handicap" contains the difficulty ranking of each hole on the course as played from the Men's or Senior's tees (Blue through Gold on this card). Hole 8 is the most difficult; it's the longest par-4 on the course, requiring a long iron or wood shot from the fairway to make green in regulation (in turn requiring you to avoid the fairway bunkers), with water bordering the hole on the left side on approach. Hole 12 is the easiest; the second-shortest par 4, and with no water and minimal hazards (one approach bunker).
The Ladies' tees are typically placed much closer to the hole, especially on longer par 4 and 5s, to compensate for reduced drive distance between men and women, and that can make certain holes easier than they would be from the Men's tees. So, the Ladies' tees have their own handicap ranking, seen on the line under the distances for the Red tees (traditionally the Ladies' tees). For ladies, Hole 7 is the hardest on this course, because it's the second-longest par-4 as played from the reds (and only by 7 yards), and has water (though easily avoided, unless the hole severely slopes toward the hazard). Hole 13 is the easiest; par 3, no hazards, and the distance is somewhere in the mid-irons for most women.
So, assuming you and I are both male golfers playing the course this card is from, with the handicaps stated above, I would add one stroke to your score (or deduct one from mine) when we played holes 4, 7, 8, 9, 14, 17 and 18.
Now, I may not need those handicap strokes on those holes. For instance, I may have it together on hole 8, and birdie with a strong drive, accurate long iron or fairway wood approach and a one-putt, while you either two-putt it for par or have to make an up-and-down with an extra fairway stroke, so I would have won the hole without the handicap. Meanwhile, back on hole 5, I hit one in the lake and double-bogied, but you three-putted to win by one stroke. In that situation (or any other), I can't apply my handicap stroke on 8 to hole 5 to halve the hole; I just have to take the loss of hole there and do better on the next few to make it back up.

EDIT:
Now, all of that is in applying the handicap in stroke play versus match play. I skimmed over calculating the handicap to apply to a course in my original answer, but that also has a bearing here. Again, looking at the title for each tee on the example scorecard, you will see two numbers separated by a slash. The first number, the decimal, is the Course Rating. This number is essentially the average expected score for a "scratch golfer" playing this course from this tee, and it can be calculated based on recent real plays of the course from that tee by scratch players, or in the absence of enough good real data, it can be estimated based on the abilities of a hypothetical "scratch golfer" playing from that tee.
The second number is the course's "Slope Rating". Basically, think of it as being a measure of how much more difficult the course is for high handicappers than scratch golfers. Courses play differently for golfers of different abilities; a course with long fairways and a lot of lateral water hazards doesn't play much differently for a scratch golfer, because he'll have the long, accurate drive and fairway shots to send the ball down the middle of the fairway and get to the green "in regulation". But, it can make for a really long day for a "bogey golfer" with a short drive and a stubborn slice who keeps putting it in the water and takes more than par just to make it to the green. Conversely, a course might have nice wide fairways, but pockmarked with hazards right in range of the scratch player's average drive; so, he either has to play better than average to carry over the hazards, or lay up short of them and possibly take an extra stroke to get on the green. The bogey golfer, however, wouldn't be bothered by the hazard since he would never be able to drive far enough for it to be a problem, so the course actually affects the scratch golfer's game and score more than the bogey golfer's.
To account for all these variations in course difficulty and player ability, without requiring the player to have recently played a number of rounds at the course to calculate a course-specific handicap, the USGA uses a "Handicap Index", which averages a number of normalized, adjusted "Handicap Differentials" recorded from past plays.
Your Handicap Index is calculated by starting with the raw score of your most recent 20 games played by "strict rules" (or however many you have; you must have at least 5). You can make a few sanctioned adjustments to those scores to mitigate really bad out-of-character scores or to compensate for deviations from struct rules such as mulligans. This gives you the Adjusted Score. Take the lowest 10 scores (if you have 20 recent plays; if you don't, you use a reduced number that can be produced by the Excel formula <code>=CEILING((A1-4) * 0.5 + ((A1-16) * 0.5 * (A1>15)), 1)</code> where cell A1 contains the number of rounds played). For each of these, subtract the Course Rating from the score, multiply by 113 (the average slope rating of all USGA courses), divide by the Slope Rating for that round, then multiply again by .96 (an "Excellence Factor" that reduces the advantage of a high handicap, forcing high 'cappers to drop more strokes from their average game to beat a low capper, thus improving their cap) and round to the nearest tenth to produce the Handicap Differential for each of the rounds. Average these Differentials together (a spreadsheet program really helps out here), round to the nearest tenth, and you have your Handicap Index.
To compute your Course Handicap, simply multiply by the Slope rating of the tee box you're about to play from, then divide by 113, and round to the nearest whole number. Why isn't Course Rating used here? Because a "scratch golfer" would expect to score the Course Rating, so it wouldn't be fair if your handicap got you to the course par which can be up to 6 strokes below the Rating of more difficult courses.
So, your Course Handicap is dependent on the tee you hit from, not only in the current round but your past 20 rounds (or however many you've played). How it is applied to the play of a round, however, does not.
Comment: I always wondered why (seemingly by convention) handicaps were all odd for one nine and all even for the other; but your very complete explanation seems to implicitly explain that, so that during match play the handicap strokes will be divided as evenly as possible between the two nines. Nicely done!


Prove that for a quadratic form $Q(x) = x^TAx$, $A$ is symmetric.

Question: We want to show that $A=A^T$. Any matrix $A$ may be written as a sum of its symmetric and skew symmetric parts: $A = \frac{A+A^T}{2} + \frac{A-A^T}{2}$. Upon substitution, we obtain $Q(x) = x^T (\frac{A+A^T}{2} + \frac{A-A^T}{2}) x$. How am I supposed to show from here that $A-A^T = 0$?
Answer: It's not true: $x^T A x$ is a quadratic form for any matrix $A$, symmetric or not.  The point is that you can choose it to be symmetric, since $A$ and $(A + A^T)/2$ produce the same quadratic form.


Fingering violin double-stopping in counterpoint

Question: Can anybody give me a fingering for the double stopping in the Violin part for the Adagio movt of the Mozart Duo K423, bars 19 to 23?

IMSLP link
Answer: I would try starting in 3rd position and then crawling back to 1st position.


Emit with ack SocketIO with iOS

Question: I'm trying to make an emit with a callback, but it seems like the server doesn't recognize the call back function as a function. I have looked up the documentation, and to my knowledge the code should work.
This is the error I'm getting: TypeError: callBack is not a function
Here is the client code:
socket?.emitWithAck("connectUsername", username).timingOut(after: 2, callback: { (data) in

        print(data)
    })

And server code:

socket.on("connectUsername", function(username, callBack)
    {
        //Do stuff with username here...

        var id = socket.id
        callBack(id);
     });

Any help is appreciated.
Answer: as @kiddosrails mention problem is the timeout 2 seconds is less time to execute,  you can set timeout 0 which refer as not time out. Hope this answer will help you.
     socket.emitWithAck("connectUsername", username).timingOut(after: 0) {data in
      print(data)
    }

Comment: The server console is still getting the same error: TypeError: callBack is not a function
Comment: can you share console log of socket.io ?
Answer: I don't see callback as a parameter of timingOut in documentation. Following should work:
socket.emitWithAck("connectUsername", username).timingOut(after: 20) { data in
  print(data)
}

If above does not work, check what exactly is callBack by changing it to following:
socket.on("connectUsername", function(username, callBack)
    {
        //Do stuff with username here...

        var id = socket.id
        console.log(callBack.toString());
     });

Comment: I will test it as soon as I'm home
Comment: If I delete the callBack parameter in the client, the compiler will complain and suggest to add it back.

If I try to check the string of 'callBack' the following happens in the console:

/Users/xxxx/Documents/socket-training/index.js:69
       console.log(callBack.toString());
                            ^
TypeError: Cannot read property 'toString' of undefined
Answer: iOS Code
socket?.emitWithAck("connectUsername", data).timingOut(after: 0) {data in
            print(data)
        }

Server Code
var io = socketIO.listen(server);
io.sockets.on('connection', function(client){
    console.log('a user connected..!!!!!');
    client.on('connectUsername', function(username, callBack){
        var id = socket.id
        callback({
        ID:id,
        Message: "Successfully."
        });
    }
}

Comment: The server console is still getting the same error: TypeError: callBack is not a function
Comment: Please check updated answer and let me know if you still face any issue
Comment: This is exactly how my code is written out, I can connect users successfully and do other stuff, but as soon as I try to do an emit with a callback it crashes.
Comment: would you please confirm which socket.io version you have used on server and iOS side
Comment: Server: email@example.com   -
Client: 'Socket.IO-Client-Swift', '~> 13.2.0'
Answer: In your server code:
socket.on("connectUsername", function(username, callBack)
    {
        //Do stuff with username here...

        var id = socket.id
        callBack = ({id});
     });

That's because callback is not defined like an object so you can defined it like one.
Comment: Please mention the reasons for your approach so others can understand it easily

Emit with ack SocketIO with iOS


Hibernate saveOrUpdate does not update existing record instead it saves the record as new entry

Question: Been searching for SO since this morning but I can't find the right answer to this question, I'm doing an update to a record using the ID as reference, but instead of updating the app inserts new entry of the existing record, the console is showing "insert into" instead of "update". here are snippets from the app:
Controller:
<code>@PostMapping("/saveCustomer")
public String saveCustomer(@ModelAttribute("customer") Customer customer) {

    customerService.saveCustomer(customer);

    return "redirect:/erp/list";
}

@GetMapping("/showFormForUpdate")
public String showFormForUpdate(@RequestParam("customerId") int id, Model model) {

    Customer customer = customerService.getCustomer(id);

    model.addAttribute("customer", customer);

    return "customer-form";
}
</code>
DAO implementation:
<code>@Override
public void saveCustomer(Customer customer) {
    Session currentSession = sessionFactory.getCurrentSession();

    currentSession.saveOrUpdate(customer);
}
</code>
Entity:
<code>@Entity
@Table(name="customer")
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;

@Column(name="company_name")
private String companyName;

@Column(name="company_email")
private String companyEmail;

@Column(name="company_address")
private String companyAddress;

@Column(name="contact_no")
private String contactNo;

@Column(name="company_tin")
private String companyTin;

public Customer() {

}

public String getContactNo() {
    return contactNo;
}

public void setContactNo(String contactNo) {
    this.contactNo = contactNo;
}

public String getCompanyName() {
    return companyName;
}

public void setCompanyName(String companyName) {
    this.companyName = companyName;
}

public String getCompanyEmail() {
    return companyEmail;
}

public void setCompanyEmail(String companyEmail) {
    this.companyEmail = companyEmail;
}

public String getCompanyAddress() {
    return companyAddress;
}

public void setCompanyAddress(String companyAddress) {
    this.companyAddress = companyAddress;
}

public String getCompanyTin() {
    return companyTin;
}

public void setCompanyTin(String companyTin) {
    this.companyTin = companyTin;
}

public int getId() {
    return id;
}
</code>
Comment: The only way I can see this happening is if the entity really does not already exist, in which case you would get an `INSERT`.
Answer: I think you are missing setter method in your bean:
<code>public int setId(int id) {
    this.id = id;
}
</code>
and that's why when you are adding model attribute, it is not setting id value in your bean.


Creating date with 31 as day gives 30 in output

Question: I'm creating dates from strings with the format 'yyyy-MM-dd' but they're always created on the previous day for some reason. If I set the date as '2012-10-31' the Date object with actually be 30 of October and not 31. For example, this:
var d1=new Date('2012-10-31');

Will output this:
Tue Oct 30 2012 19:30:00 GMT-0430 (Venezuela Standard Time)

Can someone explain why this happens?
Comment: what is your UTC offset?
Comment: Look at [this question](http://stackoverflow.com/questions/7556591/javascript-date-object-always-one-day-off).
Comment: How can I compensate then? To get the time in my actual timezone?
Answer: Try this
var d1=new Date(2012, 10-1, 31, 0, 0 ,0);
document.write(d1);

which produces
Wed Oct 31 2012 00:00:00 GMT-0400 (Eastern Daylight Time)

the key is to remove the quotes and manually set the time. Also note that 'month' is zero based and so for readability I subtract one from it
Comment: I see the problem now, since the date isn't getting created with any time information is just takes it as GMT 0000 and rolls it back to my timezone.
Answer: This happens because dates are converted to a string based on your local time zone.
The date variable actually contains October 31st 0:00 UTC. When you convert it to string, it is converted using your own time-zone, which is 4:30 hours behind UTC.
Answer: With no further parameters, Date() create your time-stamp with GMT+0000.
Converting your date to string with no further parameters either, it will use the localised notation.
If you want to create a date matching your time-zone, do:
var d1=new Date('2012-10-31 GMT-0430');
//That's what you should get
//"Wed Oct 31 2012 00:00:00 GMT-0430"

Using this date now, you can convert the local time to the time of other timezones if you execute d1.toString() in a browser with a different timezone:
d1.toString();
//That's what I get
//"Wed Oct 31 2012 05:30:00 GMT+0100"


Automatically add taxonomy term based on state

Question: Suppose I have a shopping website for a number of shops selling toys. Not each shop sells each toy.
Our solution is that there is a taxonomy 'shops' and toys have a field to assign toys to a particular shop (or multiple shops). This works ok, but has two major flaws:

I dont want shop owner A to be able to change whether shop B sells a particular toy (they are competitors)
I dont want shop owners to have to select their shop each time when they add a toy.

So what I want is that upon login, the shop owner gets assigned a particular shop. When adding toys, this shop is automatically being added to the toy's "shops" field.
Furthermore, the site administrator should be able to select a shop upon login, and then see only stuff belonging to that shop.
How to achieve this without writing my own module?
Comment: What have you tried? If you want to control access to taxonomy, it's strange you don't even mention [Taxonomy Access Control](https://www.drupal.org/project/taxonomy_access), for example.
Answer: some Drupals core features will deal with parts of this for you.
You can set up a Role and set boolean permissions for
'Create own value for'
'Edit own value for field'
'Edit anyone's value for'
'View own value for '
'View anyone's value for
on fields of nodes/entities.
However with a project of this size you should expect to have to get your hands dirty and write code at some point ! IMHO


Existence and uniqueness of unital ring containing a non-unital ring as maximal ideal

Question: I think the title is pretty self-descriptive: let $I$ be a non-unital ring. Is there a unique (up to isomorphism) unital ring $R(I)$, s.t. $I \subseteq R(I)$ is a maximal ideal?
Answer: Let $F$ be any subfield of $\Bbb C$, and $I=(x)\lhd \Bbb C[x]$.
Then the ring $R=F+I$ is a subring of $\Bbb C[x]$ with identity, $I$ is clearly an ideal of this ring, and $R/I\cong F$, so $I$ is a maximal ideal. (This matches the 'idealization' of $I$ by $F$, a.k.a. the Dorroh extension.)
For $F=\Bbb Q$ and $F=\Bbb R$, you get nonisomorphic rings, for the group of units in $\Bbb Q+I$ is countable while the group of units in $\Bbb R+ I$ is uncountable.
Comment: Thx! Maybe this is trivial but is the existence always clear?
Comment: The famous way to embed a rng in a ring as an ideal is the Dorroh extension:  if $R$ is a rng, give $\Bbb Z\times R$ a ring structure by adding coordinatewise and multiplying this way:  $(n,r)(m,s)=(nm,ns+rm+rs)$. If $R$ is an $F$ algebra, then you can replace $\Bbb Z$ with $F$, but this won't always be the case. I haven't ruled out the possibility of a different construction that accomodates embedding as a maximal ideal, but I'm just giving you the best information I know at the moment.


fancybox, open gallery on click

Question: I`m not sure, maybe this question is already answered or there is some similar, but i hope that this will be the easiest way for me, to figure out this problem.
So i have this code in my "head" tag:

<link rel="stylesheet" href="js/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />

And this one in my body:

I want to open a gallery of 2 images (both.jpg and front.jpg) on click on eyey.png, but i get this error:
Uncaught TypeError: $.fancybox.open is not a function
How can i solve this error ?
Answer: just change this part from
$.fancybox.open([

to
$.fancybox([

fancybox, open gallery on click


Interpret seaborn pairplots

Question: For the figure given below, generated by seaborn.pairplot, I am trying to describe what the plots says.

I can say for sure that Label 0 is well concentrated.  What does the diagonal plot say though about the classes?  I just wanted to get a gauge as to what information can be interpreted from the plots, without knowing anything else?
Any help will be greatly appreciated!
Answer: There is significant overplotting here (orange on top of blue, green on top of orange on top of blue, etc.). You may wish to set the alpha parameter to be lower (say 0.25) to get a visual sense of the extent of class overlap.
With that said, I think you could see that:

There is little evidence of class separation between groups 0, 1 and 2 - there is significant overlap between them.
Group 2 appears to contain a wider range of feat1 values than the other two groups.
Group 0 is tightly clustered around about (0, -1).

Interpret seaborn pairplots


Is there a way to run tests prerequisite once and clean up in the end in whole unit test run

Question: I'm running series of testcases in multiple files, but I want to run the prereq and cleanup only once through out the run, please let me know is there a way to do it?
Answer: py.test -> session scoped fixtures and their finalization should help you
You can use conftest.py to code your fixture.


Simulation of dice rolling using struct

Question: I need a program that simulates dice rolling. I wrote code but I get 1 number on each roll. I need to get 5 numbers. Here is my code:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
using namespace std;

struct Dice
{
    int die[5];
};

void roll(Dice&);
void print(Dice);

int main()
{
    Dice myDice;

    roll(myDice);
    print (myDice);
    return 0;
}

void roll(Dice &num)
{
    for(int i = 0; i < 5; i++)
        num.die[i] = rand()%10;
}

void print(Dice num)
{
    for(int i = 0; i < 5; i++)
        cout << "You rolled: " << num.die[i] << endl;
}

The output should be similar to this:
You rolled 6 6 5 5 6
You rolled 5 1 1 5 3
You rolled 5 6 2 2 1
You rolled 6 4 3 4 4
You rolled 3 4 2 6 5

But my output is:
You rolled 6
You rolled 5
You rolled 5
You rolled 6
You rolled 3

Please, help me to figure it out!
Comment: Prefer the `` header.
Answer: You need something more like:
void print (Dice num)
{
   cout << "You rolled: ";
   for (int i = 0; i < 5; i++)
       cout << num.die[i];
   cout << endl;
}

Answer: Please check your logic more carefully.
1.  roll() fills each die with a random roll.
2.  print() prints each die's value.
In other words, your code prints the first roll of your desired output.  If you want to output all 5 rolls in a single line, then cout may have a way to do this, otherwise you can use printf() without a newline (then do an extra printf() with a newline at the end).
THEN you need to run this the 5 times you want in your example, meaning you want to loop over roll() and print() so you call them many times.
If this is your homework assignment, I recommend looking further into it before having us solve it for you.
Answer: Your code only rolls one die 5 times and not 5 dice 5 times. Make these changes
Dice myDice;
for (int i =0;i < 5;i++) {
roll(myDice);
print (myDice)
}

in main and
cout << "You rolled: ";
for (int i = 0; i < 5; i++)
cout << num.die[i]<< "\t";
cout << endl;

in the print function

Simulation of dice rolling using struct


Append to file using BinaryFormatter

Question: I'm using this code
    for (int i = 0; i < 3; ++i)
    {
        List<int> tl = new List<int>();
        tl.Add(5);
        tl.Add(4);
        using (var fileStream = new FileStream(@"C:\file.dat", FileMode.Append))
        {
            var bFormatter = new BinaryFormatter();
            bFormatter.Serialize(fileStream, tl);
            //fileStream.Close();
        }

        var list = new List<int>();

        using (var fileStream = new FileStream(@"C:\file.dat", FileMode.Open))
        {
            var bFormatter = new BinaryFormatter();
            //while (fileStream.Position != fileStream.Length)
            //{
            //     list.Add((int)bFormatter.Deserialize(fileStream));
            //}
            list = (List<int>)bFormatter.Deserialize(fileStream);
            //fileStream.Close();
        }
    }

I expect .dat file will be

5 4 5 4 5 4

but it's only

5 4

also this code return also

5 4

        List<int> tl = new List<int>();
        tl.Add(5);
        tl.Add(4);
        using (var fileStream = new FileStream(@"C:\file.dat", FileMode.Append))
        {
            var bFormatter = new BinaryFormatter();
            bFormatter.Serialize(fileStream, tl);
        }

        tl.Clear();
        tl.Add(3);
        tl.Add(2);
        using (var fileStream = new FileStream(@"C:\file.dat", FileMode.Append))
        {
            var bFormatter = new BinaryFormatter();
            bFormatter.Serialize(fileStream, tl);
        }

        var list = new List<int>();

        using (var fileStream = new FileStream(@"C:\file.dat", FileMode.Open))
        {
            var bFormatter = new BinaryFormatter();
            list = (List<int>)bFormatter.Deserialize(fileStream);
        }

it looks like it de-serialize only first portion that was appended.
why data don't append?
UPDATE:
So the solution is:
        var list = new List<int>();

        using (var fileStream = new FileStream(@"C:\file.dat", FileMode.Open))
        {
            var bFormatter = new BinaryFormatter();
            while (fileStream.Position != fileStream.Length)
            {
                var t = (List<int>)(bFormatter.Deserialize(fileStream));
                list.AddRange(t);
            }
        }

Answer: You are adding three lists of ints, one after the other, and only reading the first one back.  I think what your intent may be is to append to a (single) existing list, in which case you'd have to

Read your list back into memory
Add your new elements
Write the list back out to the file in overwrite (not append) mode
Answer: BinaryFormatter is not listed as being appendable. As it happens, you can usually get away with deserializing multiple times until you get to the EOF (and merging manually), but: there are other serializers which are explicitly designed to be appendable. For example, protocol buffers is an appendable format: concatenation is identical to merge. Further: if the outer element is a list, appending to the file is identical to adding to the composes list.
With protobuf-net, this is just:
for (int i = 0; i < 3; ++i)
{
    List<int> tl = new List<int>();
    tl.Add(5);
    tl.Add(4);
    using (var fileStream = new FileStream(@"C:\file.dat", FileMode.Append))
    {
        Serializer.Serialize(fileStream, tl);
    }

    using (var fileStream = new FileStream(@"C:\file.dat", FileMode.Open))
    {
        list = Serializer.Deserialize<List<int>>(fileStream);
    }
}

At the end of each loop iteration, list (i.e. after deserialization) has 2, then 4, then 6 elements.
Answer: As Marc Gravell mentioned BinaryFormatter isn't appendable which means you'll need to reserialize every time you need to modify the file.
Example:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;

class Program
{
    const string file = @"C:\temp\file.dat";

    static void Main()
    {
        for (int i = 0; i < 3; ++i)
        {
            List<int> tl = new List<int>();
            tl.Add(5);
            tl.Add(4);

            AppendToDisk(tl);
        }

        var list = ReadFromDisk<int>();

        foreach (var item in list)
        {
            Console.Write(item);
        }
    }

    private static void AppendToDisk<T>(IEnumerable<T> collection)
    {
        var existing = ReadFromDisk<T>().ToList();

        existing.AddRange(collection);

        PersistToDisk(existing);
    }

    private static void PersistToDisk<T>(ICollection<T> value)
    {
        if (!File.Exists(file))
        {
            using (File.Create(file)) { };
        }

        var bFormatter = new BinaryFormatter();
        using (var stream = File.OpenWrite(file))
        {
            bFormatter.Serialize(stream, value);
        }
    }

    private static ICollection<T> ReadFromDisk<T>()
    {
        if (!File.Exists(file)) return Enumerable.Empty<T>().ToArray();

        var bFormatter = new BinaryFormatter();
        using (var stream = File.OpenRead(file))
        {
            return (ICollection<T>)bFormatter.Deserialize(stream);
        }
    }
}

Append to file using BinaryFormatter


Convergence of polynomials pointwise implies convergence uniformly

Question: Let $P_n$ be a sequence of real polynomials of degree $\le 10$. Suppose $P_n(x)$ converges pointwise to 0 as $n \rightarrow \infty$ and $x \in [0,1]$. Prove that $P_n$ converges uniformly to 0.
Now the hint said to consider $P_{10}$ as a vector space and consider the open ball of radius $R$ around $0 \in P_{10}$. For some basis, define a mapping $$f: P_{10} \to \mathbb{R}$$ by
$$f: \mathbb{R}^{11} \ni v \to \sup_{[0,1]}\, \Bigl|\sum_{k=0}^{10} v_kx^k\Bigr|$$  where $v$ is the co-ordinate representation of $p \in P_{10}$ according to some basis. Note $f \in \mathscr{C}$, i.e. is continuous. Now, since $B_R (0) \subset P_{10}$, if we can show that $M =\max{f(B_R (0))} \to 0$ as $R \to 0$, we have uniform convergence.
Could someone help explain why $M \to 0$ implies uniform convergence? Moreover, how to show that this is true.
I've seen linear algebra methods, but I want to see an analysis method.
Comment: Once you've written $\sum_{k=0}^{10}\nu_kx^k$ *some* basis becomes *the* basis $x^k$.
Answer: You have not used point-wise convergence in your construction. You need  to prove (besides to what you've mentioned) that

$$
p_n(x)\to 0,\ \forall x\in[0,1]\quad\Rightarrow\quad \mathbb{R}^{11}\ni\nu_n\to 0.
$$

Then the rest is obvious
$$
\|\nu_n\|\to 0\quad\Rightarrow\quad\nu_n\in B_{R_n}(0),\ R_n\to 0\quad\Rightarrow\quad \|p_n\|_\infty=f(\nu_n)\le M_n\to 0.
$$
P.S. To prove that $M\to 0$ consider the estimate
$$
\left|\sum_{k=0}^{10}\nu_k x^k\right|\le \sum_{k=0}^{10}|\nu_k||x^k|\le
\sum_{k=0}^{10}|\nu_k|\|x^k\|_\infty\le \sum_{k=0}^{10}|\nu_k|.
$$
Comment: @AnthonyPeter You *need to prove* that pointwise convergence implies $\nu_n\to 0$, i.e. $R_n=\|\nu_n\|\to 0$. A possible way: choose $11$ distinct points $x_m\in[0,1]$ and build a matrix $A$ so that $A\nu_n=[p_n(x_0)...p_n(x_{10})]^T\to 0$. What can you say about $\nu_n$?
Comment: This estimate being so because our domain is $[0,1]$, yes?
Comment: @AnthonyPeter Right, otherwise $|x^k|\le \|x^k\|_\infty\le C_k<+\infty$
Comment: Perhaps I'm missing something. Is $R \to 0$ point-wise convergence? Where does it get its metric? Are we not taking the metric induced by the sup metric on $C([0,1[)$? I suppose I'm a bit confused in regards to how to include point-wise convergence.


jQuery .closest default context

Question: The documentation for jquery's closest says the following:

.closest( selector [, context ] )
  ...
  context  Type: Element  A DOM
  element within which a matching element may be found. If no context is
  passed in then the context of the jQuery set will be used instead.

As I understand it, the bolded text means that the two statements should be equivalent:
set.closest("a");

set.closest("a", set.context);

where set is some jquery set.
However, this does not seem to be the case:

var context = $("#inner")[0];
var set = $("#el", context);

// the set's context is correctly the "inner" element
set.text("context: " + set.context.id);

// if the set's context is used, this closest should match nothing, but it matches and sets the color
set.closest("#outer").css("color", "red");

// with the context explicitly set, the "outer" is not found and no background color is set
set.closest("#outer", set.context).css("background-color", "blue");
#outer{
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

As you can see, when no context is explicitly set, the set's context does not seem to be used as the #outer element is found by closest.  When explicitly set, the #outer is correctly not found.
Is the documentation just incorrect or am I missing something?
Comment: I guess the documentation is wrong. It doesn't look like the context of the jQuery set is used if the context isn't specified.
Comment: Why you did it like `var set = $("#el", context);` ? As per doc reading what I am getting is, `closest()` try to match the `selector` expression up the ancestor chains, till it finds a match. Now the second argument the method `closest()` is just to give it the a limit till that point it will keep hunting for a match. And if no second argument it will be decided by the Jquery where `body` might be the last parent.
Comment: So your code looks like doesn't the proper example to go against the Jquery doc.
Comment: It's somewhat confusing because jQuery's `closest()` doesn't always use the context, it uses a regex to determine if a context is needed, like this `/^[\x20\t\r\n\f]*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\([\x20\t\r\n\f]*((?:-\d)?\d*)[\x20\t\r\n\f]*\)|)(?=[^-]|$)/i`, so just changing it to `set.closest("#outer:first")` makes it use the context, and no longer match the element, while `$('#el').closest("#outer:first")` still matches the element like it should.
Comment: I would prefer using `parents( selector )` for parent element and in your code simply use id selector
Answer: This is clearly a bug, and not how it was intended to work.
The source for closest() is
function (selectors, context) {
    var cur,
        i = 0,
        l = this.length,
        matched = [],
        pos = rneedsContext.test(selectors) || typeof selectors !== "string"
           ?
           jQuery(selectors, context || this.context)
           :
           0;

    for (; i < l; i++) {
        for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) {
            // Always skip document fragments
            if (cur.nodeType < 11 && (pos ? pos.index(cur) > -1 :

            // Don't pass non-elements to Sizzle
            cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors))) {

                matched.push(cur);
                break;
            }
        }
    }

    return this.pushStack(matched.length > 1 ? jQuery.unique(matched) : matched);
}

What's notable is the way pos is defined, it's the collection to be searched for a closest parent element, and rneedsContext is the regex
/^[\x20\t\r\n\f]*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\([\x20\t\r\n\f]*((?:-\d)?\d*)[\x20\t\r\n\f]*\)|)(?=[^-]|$)/i

If the passed in selector doesn't match that regex, no context is used whatsoever, pos would equal 0, and the check for cur in that collection is just skipped all together, which seems mighty strange.
A quick test shows
var reg = /^[\x20\t\r\n\f]*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\([\x20\t\r\n\f]*((?:-\d)?\d*)[\x20\t\r\n\f]*\)|)(?=[^-]|$)/i;

reg.test('#outer');       // false, no context used
reg.test('#outer:first'); // true, context used
reg.test('#outer:eq(0)'); // true, context used

So if you add a pseudo selector, it suddenly uses the context ?
I doubt this is what was intended, and it seems like a strange thing to do, and it surely doesn't do what the documentation says it should do.
Comment: Looking at the release notes for 2.1.4 there's no changes to `closest`, and looking at the source for 2.1.3 `closest`, and specifically the `pos` variable, is defined the same way as in the last ten versions of jQuery. Testing with 2.1.4 in jsFiddle seems to still have the same issues as well, so I think this is a bug, hats of to James for finding it, it is a strange one.
Comment: @adeneo Yup, I think we're on the same page.  Thanks.  I thought it was broken but needed someone to bounce it off of.  Your answer (and discussion) were very helpful.  I'll submit a bug report.  They either need to change the documentation and remove this.context from pos, or make the non-pos version use this.context too.
Comment: _"The source for closest() is"_ Which version is source at post ? See http://stackoverflow.com/questions/34580013/jquery-closest-default-context/34580530#comment56906623_34580530
Comment: @guest271314 - that's from 1.11.2, but it's the same for all somewhat current versions
Comment: Tried both jsfiddles ? Issue appear to have been addressed at lastest ? Though `.text()` not set ? Or, is jsfiddle not loading latest ? Using jQuery object for `DOM` element sets `background-color` `set.closest("#outer", $(set.context)).css("background-color", "blue");`
Comment: Why does using jQuery object set `background-color` https://jsfiddle.net/qeb26cox/  ?
Comment: Thanks adeneo, I had a really quick look at the source last night but hadn't gotten to the point of looking at what `rneedsContext` was actually doing.  Now I'm curious what they're actually trying to do there.  I might skim the overall jquery source to see where else they use it to see why it's needed.
Comment: @JamesMontagne - it sure seems strange that they use a regex like that to determine wether or not to use context, it surely can't be intended that if you add pseudoselectors like `;eq()`, `:first` etc. it suddenly works as documented, someone did something strange, and noone has spotted it in years ?
Comment: The only thing I could figure, is that it would probably be even stranger if `closest()` used the context from the passed in collection (the original context), as that would seem strange to most people when they do `$('#inner', '#outer').closest('body')` and find nothing, because the search is suddenly limited to `#outer`.
Comment: @adeneo actually, looking at it, the use of context is actually in the loop condition whereas `pos` is doing something else entirely.  It seems like some additional check is needed when that regex matches (and maybe rightfully so) but that the loop condition is the actual bug
Comment: Seems almost like `matchesSelector` doesn't work for these matched by the regex so it gets the set first and checks if it is contained within.  If it doesn't match the regex then it uses `matchesSelector`.
Comment: I think that if `pos` is **not** `0`, or in other words if `pos` is a jQuery collection, it uses `pos.index(cur) > -1` to determine wether or not to push the element to the array. Of course, that checks to see if `cur` is inside `pos`, like you'd expect when passing in context. If `pos` is **not** a jQuery collection, but `0`, the regex test failed, and the condition checks that `cur` is an element, and that it matches the selector passed to `closest()`, before adding `cur` to the array, all done without any checks for context. I think the condition works, as long as `pos` is set correctly.
Comment: It looks like `matchesSelector` tries to use the browser's native `matches`.  Of course `matches` won't work with things like `:gt` which are created by `jquery` so `matchesSelector` cant' be used if that is part of the selector.  So the `pos` thing is for those edge cases.  The edge case code uses context as documented, the simple case (browser supported selector) doesn't
Comment: But `matchesSelector` just does `matchesSelector(element, selector)` and returns true if the element passed in can be matched by the selector, there's no context used there, neither from the original collection, nor the one passed to `closest(selector, context)`, so if `pos` is `0` the context is just skipped. Depending on how you look at it, they either need to figure out a way to pass context to `matchesSelector`, or set `pos` correctly on just about any context other than `window`, so I agree, the issue could be fixed at that point as well.
Comment: Yes, this surely can't be what they intended. I do see that they have extended the regex for `pos` somewhere between 1.7 and 1.8 to match more cases, but it still has the same issues ?
Comment: @adeneo Was attempting to modify Attribute Not Equal Selector [name!="value"] selector recently , had to remove `"^"` at beginning of `RegExp` for `"ATTR"` at line 712. `needsContext` of `rneedsContext` appear to be at line 720 . Not certain how to access , change `matchExpr` , tried thus far using  `$.expr` , though `matchExpr` regexps not extended from `Sizzle` ?
Comment: @guest271314 - `rneedsContext` is just an alias for `jQuery.expr.match.needsContext`, that's where the regex really is, but just changing the regex at runtime probably won't work as it's not passed by reference *(of a value)*, and it won't change all the places it's used etc.
Comment: @adeneo fwiw,  plnkr of deleted Question "How to extend, modify, or override jQuery Attribute Not Equal Selector [name!="value"] selector?" http://plnkr.co/edit/uavSs1jcaMarbDKG1xfe . Was able to return expected result for `ul[class!='active']`, save for selector where space was within selector `body [class!='active']`. Also tried to create a `[data]` selector , similar to `[class]` or `[id]` , which would return all elements having `data-*` set at `html` or `jQuery.data()` . Documentation on how to adjust or extend selectors using `$.expr` appear sorely missing from jQuery documentation
Comment: Adjusted lines 713, 1699 at `script.js` at plnkr
Comment: @adeneo `.needsContext` does not appear to be extended to property of `$.expr.match` ? Try `$.expr.match` at `console`

jQuery .closest default context


Last page and First page Gives Exception in MVC paging

Question:  protected void gvValues_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvValues.PageIndex = e.NewPageIndex;
            this.FillData();
        }

paging works fine but when I clcik on last or First it gives me Error as
Input string was not in a correct format.

Comment: OK, I did , what shall I do also ?
I tried to make switch loop to make index correctly but I didn't know where shall I put this loop
Comment: Can you look at my answer ?
Answer: Write following code :
protected void gvValues_PageIndexChanging(object sender, GridViewPageEventArgs e){

    GridView1.PageIndex = e.NewPageIndex;

    //rebind your gridview - GetSource(),Datasource of your GirdView
    GridView1.DataSource = GetSource();
    GridView1.DataBind();

}

Comment: I bind it in my original code look at my updated question, and my paging works correctly in 123456 ... but when I press last page it gives me this exception


Can one's musical 'ear' be trained with practice and dedication?

Question: These great composers of the past: Beethoven, Mozart, Bach, Tchaikovsky, Brahms, and my personal favourite Elgar, all lived in a time where they had only a piano to work out their various symphonies or their serenade for strings for example, when it came to notating their work, preparing it for orchestration.
This would surely mean that their ear for music would have to almost be of 'perfect pitch' would it not? This is something you are born with I believe. The great composers would hear (Beethoven was of course deaf in his later life) the music (as stupid as it sounds...in their head) and then, naturally, notate the chosen melodies, harmonies on the manuscript. They did not have an ability to plug in a keyboard to a computer; no software for playback and so on.
My question is, if one's musical ear (as I have found) is not up to that... craftsmanship shall we say, can it be trained as such? Are there any good examples or best practices for training your ear to gain almost perfect pitch, where you can hear it in your head and then write it down almost immediately?
Elgar for example, would pore over Brahms's 3rd Symphony, reading it all the hours god sent, but in order to hear that, he would have to have an idea of what that sounded like. Does a bad musician translate to someone who cannot hear this, unless it is played aloud?
Comment: And for what it's worth a piano is generally considered the **best** instrument to compose or arrange on. It has all the range you need and a relatively smooth gradient of timbre between registers.  The general wisdom is that if if sounds good arranged on a piano it will probably sound good everywhere else as well.
Comment: Actually I  listened to lectures by Professor Robert Greenberg from Berklee collage, on the masters of classical music. He said just that, Mozart had everything in his head, he wrote a whole symphony hours before it had to be played. He had all the parts, everything, inside.
Comment: _This would surely mean that their ear for music would have to almost be of 'perfect pitch' would it not?_ Why is that? What's wrong with a piano?
Answer: Our ears can be trained. The notion that you're either born with "perfect pitch" or you're not is a myth, and "perfect pitch" itself is relative and comes in different forms.
Berklee College of Music : Ear Training

Ear training, one of Berklee's core requirements, teaches students how
  to hear and apply melodic, rhythmic, and harmonic musical forms.
Ear training assists instrumentalists and vocalists in mastering the
  technical and stylistic aspects of their instruments, writers in
  notating music they have created or arranged, and listeners in
  understanding what they are hearing.
First-semester placement is based on your music placement test scores,
  taken during your initial week at the college...

See:
Is it possible to train perfect pitch ?
Do "Perfect Pitch Programming" tracks actually work?
Perfect & Relative Pitch, and its relation to genetics?
And many others.
Answer: Your focus on 'perfect pitch' is not all that helpful.  Yes, a composer needs an 'inner ear' but, as you say, there is generally a piano for pitch reference.  So let's not get too hung up on 'perfect pitch'.  A composer certainly needs excellent 'relative pitch' - having established the pitch of C, he must just KNOW what A sounds like.  And what a chord containing several notes sounds like.  And how it will sound, and fit in to the music, when played by different instruments.  And he needs to be able to 'read' a score, hearing in his head what it will sound like.  It really doesn't matter THAT much whether he 'hears' it at a strict A=440 pitch or not though!
Yes, of course all this develops with experience, with practice and with good teaching.
Many of us here will be accustomed to 'composing' by trial-and-error.  Maybe even by constructing instrumental music that way in a sequencer or score-writing program.  And these can be excellent tools for giving a rough idea of what a musical idea will sound like, of trying out something that might otherwise be considered too risky to put in front of live players with limited rehearsal time.
And remember, as well as the part of the music business where a rock group may be able to inhabit a studio for weeks while trying out material, or a track may be endlessly developed by trial-and-error on a computer, there's the world where a studio and musicians are booked, the music is handed out and that is what will be played.  It has to be right.  And THAT is where the composer and arranger's craft is tested! The definition of a professional is not so much being able to produce occasional genius, but being able to consistently produce high-quality product, and produce it QUICKLY.  Otherwise, it's a lousy hourly rate :-)

Can one's musical ‘ear’ be trained with practice and dedication?


Waiting for commands to be complete

Question: I am working with a winform that runs a cmd in the background, redirecting input and output asynchronously.
Currently, the winform iterating through an array of commands, writing each to the cmd via the StreamWriter the StandardInput is redirected to. How can I force the loop to wait until the present command is complete in the cmd before writing the next line in?
EDIT: I took out all of my actual project code, and replaced it with this, a stripped down version of what I'm trying to do, only including components of my project relevant to my question.
public partial class Form1 : Form
{

    public delegate void WriteToConsoleMethod(string text);
    Process _process;

    string[] _commands =
    {
        "echo hello world",
        "echo my name is T.K.",
        "echo Here is a list of commands"
    };
    public Form1()
    {
        InitializeComponent();
        ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd")
        {
            RedirectStandardError = true,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        _process = Process.Start(processStartInfo);
        _process.OutputDataReceived += new DataReceivedEventHandler(new DataReceivedEventHandler(DataReceived_EventHandler));
        _process.ErrorDataReceived += new DataReceivedEventHandler(new DataReceivedEventHandler(DataReceived_EventHandler));
        _process.BeginErrorReadLine();
        _process.BeginOutputReadLine();
    }

    private void DataReceived_EventHandler(object sender, DataReceivedEventArgs e)
    {
        IAsyncResult result = this.BeginInvoke(new WriteToConsoleMethod(writeToConsole), new object[] { e.Data + Environment.NewLine });
        this.EndInvoke(result);
    }

    private void writeToConsole(string output)
    {
        txtbxConsole.AppendText(output);
    }

    private void btnBegin_Click(object sender, EventArgs e)
    {
        foreach (string command in _commands)
        {
            _process.StandardInput.WriteLine(command);
            // I want a way to pause here until the cmd has finished processing the command.
        }
    }
}

Comment: Sure - give me a minute to get it together.
Comment: Can you post the code for the run method?
Comment: I'm sorry there's a lot of moving parts I'm not showing you, but there's more code than I'm comfortable having people spend time to read over. Have I included enough code to clarify the context?
Comment: @sgmoore @JohnFx I wrote up a simple winform that only has the components of the winform I'm working on that are relevant to my question. I hope this helps to clarify what I'm asking.
Answer: I don't think there is anything built-in that will support that. However you could send your own special command and then wait until you see this in the output for example ,
 something like :
    const string Separator= "---Command Completed--\xE3\xE2\xE1\xE0\xE3";
    // Has to be something that won't occur in normal output.

    volatile bool finished = false;

    private void button1_Click(object sender, EventArgs e)
    {
        foreach (string command in _commands)
            Run(command);
    }

    private void writeToConsole(string output)
    {
        if (output.IndexOf(Separator) >= 0)
            finished = true;
        else
            richTextBox1.AppendText(output);
    }

    private void Run(string command)
    {
        finished = false;
        _process.StandardInput.WriteLine(command);
        _process.StandardInput.WriteLine("@echo " + Seperator);
        while (!finished)
        {
            Application.DoEvents();
            System.Threading.Thread.Sleep(100);
        }
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        finished = true;
    }

Comment: Yeah, if I had a string that occurred if and only if the command was finished, that would be a good solution. However, I can't count on knowing what my commands will output. For situations where you can be certain what will be outputted, though, this is a good solution.
Answer: Assuming you are using System.Diagnostics.Process, then you probably need something like
ProcessStartInfo pi = new ProcessStartInfo(cmd);
pi.Arguments = ...
pi.WorkingDirectory = ...
Process myProcess = Process.Start(pi);
myProcess.WaitForExit();

Comment: I am using System.Diagnositc.Process. I don't want to wait for exit, though. I don't want _proc to exit each time a different command is run. I've edit to include my process initialization method, as well.
Answer: I ended up solving this problem by wrapping my interaction with the command prompt into a separate class and instead of maintaining one prompt for all of the actions, I started up another prompt for each call. Then I take advantage of WaitForExit() to synchronize my threads.
After each command, I write in an exit command to close the process. I scan the output for exit calls, and when I find one, I use the context of that line to save the workspace so that the prompt for the next command will be made from the same working directory. I also had to hook up a DataRecievedEventHandler to parse out the header and exit calls before forwarding the EventHandlers to the winform.
The thing that's nagging me about this solution is that if the output of whatever process I'm running prints out exit, output scanner will behave as though it found the original exit. I employed the same solution sgmoore had in his answer - I write in exit [UNIQUE STRING] to the prompt, and scan the output for that, but I'm sure that's far from best practice.

Waiting for commands to be complete


Calculation on the Power of Means (Probability)

Question: The problem is:
Suppose $X\ge 0$ is a random variable, $p(x)$ is its probability density function. If $\operatorname EX$ exists, $r>0$, prove:
$$\operatorname EX^r = \int_0^\infty rx^{r-1}P(X>x) \, dx.$$
I see $\operatorname E X^r$ as $\int_{-\infty}^\infty x^r p(x) \, dx$, while $$\text{RHS}=\int_0^\infty \left(\int_x^\infty p(t)\,dt \right) dx^r = \left.\left(x^r\int_x^\infty p(t) \, dt\right)\right|_0^\infty-\int_0^\infty x^r p(x) \, dx.$$
However, when calculating $x^r \int_x^\infty p(t) \, dt$ as $x\to \infty$, it comes to a $0 \times \infty$ problem. How can I solve it?
Thanks.
Comment: https://math.stackexchange.com/q/172841/321264.
Answer: \begin{align}
& \int_0^\infty rx^{r-1}P(X>x) \, dx \\[8pt]
= {} & \int_0^\infty rx^{r-1} \left( \int_x^\infty p(w)\,dw \right) \, dx \\[8pt]
= {} & \iint\limits_{(x,w)\,:\, 0\,<\,x\,<\,w} rx^{r-1} p(w) \, d(x,w) \\[8pt]
= {} & \int_0^\infty \left( p(w) \int_0^w rx^{r-1} \, dx \right) \, dw \\[8pt]
= {} & \int_0^\infty w^r p(w)  \, dw
\end{align}
You said $X\ge0,$ so this last integral is only from $0$ to $+\infty,$ not from $-\infty$ to $+\infty.$
Comment: Oops! I forgot the condition that $X \ge 0$ !
Answer: $$E(X^r)=\int_0^{\infty} r x^{r-1} [1-F_X(x)]dx$$
by parts you get
$$E(X^r)=\Big[x^r(1-F_X(x))\Big]_0^{\infty}+\int_0^{\infty} x^r f_X(x)\,dx$$
$$x^r\left[1-F_X(x)\right]_{x=\infty}=\frac{x^r}{\frac{1}{1-F}}=\frac{\infty}{\infty}\rightarrow 0$$
Using the l'hopital $r$ times
Thus you are all set
Comment: Is it always true that $x^rP(X>x)\to 0 $ as $x\to \infty$? What if we take $p(x)=\frac{2}{x^3}\cdot \mathbb{1}_{[1,+\infty)}$ and $r=2$. Then, $x^2P(X>x)\to 2$ as $x\to \infty$. I think we have to assume that $EX^r$ is finite in order to get $x^rP(X>x)\to 0$. Am i somewhere wrong?


Set-ADUser with PowerShell's ActiveDirectory Module: changing the user's OU

Question: I was wondering if it was possible to change the OU (organizational unit) of a user in ActiveDirectory using PowerShell.  I have a script that should update many of the fields.  I am using the Set-ADUser command to update, but I can't seem to find a flag that will allow me to update the OU.  Below is the the Set-ADUser command I am using currently.  The variables are set earlier in the script and shouldn't be relevant to the question.
set-ADUser -identity $samName -GivenName $firstName -Surname $lastName -Department $department -Description $description -Manager $manager -AccountExpirationDate $acctExp -Organization $org

I also have a script that creates users.  That script allows me to set the OU.  That leads me to believe that I could change the OU after creation.  Below is the command I use to create the user.  Again, the variables are set earlier in the script.
New-ADUser -Name $dName -SamAccountName $sam -GivenName $firstName -Surname $lastName -Path $OU -AccountPassword $passwd -ChangePasswordAtLogon $true -Department $department -Description $description -Manager $manager -Organization $org

If there is a flag for the Set-ADUser command that would be great, otherwise, any help is appreciated.  Thanks.
Answer: You can use the move-adobject:
Move-ADObject 'CN=myuser,CN=Users,DC=mydomain,DC=com' -TargetPath 'OU=mynewou,DC=mydomain,DC=com'

or
Get-ADUser $name| Move-ADObject -TargetPath 'OU=mynewou,DC=mydomain,DC=com'

Comment: Minor nitpick - shouldn't the second command say `DC=mydomain` instead of `OU=mydomain`?
Comment: @CodyPoll Yes! Fixed. ;)
Comment: Wonderful.  I was trying to find a Change-ADUser or something like that.  Move makes a lot more sense.  Thank you.


Lebesgue measure of complement of this set

Question: This question was part of  my real analysis quiz and I need help in correctly proving it.

For each a $\in \mathbb{R}$ , let $ S_a$ ={$(x,y,z)\in {\mathbb{R}}^3 | x^2+y^2+z^2= a^2$} Let $E=\bigcup_{a\in \mathbb{R}/ \mathbb{Q}} S_a$ Then does every open set containing $E^C$ has finite Lebesgue measure ?

I can't think why measure must be finite , even intutively I think that measure must be infinite. I am looking for a rigorious argument why measure must be finite. I am not really good in Lebesgue measure but really want to learn.
Comment: Your claim is false. For example, $\mathbb{R}^3$ is an open subset of $\mathbb{R}^3$ containing $E^C$ and does not have finite measure.
Answer: (edit) I assume you meant to say that there is not open set contained in E, with positive measure, so I answered that question.
E is $\mathbb{R}^3$, except for the points with rational norm ( $||\mathbf{x}||\in \mathbb{Q}\Rightarrow \mathbf{x}\notin E$).
The idea here is that, $F:=\mathbb{R}^3-E$ is dense in $\mathbb{R}^3$ (and $\overline{F}=\mathbb{R}^3$)
Then, you can show that, there are no open sets in $E$, with non cero messure, since they would intersect with $F$.
Let me know if you need more details.


Compute $\pi_1(S^1 \times (0,\infty))$

Question: Compute  $\pi_1(S^1 \times (0,\infty))$
My attempt : By uisng the theorem $\pi_1( X\times Y) $ is isomorphic to $\pi_1(X) \times \pi_1(Y)$ if  $X$ and $Y$ are connected
we have  $\pi_1(S^1 \times (0,\infty))=\pi_1(S^1) \times \pi_1(0, \infty)$
Since $(0,\infty)$ is contractible so $\pi_1(0, \infty)=0$ and $\pi_1(S^1)=\mathbb{Z}$
$\implies  \pi_1(S^1 \times (0,\infty))=\pi_1(S^1) \times \pi_1(0, \infty)=\mathbb{Z} \times \{0\}=0$
Therefore  $\pi_1(S^1 \times (0,\infty))=0$
Is it true ?
Comment: $\mathbb Z \times \{0\}\neq 0$ nor $\{0\}$, even set-theoretically.
Comment: What you probably meant was $\Bbb Z \times 0  = \Bbb Z$, in which case you're fine...almost. What's actually true is that the two groups are isomorphic (possibly by the isomorphism that sends $1$ to $-1$, for instance, unless you show otherwise). People usually write "=", but it's worth remembering that there's a hidden isomorphism in there.
Comment: More directly, you can use the fact that the contractibility of $(0, \infty)$ implies that $S^1 \times (0, \infty)$ and $S^1$ are homotopy-equivalent (and unravelling the definition gives you an explicit isomorphism between their fundamental groups).
Answer: So close. You made one mistake. In the category of groups, $A \times 0 \simeq 0$ does not hold. In fact, for groups, $0 = 1$, so $A \times 0 \simeq A \times 1 \simeq A$.
So $\mathbb{Z} \times 0 \simeq \mathbb{Z}$.

Compute $\pi_1(S^1 \times (0,\infty))$


Post image via webservices

Question: I tried to create a node through external application using web services. This having only two fields node title and cck field image. i will grateful if anyone share the JSON format to post the images. I tried using format that mentioned below link but its failed means image not uploaded.
https://www.drupal.org/node/2195165
Any one guide me do this.
Thanks..
Answer: URL: http://example.com/service_enpoint/file
Method: POST
file: (file to be uploaded in base 64 encoded format)
filename :plus-box.jpg
uid: 55
The jpg file should be uploaded in base 64 encoded format.
As response you will get a fid , which you will have to pass in the image field while creating the node.

Post image via webservices


Configure 4-4 Tabla for Bansuri Practice

Question: The video below (starting at 2:50) shows the Instructor turning on the 4-4 Tabla player.
How did he configure the Tabla player? He's a wonderful Instructor, but rather vague on these points.
In my case, I will likely get a computer/app-based Tabla player.
What is the best way to configure it? For instance, when I download various tabla players for Andriod, it lists various taals and it shows numerous hand-dials.
Answer: Following three parameters need to be configured:
The Shruti (Drone, or the reference note for music that is played)
In the flute that is included in your question, it is E (White key 3rd)
The Taal
It determines the number of beats per cycle, and the sounds of those beats
The Speed
Speed of the cycle-how fast does one whole cycle complete.
One may find two settings in this category.
Cyclic Time Period: It lets you mechanically compress or expand the Taal cycle without changing the sounds in the Taal. It's like controlling the speed of a fan or a wheel.
Laya: It lets you select a slower version of the same Taal, which changes the sounds of the beats chosen in that Taal.


What is the time function of this loop

Question: <code>For (i=0, i < n, i++) // n+1
{
    for(j=0; j < n, j++) // n * (n+1)
    {
       C[i][j]+ B[i,j]; // n * n
    }
}
</code>
The instructor said the time function is f(n) = 2n^2 +2n +1
How come it's not 2n^2+ 2n + 2 because both loops run one extra time when i=n and j=n?
Answer: Each time we increment i, we check if the new value becomes equal to or greater than n, so we perform the comparison n + 1 times (n times when i <n and an additional comparison when i becomes equal to n). the same thing for j => (n+1) * (n times when i<n).
So, n*n+(n+1)*n+(n+1)=2n^2+ 2n +1

What is the time function of this loop