How to select a DIV if its child has any children?

Question: I'm trying to select any divs on a page if a certain child of theirs has any children of its own.
Here's how the structure looks:

So I want to select all divs with id ID-SOME_LONG_ID only if the GK DIV has any children.  It may or may not.
ID- stays the same and SOME_LONG_ID changes with each one.
The other one SOME_LONG_ID is the same on as the parent, and after the # it's a 16 digit number that is random.
Would using Regex be a good idea to look for them or maybe using jQuery's .children() like $( ".GK" ).children()?
Thank you!
Answer: Use :has(), :empty, and :not()
$('#ID-SOME_LONG_ID:has(.GK:not(:empty))')

However, note, :empty will fail if you want real children without text nodes. In that case you can do
$('.GK').filter(function() {
  return $(this).children().length > 0;
});

Comment: @SS113, remove the :not like `$('#ID-SOME_LONG_ID:has(.GK:empty)')`
Comment: Thanks but I may have switched the logic on myself.. what if I want to select only ones  where `GK` doesn't have any children?
Comment: @SS113, if the answer didn't work or you are still facing trouble let me know so I can help
Comment: Thank you so much!  It seems to be selecting the right ones now but I can't see how to hide the selected DIVs by adding `.setAttribute("style","display: none;")`.  I know it's not part of this question so sorry about that.
Comment: @SS113, instead of `.setAttribute("style","display: none;).` try `.hide()` or `.attr("style","display: none;").`
Comment: Thanks! It worked with `.attr()` but it's hiding the `` from my example originally and not the whole ``.  This is what my code looks like now: `var selectDIVS = $('.GK').filter(function() { return $(this).children().length > 0; });`
Comment: @SS113, can you put it up in a fiddle?
Comment: Here's what it's doing: https://jsfiddle.net/vpec3aw6/  it's hiding the GK DIV and its children but not the main one.  I need it to hide everything **if** GK has children.
Comment: @SS113, if you are still facing trouble let me know so I can help
Comment: Thank you so much for the amazing help! I had to use a different DIV since there were more nested into each other but ultimately I got it to do what I need!


representing an iteration loop in math

Question: I have a computation step where
$$
a_{n+1} = f_1(a_n)
$$
That is, $a$ at step $n+1$ is some function $f_1$ of $a$ at step $n$.
I want to iterate till an $N$ where $f_2(a_N) = b$ (where $f_2$ is some other function)
and then at that $N$ compute  $x = f_1(a_N)$.
Question is how do I write this in a nice compact mathematical formula.
Thanks in advance
Answer: Assuming you know that there will be such an $N$ such that $f_2(a_N) = b$, then you can say let $N:= \min\{n \in \mathbb{N} : f_2(a_n) = b\}$. Then saying $x = f_1(a_N)$ makes sense.
Answer: I think what you've done is just fine. If you want to dress it up, you could write something like
$$
x = f_1(a_H)
$$
where
$$
a_0 = \text{whatever your initial value is}
$$
$$
a_k = f_1(a_{k-1})
$$
and
$$
H = \min \{ k \mid f_2(a_k) = b \}
$$

representing an iteration loop in math


When to use drush_log() or drush_set_error()?

Question: I just trying to show an error message with drush and I see that you can achieve this with
drush_set_error('NON_EXISTENT', 'Message');

and with
drush_log('Message', 'error');

In both cases you will see the same error message, I read the functions documentation but I can't figure out are the differences between they?
Answer: In general, you should avoid using the status code 'error' when calling drush_log directly. Use drush_log to signal non-terminal events, usually with a status code of warning or notice.
If a function fails and cannot continue, the best thing to do is to exit with return drush_set_error(...);. This sets internal state, so that Drush knows that there was an unrecoverable error, and calls through to drush_log('Message', 'error');.


IIS 7.5 Missing Authorization Header

Question: I have a website running an ISAPI filter providing SSO functionality, as well as anonymous & basic authentication.
The ISAPI filter populates the "Authorization" header of each request with basic credentials e.g. basic base64EncodedString (username:password), which I can see using Fiddler.
Next I have an HTTP Module picking up the basic credentials from the "Authorization" header, decoding them and placing the username in a new header value. The new header is then picked up by Tridion and used by the inbuilt SSO module.
This solution works in IIS6, but not in IIS7.5; in IIS7.5 the "Authorization" header is not present in the request. I checked for the header both in the HTTP Module, and in a dummy ASPX page.
Answer: Although IIS 7 supports ISAPI filters, Microsoft recommends that you extend Web server functionality by using modules instead of by using ISAPI filters.
Is there any reason why you have chosen to develop something on IIS 6 and now moving it to IIS 7.5?
Also have you followed the correct procedure of installing the ISAPI filter on IIS 7.5, as that differs from IIS 6. Perhaos you can share some more details on your ISAPI filter and it's configuration?
Comment: The ISAPI filter is provided by Oracle, it provides SSO functionality. The ISAPI filter was not the problem, it was working correctly. However, headers which it populated where being removed by IIS 7.5, I think due to increased security measures. We have since solved the issue by moving required values to none standard header keys.

IIS 7.5 Missing Authorization Header


Any ways to physically improve hand and finger speed?

Question: My question is general and is instrument agnostic (it's actually even music acoustic).
I'm looking for ways to improve my hand and finger speed, whether it's finger drumming on the kitchen table, picking the string, or other fast tremolos of any kind.
My question is not about playing fast riffs, but rather on how to extend your physical ergonomic capabilities regarding speed of any kind. And 'eat more tuna' also counts as a valid answer as long as it's true.
Answer: For me, my speed is directly related to coordination between my two hands. As a guitar player, this is my fretting and picking hands. So coordination exercises are important.
As for speeding up, I've found the best way to ramp up speed is to practice slowly and deliberately for a while, then try a few runs at a speed slightly faster than you are comfortable with. After doing that, you should find that your technique when slowed back down  is more accurate and after a while your top speed should improve.
As suggested in another answer, relaxing your hands is also critical. The exercise I suggest should help with that, but another one to try, for your fretting hand is to learn to fret as light as possible. You can practice this by removing your thumb from the back of the neck and just use finger pressure to fret. This will encourage your to lighten your grip and hopefully speeding your fretting hand up.
Answer: Speed, on any instrument, is about relaxing all but the muscles needed to perform the required motion.  Here's an illustrative example:  clench every muscle in your body and try to move. Hard right?  When you practice something slowly, the focus should be on making sure you are not doing anything extraneous and that it remains comfortable and smooth.  You must constantly check your body for extra tension.  You will be surprised at how much tension is there that you don't even notice because it's there all the time.
Comment: This is soo important .. not even just for musical practice, but for everyday activities, work, watching TV, whatever. Learn how to relax properly and life will be so much easier. :)
Answer: There's an eastern meditation exercise which should offer benefits in mind/body coordination. One of the first exercises in Sadhana (/So' -dana/) by Anthony De Mello [link] is the following, assuming a comfortable relaxed posture:

Direct your attention on the left elbow.
Direct your attention on the right big toe.
Direct your attention on the left shoulder.
Direct your attention on the right elbow.
Direct your attention on the left big toe.
Direct your attention on the right shoulder.

Go through the sequence slowly the first few times, make sure you feel the spot (air moving against the skin, some sense of muscular tension (but don't tense, don't move anything during this exercise except for normal breathing)), perhaps even the pulse of the bloodflow. After some practice, go through the sequence more quickly.
I may not be remembering the exact sequence or locations, but the point is to learn how to quickly select a part of the body and more tightly bind the stream of sensations to the higher parts of consciousness. It should also increase your total awareness of your body.
Personally, I found the most difficult part of this exercise was alternating the left and right sides of the body. With my eyes closed, I can easily start with my index finger and move my attention to nearby parts, like the wrist, other fingers, higher up the arm. Attempting to find the right foot immediately after the left arm was (is) difficult for me to do quickly. I kind of have to feel my way down my leg to get there. But after a few times through, it becomes easier.
The next level is feel all these parts of the body at once. But it is a different exercise with a somewhat different goal.
I highly recommend the above book (I must have given away my copy) to anyone interested in meditation. It is spiritual practice but is essentially "religion"-neutral, and can be used by practitioners of any religion. (I'd be very surprised to learn different.)

Edit: Still more disjointed commentary. William James describes the primary function of consciousness as selection. That is selecting what to pay attention to and what to ignore. I had earler used the term focus attention which I now think is redundant, since both component terms implicitly include their opposite (to bring one thing into focus, one pushes others out of focus; to attend to one stimulus is to ignore (or reduce attention toward) another stimulus).
Now, since stimuli and motor commands are both carried by the nervous system, it becomes apparent that these can be affected by drugs that act upon the nervous system. Stimulants can increase the apparent strength of stimuli and the apparent speed of motion. But it's very difficult to analyze this effect upon oneself precisely because they both change together. You may indeed be the Drunken Master, but it's hard to determine this for oneself due to the Beer Goggles. :) (And remember, the Drunken Master still needed intense (sober) physical training.)
Other dangers in this area include: excessive dose of stimulants can produce jitters, shaking of the muscles in an uncontrollable manner (which is the opposite of what we want). Use of stimulants can encourage chemical dependence (not good). And abuse can cause hallucinations, disconnection with others/reality.
I suppose I'm saying try practicing after drinking a glass of water, and then try after a cup of coffee. I am NOT saying: try some coke to make your solo awesome. Use your brain, always. A beer may help you get the rhythm nice and smooth at the local open mic. A fifth of jack will not help.
Comment: I'm not sure what more to say because I have defined it twice already: *"make sure you feel the spot (air moving against the skin, some sense of muscular tension (but don't tense, don't move anything during this exercise except for normal breathing)), perhaps even the pulse of the bloodflow"*, and *"more tightly bind the stream of sensations to the higher parts of consciousness"*. Perhaps there's a better word choice than "focus attention". But I keep coming up with synonyms: concentrate awareness, pay attention to sensation, move the point of conscious awareness.
Answer: I can only speak for guitar but you can basically see drastic improvements in lets say a year by practicing with a metronome. People do not want to do it because it is tedious but the improvement will be tremendous.
Start of with a 4/4 time signature and four crotchets. Start at 60 bpm. At the beginning you do not do scales they come a little bit later. You just pick one string at a time up and down the fretboard over all the strings. Using all your left hand fingers
I did practice sessions three times a week for two hours. After every second session I would go up five bpm. When you get to 180 bpm you cut the speed by half (i.e. 90) and do quavers. So it would be a 4/4 beat with 8 notes in a bar two per beat. Then you would go from 90 all the way up to 180 again.
What is great when you can play quavers at 180 comfortably you can start playing rhythms. Crotcet quaver / quaver Crotchet Crotchet.
Eventually you incorporate these rhythms into scales. You learn how to compose melodies and now you have the dexterity to actually play your ideas.
Answer: I've always found a good exercise for finger speed to be simply, tapping. Tap away to glory. Use a metronome and keep up the rhythm. Slowly increase your speed and also the duration of each session.
The most important thing about speed is that it's not just your hand that's doing the job, but your whole arm. The muscle that will feel strain first is the one on your forearm, and this muscle is the most important. It gives you speed, stability and also helps keep your arm in place. Do stretching exercises for your forearm (ones by Petrucci are good) and ALWAYS do them before you start playing. These apply for both arms. The left forearm muscle helps you slide back and forth (along with the elbow muscles) and gives your fingers strength.
The next most important muscle is your bicep. Standard light exercises like stretching should help you out.
But most importantly, PLAY.
Pick a song you like and play that shit over and over and over again.
Play it along with the song, play it longer, play it faster.
Go gradually.
Select tougher and more technical songs.
At the end of the day, NOTHING will help you better than practice.
Answer: I have noticed that in my experience as guitarist/pianist that speed can be developed by first setting a goal and practicing slowly, synchronizing both hands. A metronome does help tremendously but I find that sometimes even without a metronome constant slow practicing can develop speed and accuracy. I chose the Coltrane solo Countdown to experiment and I really thought at first it was impossible to play but after constant slow patient practicing with a metronome I was able to develop the speed.
Answer: for anyone looking at this that plays piano, I highly recommend Josh Wright's tutorials. at first when i tried using them, they didn't work quite right. now, after only a month they have helped dramatically. not saying I can suddenly play HR2, but I am getting a lot better.
Answer: I just realized there is a great simple and fun way to instantly improve finger strength and dexterity. I'm sure many people do this by nature, but for people like me it was a great catch.
Open this playlist (from the Dave Conservatoire - an great resource for itself), and play all the songs one by one, and use your fingers to clap the beat.
I always used to train my fingers with a metronome and found it very boring and aching. When doing so whilst using actual music as a metronome, it's just way simpler and natural.
At the beginning just tap with your fingers of each hand separately (finger per beat), then combine both hands.
Use different rhythms to train different finger patterns. The challenging it is, the strength you gain when you get used to it.
After you feel comfortable and accurate, start knocking a bit louder and try different types of attacks i.e. staccato, legato, with/without other fingers lifted/rested etc.
Once you gained a good dexterity and accuracy, speed is not an issue at all. The goal is not speed, its accuracy. Once finger strength, dexterity and accuracy are achieved, speed is right there.
Hope this helps.


Using a CNAME record to point to an Amazon ELB

Question: I have an elastic load balancer in an AWS VPC.
I can access the resources successfully behind the load balancer exposed on different ports - standard https 443 and a couple of higher ones say 8888.
So
https://aws-elb.xxxxxxxxxxxx.region.com:443
https://aws-elb.xxxxxxxxxxxx.region.com:8888
all work - I get the expected security warning but can ignore and access the service.
I then added a CNAME record for mysite.example.com to point at https://aws-elb.xxxxxxxxxxxx.region.com and got a cert for mysite.example.com.
Now I can access
https://mysite.example.com[:443]
successfully, but
https://mysite.example.com:8888
times out.
I was under the impression that the CNAME would just route through to the underlying url and all would work?
Answer: That's weird, DNS has nothing to do with the port you're connecting to (443, 8888).
Are you sure you're testing it from the same place? Does the ELB security group permit connection to 8888 from your location?
Or is it perhaps not timeout but instead some other error that you're facing on 8888?
Comment: Turns out the dns provider only proxy a couple of non standard ports. The request was never making its way to the elb (found that it by turning on the logging and seeing only 443 was getting hit).
Comment: @PaulB DNS translates host names to IP addresses, nothing else. It's got *nothing* to do with *ports*. Really. From your location try the ALB address on port 8888 and the hostname on port 8888 and see what it does. Even if there is a problem it's got nothing to do with DNS.
Comment: @PaulB Like I said - it's got nothing to do with DNS and everything to do with CloudFlare port forwarding ;) It would have been useful if you had mentioned that you're using CloudFlare as that's a whole extra layer between your clients and your site.
Comment: Appreciate your help ... I had no idea a CNAME had anything to do with port forwarding ... thought it was just an alias to url - hence no mention of Cloudflare.


Does the subscription has unlimited lifetime?

Question: I wonder does the subscriptions (Microsoft Graph API) have a limited or unlimited lifetime? Is there any related documentation or guidance available for this... I failed to find one.
Comment: Yes, Subscriptions for Microsoft Graph have a limited lifetime. For a list of maximum expiration times, see Maximum length of subscription per resource type documentation - (https://learn.microsoft.com/en-us/graph/webhooks#subscription-lifetime).
Comment: Apps need to renew their subscriptions before the expiration time. Otherwise, they need to create a new subscription. Apps can also unsubscribe at any time to stop getting change notifications. Clients can create subscriptions, renew subscriptions, and delete subscriptions.
Comment: Thanks @Dev. It answers my question!!
Comment: Have a side question. What about apps/clients?
Comment: Awesome. Thanks for your help @Dev!! You rock!!
Comment: Glad to hear the above helped!!
Comment: I will move this to answer. Please upvote, so it can be useful to others...
Answer:
Yes, Subscriptions in Microsoft Graph have a limited lifetime.
For a list of maximum expiration times, see Maximum length of
subscription per resource type documentation.
Apps need to renew their subscriptions before the expiration time. Otherwise, they need to create a new subscription. Apps can also unsubscribe at any time to stop getting change notifications. Clients can create subscriptions, renew subscriptions, and delete subscriptions.


regexp to find number between characters

Question: I have a string with the following pattern:
......id\":\"1122575828\",\"raw_id\":1122575828,\"query\"....

I want to extract the number between raw_id\": and ',' as in raw_id\":(the number),
What should be the right combination in Regexp for PCRE (PHP)?
Thanks in advance.
Comment: Is this some escaped `JSON` ?
Answer: Use the following regexp pattern with preg_match function:
$str = "......id\":\"1122575828\",\"raw_id\":1122575828,\"query\"....";
preg_match('/"raw_id":([^,]+?),/', $str, $matches);

$number = $matches[1];  // 1122575828

Comment: Thanks for your help, actually don't know why but on post the content altered the actually string was ...raw_id\\":1122575828,..... and I after trying for a while I got the correct expression that is /raw_id\\\\\\\\":([0-9]+),/ . Anyway your solution is correct for the altered string on my post. Thanks.


Is there an API or a simple way to check if a volume is deduped on Windows server 2012?

Question: Here's the MSDN page about Data deduplication API, and it seems there's no API to check if a volume is deduped.
One way to do it  is to check if there's a folder named "Dedup" under "System Volume Information", but I don't think it is reliable for every case.
Comment: Using WMI (http://msdn.microsoft.com/en-us/library/windows/desktop/hh769311(v=vs.85).aspx), you can check if dedup is enabled for a volume (using the Enabled property)
Comment: WMI is the API that Windows provides for this kind of operation. You can use WMI interfaces inside your C++ application and use its properties.
Comment: This should work. I want to know if there's windows API for it, simpler than the WMI solution
Comment: It seems to be only way to do that: using WMI
Answer: The list of deduped volumes can be obtained in powershell. See the following link about a third of the way down the page
http://windows-scripting.org/category/windows-2012/
Comment: I think the powershell script is using WMI too.
Comment: Wmi is the only way you are going to be able to get the information. Why is that an issue?
Comment: Just wonder if there an windows API for this, called by C/C++


in PHP, is there a way to detect if a string contains any words?

Question: The question is about detecting if a string have any words (from any languages). I'm not looking for a specific word in particular, just test if a string have real world existing words in it.
Example $str = 'allo' would return true and $str = 'zyzassk' would return false
I tried preg_match_all('/\w/', $input_lines, $output_array);
preg_math \w return each individual letters, but how to get complete words ?
and is there a library to test against dictionaries?
is there a way or php function to do this?
Comment: Can you try `strpos` ?
Comment: I have added an answer with language detection, but it is not the optimal way to achieve the goal ... due to the complexity of many languages in the world. but I think it meets what you expect.
Answer: There are several ways to do it:
using str_contains:
https://stackoverflow.com/a/65473395/4717133
using strpos:
https://www.php.net/manual/es/function.strpos.php
the main problem is that you need a pattern match in language to know if it exists in any language; This can be a bit torturous and shouldn't be done ...
but you can implement the use of some app like google translate ...
https://cloud.google.com/translate/docs/basic/detecting-language
Método HTTP y URL:
POST https://translation.googleapis.com/language/translate/v2/detect

JSON body of the request:
{
  "q": "Mi comida favorita es una enchilada."
}

To submit your request you can use curl:
curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/language/translate/v2/detect

you would get a response like this:
{
  "data": {
    "detections": [
      [
        {
          "confidence": 1,
          "isReliable": false,
          "language": "es"
        }
      ]
    ]
  }
}

Comment: You answer is good, what do you think of my answer the function is_str_have_human_words...
Answer: I did some digging and I came up with this
function is_str_have_human_words ( $txtToDetect ) {

    $highestLangCode = '';

    if ( preg_match('/[\x{4E00}-\x{9FBF}]/u', $txtToDetect) )   { $highestLangCode = 'zh'; }
    if ( preg_match('/[\x{3040}-\x{309F}]/u', $txtToDetect) )   { $highestLangCode = 'zh'; }
    if ( preg_match('/[\x{30A0}-\x{30FF}]/u', $txtToDetect) )   { $highestLangCode = 'zh'; }
    if ( preg_match('/[\x{3130}-\x{318F}\x{AC00}-\x{D7AF}]/u', $txtToDetect) ) { $highestLangCode = 'ko'; }
    if ( preg_match('/\p{Thai}/u', $txtToDetect) )              { $highestLangCode = 'th'; }
    if ( preg_match('/\p{Arabic}/u', $txtToDetect) )            { $highestLangCode = 'ar'; }
    if ( preg_match('/\p{Armenian}/u', $txtToDetect) )          { $highestLangCode = 'hy'; }
    if ( preg_match('/\p{Bengali}/u', $txtToDetect) )           { $highestLangCode = 'bn'; }
    if ( preg_match('/\p{Devanagari}/u', $txtToDetect) )        { $highestLangCode = 'hi'; }
    if ( preg_match('/\p{Georgian}/u', $txtToDetect) )          { $highestLangCode = 'ka'; }
    if ( preg_match('/\p{Greek}/u', $txtToDetect) )             { $highestLangCode = 'el'; }
    if ( preg_match('/\p{Gujarati}/u', $txtToDetect) )          { $highestLangCode = 'gu'; }
    if ( preg_match('/\p{Hebrew}/u', $txtToDetect) )            { $highestLangCode = 'he'; }
    if ( preg_match('/\p{Kannada}/u', $txtToDetect) )           { $highestLangCode = 'kn'; }
    if ( preg_match('/\p{Khmer}/u', $txtToDetect) )             { $highestLangCode = 'km'; }
    if ( preg_match('/\p{Lao}/u', $txtToDetect) )               { $highestLangCode = 'lo'; }
    if ( preg_match('/\p{Limbu}/u', $txtToDetect) )             { $highestLangCode = 'li'; }
    if ( preg_match('/\p{Malayalam}/u', $txtToDetect) )         { $highestLangCode = 'ml'; }
    if ( preg_match('/\p{Mongolian}/u', $txtToDetect) )         { $highestLangCode = 'mn'; }
    if ( preg_match('/\p{Myanmar}/u', $txtToDetect) )           { $highestLangCode = 'my'; }
    if ( preg_match('/\p{Oriya}/u', $txtToDetect) )             { $highestLangCode = 'or'; }
    if ( preg_match('/\p{Sinhala}/u', $txtToDetect) )           { $highestLangCode = 'si'; }
    if ( preg_match('/\p{Tagalog}/u', $txtToDetect) )           { $highestLangCode = 'tl'; }
    if ( preg_match('/\p{Tamil}/u', $txtToDetect) )             { $highestLangCode = 'ta'; }
    if ( preg_match('/\p{Telugu}/u', $txtToDetect) )            { $highestLangCode = 'te'; }
    if ( preg_match('/\p{Thaana}/u', $txtToDetect) )            { $highestLangCode = 'dv'; }
    if ( preg_match('/\p{Tibetan}/u', $txtToDetect) )           { $highestLangCode = 'bo'; }
    if ( preg_match('/[А-Яа-яЁё]/u', $txtToDetect) )            { $highestLangCode = 'ru'; }

    if ( $highestLangCode == '' ) {

        $wordsToTests = explode(strtolower($txtToDetect));
        $wordsToTests = preg_replace("/[:punct:]+/", "", $wordsToTests);

        foreach ( $wordsToTests as $wordsToTest ) {

            // DATABASE WITH WORDS FROM LOTS OF LANGAGES
            $uword = $mysqli->query("SELECT * FROM `langtable` WHERE `word` = '".clean($wordsToTest)."'; ");
            if ( $uword->num_rows > 0 ){ $highestLangCode = '-'; break; }

            // OR A SPELL CHECK LIKE pspell_check...

        }

    }

    if ( $highestLangCode == '' ) { return false; } else { return true; }

}

Comment: I think your database is going to explode ... :( and you need provide a dictionary to solve the problem ....
Comment: my database is 30 million row using ROCKSDB as engine and it's very fast and efficient
Answer: If  you have those words in database or in a file you can use this function:
function CheckStringForWords($text){

$words = array("words","that","you","wanna","check");
//$words array can come out from a file or even database.

$matches = array();
$matchFound = preg_match_all(
                "/\b(" . implode($words,"|") . ")\b/i",
                $text,
                $matches
              );

if ($matchFound) {
  $words = array_unique($matches[0]);
  foreach($words as $word) {
    return true;
    //returns true if $text contains any of the words in $words array.
  }
  return false;
  //returns false if $text does not contain any of the words in $words array.
}
}

Comment: I'm not sure that you can use implode with billion words existing in any language in the world! And how do you deal with words written RtoLas well as LtoR?
Comment: Well for billion words I never tried but it will be hard I guess, and to deal with words written like this we can use strtolower to lowercase them and compare.
Comment: I meant Right to Left as Arabic for example.
Answer: If you are using php 8 then there is a function str_contains()  Determine if a string contains a given substring
$string = 'The lazy fox jumped over the fence';

if (str_contains($string, 'lazy')) {
    echo "The string 'lazy' was found in the string\n";
}

if (str_contains($string, 'Lazy')) {
    echo 'The string "Lazy" was found in the string';
} else {
    echo '"Lazy" was not found because the case does not match';
}

Determine if a string contains a given substring
The above example will output:
The string 'lazy' was found in the string
"Lazy" was not found because the case does not match

Comment: does not support existing language detection.
Comment: in my question I said any words (from any languages)


Catering problem. How many will eat wheat sugar and are vegetarians (combinatorics)

Question: You are catering the awards banquet. One hundred will be attending. 8 do not eat wheat,sugar or meat. 68 eat wheat, 48 eat wheat but are vegetarians, 18 eat wheat but not sugar,50 eat wheat and sugar, 20 people eat wheat and are not vegetarians, 20 eat sugar and not wheat, 70 guests eat sugar and 47 are vegetarians that eat sugar  How many eat wheat and sugar but are vegetarians? how many vegetarians are there
For this problem i created a ven diagram with sections labeled A-G. however i had difficulty placing the right values into the right sections. i understand that in the end you would want to get something like  AintersectionBintersectionC. (which would be the middle part of the diagram) perhaps i am just not visualizing this correctly but its causing me some heart ache.
Answer:
First, determine those people who eat wheat, sugar, or meat. These people lie at the center of the venn diagram.
Then, subtract this number from the people who eat (wheat and meat), (wheat and sugar), and (meat and sugar) to determine the amount of people who eat two of the specified food groups.
Then take the people who eat (wheat), (sugar), and (meat) and subtract those that eat all three and those that eat two to determine those that only eat the specified category of foods.
The remaining people do not eat any of the specified foods.


Probability of completing N events

Question: I'd like to calculate the probability that at least N independent events out of a set of M events complete successfully.  Each event Ei has a probability of success of Pi.
For example, if there are four independent events each with a unique probability of success:
E1: P1
E2: P2
E3: P3
E4: P4
How do I calculate that probability that at least 1 event will be successful?  At least 2 events?  3 events?  The order of successes does not matter.  Thanks for any help!

The best answer I could find is here:
http://mathbits.com/MathBits/TISection/Statistics2/binomialAtMost.htm
Unfortunately for me, it doesn't look like there's an easy way to get rid of the looping (summation) to solve the problem.
Comment: Is this a question from a course or textbook? If so, please add the `[self-study]`
tag & read its [wiki](http://stats.stackexchange.com/tags/self-study/info).
Comment: This is not a course problem, it's actually a business problem (flight scheduling).

I'm trying to calculate the probability of at least M of N flights being completed given that each flight has an individual probability of completion.  I see how I can get exactly M of N events using binomial series, and I suppose that I can just add up M, M+1, ... N probabilities in a loop to get the overall probability.  I was hoping there was a way to simplify the expression to one formula and not use a loop for computational efficiency.
Answer: The probability that no event occurs is$$\prod_i (1-p_i)$$hence the probability that at least one event occurs is$$1-\prod_i (1-p_i)$$The probability that exactly one event occurs is$$\sum_{j=1}^m p_j\prod_{i\ne j}(1-p_i)$$and so on. The probability of exactly $k$ events is thus
$$\sum_{1\le i_1<i_2<\cdots<i_k\le m} \prod_{j=1}^k p_{i_j} \prod_{j=k+1}^m (1-p_{i_j})$$where the second product is on the indices that are not in the first group $\{i_1,\ldots,i_k\}$

Probability of completing N events


Is this the command pattern?

Question: I have a MVP Gui and now I would like to define certain Actions or Commands (Modify, Save, Close, ...) for certain views.
Is there an easy way to do this? Should I provide Commands for each View?
Comment: MVP sounds like you are using WPF? Have you examined WPF's Commanding architecture yet?
Comment: No, I'm doing a MVP implementation in Winforms
Answer: The easiest way is to have a factory where all your command objects are instantiated. So if you have a open Job Command all the views would goto the factory and pull out the Open Job Command object, instantiate it, and then execute it. If you need to fix a bug or change the Open Job Command there only one spot you have to do it for all the Views.
With that being said there will be some commands that will probably be unique to each View. Despite that you may want to still encapsulate those in a command object as you can easily implement Undo/Redo with everything going through command objects.

Is this the command pattern?


How to call auto of reutrn function in node js

Question: On the time of page loaded get_switch() function which globally created on app.js page will be call then return a method. i want to execute these return methods.
demo.js
  const return_functions = get_switch('BTC');

   function get_btc()
  {
    console.log('btc');
  }

 function get_bch()
 {
   console.log('bch');

 }

app.js
  global.get_switch=function(coin_name){

 switch(coin_name){

 case 'BTC':
 return 'get_btc()';
 break;

  case 'BCH':
  return 'get_bth()';
  break;

  default:
 console.log('default');
 }

 }

As shown in example above i have passed BTC in get_switch. and that function return us get_btc() function. so i want to call get_btc function on same time.
If this is not possible in this way so please guide me with your idea and suggest me how can i do this.
Answer: demo.js
var obj = {
    get_btc: function get_btc() {
        console.log('btc');
    },
    get_bth: function get_bth() {
        console.log('get_bth');
    }
}
const return_functions = get_switch('BTC');
if (return_functions) {
    obj[return_functions]();
}

app.js
global.get_switch = function (coin_name) {

    switch (coin_name) {
        case 'BTC':
            return 'get_btc';
            break;
        case 'BCH':
            return 'get_bth';
            break;
        default:
            console.log('default');
    }
}

Answer: var get_switch=function(coin_name){
    switch(coin_name){
        case 'BTC':
            get_btc();
            break;
        case 'BCH':
            get_bth();
            break;
        default:
            console.log('default');
    }
}

get_switch('BTC');

function get_btc() {
    console.log('btc');
}

function get_bch() {
    console.log('bch');
}


How to have IN clause in linq to EF having two tables?

Question: I'm writing a query in order to select some data in tabla A where the column C1 is in the column C2 in table B.
It's easy to have such a query in SQL. The code is something like this:
select * from A where C1 in (Select C2 from B)

What I've tried is like this code:
var InCluse = from p in B select new { p.C2 };
var query = from p in (from q in A
                       where InClause.Contains(q.C1)
                       select q)
            select p;

But there is an error which says:

Severity  Code    Description Project File    Line    Suppression State
  Error   CS1929  'IQueryable<>' does not contain a definition for 'Contains' and the best extension method overload 'AsyncEnumerable.Contains(IAsyncEnumerable, int)' requires a receiver of type 'IAsyncEnumerable'  "ProjectName"   "ClassFileAddress"  261 Active

There are questions like mine, But the difference between this one and the others is that the other questions are about using "IN" clause in order to set a condition to an array of some data, not a table.
Comment: Perhaps my [SQL to LINQ Recipe](https://stackoverflow.com/questions/49245160/sql-to-linq-with-multiple-join-count-and-left-join/49245786#49245786) might help you?
Answer: The SQL can be pretty much literally translated to LINQ:
var ans = from a in A
          where (from b in B select b.C2).Contains(a.C1)
          select a;

You can also use join to accomplish the same result:
var ans = from a in A
          join b in B on a.C1 equals b.C2
          select a;

Answer: Why not to simply join A and B ?
var res = ctx.A.Join(ctx.B, q => q.C1, q => q.C2, (q, w) => q);


New Relic unable to load properly (Android) using eclipse

Question: I am trying to work on New Relic using this
link.
I had followed the same instructions that are given on that link, but every time I get the same error.

I also tried this also https://docs.newrelic.com/docs/mobile-monitoring/mobile-monitoring-installation/android/troubleshooting-eclipse-configurations
I also have used jdk1.8.0_05. and eclipse juno with latest SDK 23.0.2.
please some one help me to resolve this.
Comment: Can you try showing the console output from Eclipse using the         -consoleLog startup option? This would be done in the same way you pass the -vm option when specifying the correct JDK.
Answer: I had the same problem. Eventually found this: https://discuss.newrelic.com/t/installing-eclipse/6793
Basically, it doesn't work with Eclipse Luna yet. It also doesn't work with Indigo, which just leaves Juno and Kepler.
Answer: Just follow the link given by @rockgecko.
Points to remember:-

Add the absolute path upto "javaw.exe" after the suffix "-vm"
In eclipse, Add the Standard Environment under JAVA/JRE, do put path of JDK there & it should be upto JDK folder only and do remember to active it instead of previous JRE option after adding it properly.
Answer: Add this line in eclipse juno properties in target section after eclipse.exe
-vm "C:\Program Files\Java\jdk1.8.0_05\bin\javaw.exe"
and set PATH variable like this way
C:\Program Files\Java\jdk1.8.0_05\bin;.
in environment variables in your system properties.
Hope it will work for you.


Typescript error: Cannot redeclare block-scoped variable 'fetch'

Question: I am working on a proof of concept to fetch some simple JSON data from JSON-server to display in my react app. In doing so I am trying to call fetch to load the data directly. When I do so.

ERROR: "cannot redeclare block-scoped variable 'fetch'.

My question is, when working in regular Typescript, how can I get around this issue?
import React, { Component } from 'react';
import '../HeaderBar/HeaderBar.css';

type StatusBarProps = {};
type StatusBarState = {
    launch_timer: boolean;
    foreGroundTimer: number;

};
class StatusBar extends Component<StatusBarProps, StatusBarState> {
    timerId: number;
    constructor() {
        super();
        this.state = {
            launch_timer: true,
            foreGroundTimer: -1,
        };
    }
    componentDidMount() {
        window.fetch('localhost:3000/StatusComponent').then(results => {
            return results.json();
        }).then(data => {
            let systemOff = 'green';
            let systemOn = 'gray';
            let statusBarBlocks = data.StatusComponent.map((Status) => {
                return(

= Status.id) ? systemOff : systemOn }}> {Status.Name}

                );
            });
            this.setState({statusBarBlocks: statusBarBlocks});
        });
    }
    componentWillUnmount() {
        clearInterval(this.timerId);
    }
    tick() {
        this.setState({ launch_timer: !this.state.launch_timer, foreGroundTimer: (this.state.foreGroundTimer + 1) % 26 });
    }
    render() {

        return (

                {this.state.statusBarBlocks}

        );
    }
}
export default StatusBar;

edit 1: the location of the issue is @types/whatwg-fetch/index.d.ts which leads me to believe this is an issue with typescript. I have implemented Isomorphic-fetch to no avail.
Comment: Do you import fetch from isomorphic-fetch package?
Comment: @SlawaEremkin I do not, but would that cause this issue?
Comment: What part of the code causes the issue? Try removing everything else
Comment: @Bergi The issue seems to arise at the window.fetch inside componentdidmount.
Comment: @jpearsonNode "*seems to*" - have you confirmed it? Does it need to be inside componentdidmount for that? Do you need any imports for it to arise? Does it need to be called? Please do some debugging.
Comment: @Bergi The specific issue that arises is error TS2451: Cannot redeclare block-scoped variable 'fetch'. It does need to be inside componentdidmount specifically for the purpose of receiving persistent updates, as this is being fed on a stream of data. I do not need any imports, as I understand fetch is native. I
Comment: @jpearsonNode I meant "does it need to be in there *to cause the error*", of course
Comment: You don't need to do fetch, just `import fetch from isomorphic fetch` and use it way
Comment: @win can you clarify your statement?
Answer: So in working to discover the cause of this issue. I found that I had an overlap where fetch was being declared in both the Lib file, and in @types/whatwg-fetch. Uninstalling this dependency allowed the program to compile. Resolving the issue.
whatwg-fetch new typescript 2.5.3
Found at this SO post. Credit to Fenton for this answer.


Can cursor be use in UPDATE and DELETE in Function

Question: I have one doupt while I try to use UPDATE and DELETE method.
So starting from basic function something like
FUNCTION GET_ANSWER(p_questionId IN INT)
    RETURN SYS_REFCURSOR IS
    rc  SYS_REFCURSOR;
    /*getAnswer*/
BEGIN
  OPEN rc FOR
    SELECT * FROM answers WHERE AnswerID = p_questionId;
  RETURN rc;
END GET_ANSWER;

While I try to use DELETE or UPDATE method I get error message
Error(3529,1): PLS-00103: Encountered the symbol "DELETE" when expecting one of the following:     ( - + case mod new not null select with <an identifier>         continue avg count current exists max min prior sql stddev    sum variance execute forall merge time timestamp interval    date       pipe    <an alternatively-quoted string literal with character set specification>

Error(3530,1): PLS-00103: Encountered the symbol "RETURN"

Error(3536,1): PLS-00103: Encountered the symbol "END"

FUNCTION DELETE_ACTIVITY(p_activityId IN INT)
RETURN SYS_REFCURSOR IS
rc  SYS_REFCURSOR;
BEGIN
OPEN rc FOR
DELETE FROM activities WHERE id = p_activityId;
RETURN rc;
END DELETE_ACTIVITY;

What is wrong here ? Wher did I made mistake ?
Answer: Cursors are only used for SELECT statements.  You cannot open a cursor for an INSERT, UPDATE or DELETE statement.
See the documentation

An explicit cursor definition has this syntax:
CURSOR cursor_name [ parameter_list ] [ RETURN return_type ]   IS
select_statement;
Answer: Don't do it via cursor, but simply
DELETE FROM answers WHERE AnswerID = p_questionId;

Also, make it a procedure, not a function.

As of UPDATE, well - it depends on what you want to update and how, but - generally:
update answers set
  some_column = some_value
where ansewrID = p_questionId

Why a procedure and not a function:
SQL> create or replace function f_test return number is
  2  begin
  3    delete from test;
  4    return 1;
  5  end;
  6  /

Function created.

SQL> select f_test from dual;
select f_test from dual
       *
ERROR at line 1:
ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "SCOTT.F_TEST", line 3

SQL>

However, if a function is an autonomous transaction, you can do that, but - not recommended:
SQL> create or replace function f_test return number is
  2    pragma autonomous_transaction;
  3  begin
  4    delete from test;
  5    commit;
  6    return 1;
  7  end;
  8  /

Function created.

SQL> select f_test from dual;

    F_TEST
----------
         1

SQL>

Comment: Thank you for answer. I get the point right now :)
One more question, why you recommend to use procedure not a function ?
Comment: You're welcome. Because you can't delete within a function :) See a demonstration at the bottom of the answer.
Comment: No problem, I'm glad if it helped.


Confidence band for simple linear regression - why the curve?

Question: I am really struggling to understand why confidence bands for regression lines have a curve to them. A few example plots showing curved CIs, taken from this post: Shape of confidence interval for predicted values in linear regression

I have read a bit and understand that the standard error for the sampling distribution of $\hat y$ at a given point ($\hat y^*$) is as follows:
$$ MSE \sqrt{\frac{1}{n} + \frac{(x^*-\bar x)^2}{\sum_{i=1}^n (x_i-\bar x)^2}} $$
Because the above equation has $(x^* - \bar x)^2$ in the numerator, the further we are from $\bar x$, the bigger the standard error will be, hence the curve being 'thinnest' when $x = \bar x$, and fatter as $x$ increases/decreases.
But why does that make sense?
My thinking is this: if one of the assumptions for a linear regression is homogeneity of variance for $Y$ across values of $X$, and the residuals from our regression are also equally distributed across values of $X$,  why would the variance of our sampling distributions of $\hat y$ not be the same at each value of $X$?
Clearly I am missing something!
Comment: Point of clarification: the **variance** of $y|x$ is constant in this model, and the curvature of the ***confidence* bands** does not reflect heteroscedasticity (non-constant of $y|x$). If you are looking for a purely intuitive idea: there is less **nearby** information informing estimates of $y$ that are far from the mean of $x$ (e.g., the estimate of $y$ for $\min (x)$ is determined by no values of $x$ below that point!).
Comment: Previously answered in some detail here: [Shape of confidence interval for predicted values in linear regression](https://stats.stackexchange.com/q/85560/805)
Comment: Does this answer your question? [Shape of confidence interval for predicted values in linear regression](https://stats.stackexchange.com/questions/85560/shape-of-confidence-interval-for-predicted-values-in-linear-regression)
Comment: If the variance of the sampling distribution of yhat were the same at each point, that means you are were only uncertain about the intercept, right? If you're uncertain about the intercept and the slope, the shape of needs to change. The homogeneity of variance of the residuals is still assumed, but that band is not about residuals.
Comment: "But does this extend to mean that our predictions are less certain the further we move from $\bar{x}$?" That is **exactly** what the widening curvature means! **Caveat:** For predicted values **of the regression line.**. The prediction interval for a value of $y$ given a single $x$ value, the bands are much wider/much less certain (although they are still curved, and for exactly the same reason).
Comment: @dataphile Perhaps you are aware, but maybe you are thinking of https://en.wikipedia.org/wiki/Prediction_interval
Comment: My intuition is that we are estimating two parameters, an intercept and a slope.  If we knew the unknown fixed true slope then the only sampling variability would come from the intercept and the confidence band would not be curved.  When the true population-level slope is unknown and estimated, the sampling variability produces the curvature in the confidence band.
Comment: @Alexis Thank you, that is very clear! But does this extend to mean that our predictions are less certain the further we move from $\bar x$? I guess I am confused as to whether the curvature of the confidence bands reflects a change in the quality/certainty of predictions across the range of $x.$
Comment: @Alexis Thank you - that clears it up! I was confused because I had assumed that prediction certainty across the regression line is uniform but now it is clear why and how that is not the case.
Answer: Computing the sample variance of the estimate $\hat{y}$
The estimate for the mean $y$ (as a function of $x$) has the following function in terms of the predictions for coefficients $\alpha$ and $\beta$
$$\hat {y} = \hat{\alpha} + \hat{\beta} x$$
The standard error of $\hat{y}$ can be computed with the formula for the standard deviation or variance
$$Var(\hat\alpha + \hat\beta x) = Var(\hat\alpha) + x^2 Var(\hat\beta) - 2x  Cov(\hat\alpha,\hat\beta)$$
So this is a quadratic function that has a minimum at $x = \frac{Cov(\hat\alpha,\hat\beta)}{Var(\hat\beta)} = \bar{x_i}$ and this creates that funnel shape with the minimum at the mean of the datapoints $x_i$.
Intuitive
Let's try out several fits. We use the following data
$X_i$ is normal distributed. $Y_i$ is $0.8$ times $X_i$ with some added noise.
$$\begin{array}{}
X_i &\sim& N(0,1) \\ \epsilon_i &\sim& N(0,1) \\
Y_i &=& 0.8 X_i + 0.6 \epsilon_i
\end{array}$$
Result of $25$ simulations with each $15$ data points

When we combine all those different lines in a single plot then we get:

So here we might see intuitively why the confidence band becomes 'fatter' at the ends. The confidence is due to errors in the height of the line (parameter $\alpha$) and the slope of the line (parameter $\beta$). It is this latter one that makes the error larger towards the ends.

$\frac{Cov(\hat\alpha,\hat\beta)}{Var(\hat\beta)} = \bar{x} $ follows from the covariance matrix for the $\alpha$ and $\beta$ which is $\sigma (X^TX)^{-1}$. Which you could work out further by filling in all the terms...  But you could also argue that the minimum should be at $\bar{x}$ by transform the data matrix $X$ such that the the column vectors are perpendicular and the estimates $\hat\alpha$ and $\hat\beta$ have zero covariance.
Comment: @dataphile the error in a prediction of a new datapoint $y$ has two sources of error. **(1)** The error in the estimate of the mean of the distribution of the data points. This error becomes larger further away from the mean as explained in the answers to the question here. **(2)** Error due to variation of the samples $y$ around the mean. This error can be (depending on the model) heterogeneous.... ...so yes, the increase of the bands further away from the mean will also happen for predictions, because the error in the estimate of the mean will influence the error of the predicitons.
Comment: This is a great visual - thank you! But now it brings me to ask: Does this suggest that predictions for y have greater error if our input x is far from the mean of x? If our confidence bands are wider at the ends than in the middle, then predicting values of y at those spots is less certain than near the mean, no?
Comment: Perfect - thank you so much! I just never made that connection before.
Answer: As you get farther from $\bar x,\bar y$ uncertainty increases. There's fewer and fewer observations when you reach out to distant regions of the domain of your function.
The main source of uncertainty is the one about the slope of the line. Take a look at the drawing here. With the given sample of observations you can say that the best fit line should be somewhere between these two grey lines. The uncertainty around $(\bar x,\bar y)$ is the smallest, but once you step away from where the observations are located, uncertainty increases.

Here's how we can intuitively "derive" the asymptotic confidence interval, i.e. where $x^*$ is very far away from your observations. The confidence given by model MSE will proportionally expand as $|x^*-\bar x|\to\infty$. Think of it as approximate equality of ratios $\frac{MSE}{\sqrt n\sigma_x}\approx \frac{CI(x^*)}{|x^*-\bar x|}$. That's the asymptotic of your formula:
$$\lim_{x^*\to\infty} MSE \sqrt{\frac{1}{n} + \frac{(x^*-\bar x)^2}{\sum_{i=1}^n (x_i-\bar x)^2}} =\frac{MSE}{\sqrt n\sigma_x}|x^*-\bar x|$$
Comment: this is not true for linear regression which has a domain everywhere. Dave's answer is the correct one in this situation
Comment: maybe you have data between [0.1] and [100,101], but you will still see uncertainty around 50, far from the data, to be small and uncertainty where you have data large
Comment: @Aksakal, the point of rep_ho is that the reason "there's fewer observations" is not very clear, because the point $\bar{x}$ does not need to be the point with the most observations. You explain it in the comments, but in the answer it is unclear.
Answer: There is 2 uncertainties here. As you mentioned there is the uncertainty with the slope thus the spreading curve at ends, but there is also an uncertainty at the mean. Yes, the curve is thinnest at the mean but it is not zero. Thus the uncertainty of the slope passing through the mean's distribution causes the estimate to be non linear and generates the above examples.
Comment: Unveiling about the intercept doesn't matter in big scheme of things. Consider the infinitely far away $x^*$


Next Step After Finding Eigenvalues of Transformation Matrix T?

Question: I've successfully determined the eigenvalues of the transformation matrix (T = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 5 & -10 \\ 1 & 0 & 2 & 0 \\ 1 & 0 & 0 & 3 \end{pmatrix}). Now I'm wondering about the next logical step in this process. Could someone guide me on how to find (if possible) the bases for the corresponding eigenspaces? I'd greatly appreciate any insights or steps to take from this point forward. Here's my attempt:
$$\left( T-\lambda_{1} I\right)  \mathbf{v} =0$$ where $\lambda_{1} = 1$, so we have:
$$\begin{pmatrix}1-1&0&0&0\\ 0&1-1&5&-10\\ 1&0&2-1&0\\ 1&0&0&3-1\end{pmatrix} \left( \begin{gathered}v_{1}\\ v_{2}\\ v_{3}\\ v_{4}\end{gathered} \right)  =0$$
Thank you in advance!
Comment: Do this in *exactly the same way* you would for finding the basis of a nullspace... just that the you are finding the basis of the nullspace of $(A-\lambda I)$.  You should have had plenty of practice doing this already by this point if you are talking about eigenvalues.
Comment: @JMoravitz I edited my post, is that a good first attempt?
Comment: I wouldn't call that an attempt yet.  This is merely the setup for an attempt.
Comment: @JMoravitz I have understood what the basis vectors are for $\lambda_1$. My question is about how to obtain bases for the eigenspaces corresponding to $\lambda_2$ and $\lambda_3$.

For $\lambda_2$, the basis of the eigenspace is the vector $$\left(\begin{array}{c} 0 \\ 5 \\ 1 \\ 0 \end{array}\right)$$. And for $\lambda_3$, the basis of the eigenspace is the vector $$\left(\begin{array}{c} 0 \\ -5 \\ 0 \\ 1 \end{array}\right)$$.
Comment: I don't understand your last comment.  The words you used make it sound like you don't know how to continue the problem, but the values you show are precisely the answer to the problem you say you don't know how to solve.  What additional help do you still need?
Comment: Also, to be clear... you used the wording "**the** *basis of the eigenspace is the vector...*" which might be interpreted that you believe there is only one correct answer, but there are in fact infinitely many ways to describe the eigenspace.  It is more correct to say "**a** *basis of the eigenspace is...*"
Comment: @JMoravitz How do they get those bases for $\lambda_2$ and $\lambda_3$? One of them is merely the third column vector here, and the other is the fourth column vector, but how is that a basis of the eigenspace? $$\left(\begin{array}{cccc}
1 & 0 & 0 & 0 \\
0 & 1 & 5 & -10 \\
1 & 0 & 1 & 0 \\
1 & 0 & 0 & 2
\end{array}\right)$$
Comment: For the eigenvalue $\lambda =1$, look at $A-\lambda I$ which is $A-I$ here.  Row reduce that.  You are left with a matrix.  Interpret that matrix as a system of equations describing the values of a vector $v$ such that $(A-\lambda I)v=0$.  Make a choice of free-variables to simplify the representations.  With regards to $\lambda_2,\lambda_3$ the process is the same.  It is a fluke that they happened to correspond to the columns here before row reduction.
Comment: Again, knowing and understanding how to find the nullspace of a matrix should have been learned and mastered several lessons before eigenvalues and eigenspaces.  If you are not comfortable with that, then go back to those lessons and exercises before continuing with your current lesson.
Answer: $A = \begin{bmatrix}1&0&0&0\\0&1&5&-10\\1&0&2&0\\1&0&0&3\end{bmatrix}$
$\det(A-\lambda I) = \lambda^4-7\lambda^3+17\lambda^2-17\lambda+6=(\lambda-3)(\lambda-2)(\lambda-1)^2$ so we have eigenvalues $1, 1, 2, 3$
The eigenspace for $\lambda_2=2$ will simply be the nullspace of $A-\lambda_2 I$.  To find this, look at the row reduction of $A-\lambda_2 I$
$\text{rref}\left(\begin{bmatrix}-1&0&0&0\\0&-1&5&-10\\1&0&0&0\\1&0&0&1\end{bmatrix}\right) = \begin{bmatrix}1&0&0&0\\0&1&-5&0\\0&0&0&1\\0&0&0&0\end{bmatrix}$
Interpreting this, this says that if $v = \begin{bmatrix}v_1\\v_2\\v_3\\v_4\end{bmatrix}$ were a vector such that $(A - \lambda_2)v = 0$ (which would mean that $Av = \lambda_2 v$) that it must be such that $\begin{cases}v_1=0\\v_2-5v_3=0\\v_4=0\\0=0\end{cases}$
This means, if we were to parametrize this by letting $v_3$ be some scalar... let's call it $t$, that we have $v_1=0, v_2=5t, v_3=t, v_4=0$, in other words that $\begin{bmatrix}0\\5\\1\\0\end{bmatrix}$ works as a basis for the eigenspace for $\lambda = 2$.
The fact that it just so happens that this was one of the columns of the original matrix is a fluke and you should not expect this to happen again in other problems.
This process is, again as pointed out in the comments, no different than what you should have learned and already been performing when being introduced to nullspaces in the previous chapter(s) before ever being shown the word "eigenspace."


Is it correct to say that the nonparametric BCa (bootstrap confidence intervals) is assumptions-free?

Question: I'd like to use the BCa algorithm to compute 95% confidence limits (maybe let's not call it intervals) for the medians of two population samples. I'd like to visually inspect and conclude whether the intervals overlap to say something about the significance of the difference. btw As far as I know visually comparing the differences like this with confidence intervals is a necessary condition but not sufficient condition to assess whether there is significant difference between the statistic of the two groups i.e. if the confidence intervals don't overlap then they are significantly different; if however, they overlap we need more specific tests to be sure ... I need to find where I learned that before.
Is it ok to state that BCa is assumptions-free and rely on it for inference i.e. generating reliable confidence limits given the following points?

The two unpaired groups are very departed from a normal distribution i.e. positively skewed.
The within-group samples were chosen to be the top N 1.5k and not randomly (the independence of the samples assumption required to resort to CLT doesn't hold). 1.5k samples is simply an arbitrarily large N for inference, it could have been 200 or 1k or 2k doesn't matter.
I can't use the mean but the median due to how the data is distributed ... the median is a distribution-free statistic and standard errors can not be calculated in this case.

UPDATE my use-case is the following I have millions of users, they reach some categories e.g. $C \subset B \subset A$. Meaning all users in C are in B and A and all users in B are in A but not the other way around. Since what I am doing is exploratory analysis and inference I would like to create relevant samples of users within each group in a short time.
The final process should first select all users in A, then excluding the ones in A, find all users in B and so on. This exclusion process is computationally very expensive to do in all the data so I needed a way to ensure exclusivity so that A users don't slip randomly into the B group which would be the case if I simply random sample from A, B and C.
The best way I found to do that is choosing the top N users, because it is guaranteed that the top users in B excluding the top users in A, will not contain top users in A slipping into B randomly.
Comment: No statistical method is "assumptions-free."  BCa makes assumptions about dataset size and the distributional property it is estimating. However, it makes no specific *distributional* assumptions: that's what "non-parametric" means. A great deal of your (original) question appears to be based on incorrect premises. For instance, it's straightforward to obtain confidence intervals for medians; the distribution of the data does not (and should not) determine whether you estimate a mean; you can't use any of these methods to make inferences from non-random samples.
Comment: non overlapping intervals are not required for significant difference of the parameters/statistics. little overlaps are tolerable. bootstrap methods can be used for hypothesis tests directly.
Comment: Could you expand on your second point a little?   What is $N$ and why 1.5k, among other things?
Comment: @jbowman thank you! question updated!
Comment: @whuber thank you! Can you please not be answer-shy and turn your comment into a proper answer?
Answer: As @whuber notes in a comment, you do need to deal first with what seem to be incorrect premises in your approach. Most important, if your samples aren't truly random then "you can't use any of these methods to make inferences," as he put it. Fix that first.
In terms of mean versus median as a measure of central tendency, the choice is yours based on your understanding of the subject matter unless your data are from a distribution like the Cauchy distribution, which has a median but not a mean. Skewness per se has nothing to do with it; the Cauchy distribution is symmetric about its median.
As @carlo put it in a comment, non-overlap of 95% confidence intervals is much too stringent a test for a difference between two values at p < 0.05. See this classic answer from @whuber for details in the case of t-tests. The associated suggestion to use bootstrap directly to test your hypotheses about differences is worth pursuit.
This answer goes into detail about several ways to use bootstrapping to estimate confidence intervals. You clearly can compute BCa confidence intervals for any data set regardless of underlying distribution, but the question is whether 95% confidence intervals determined that way represent true 95% confidence intervals. BCa is designed to deal with bias and skew, and might perform the best of common ways to estimate confidence intervals via bootstrapping, but you can't necessarily be sure.
The problem is that confidence intervals are based on a null hypothesis: there is no difference in the value of the parameter of interest between the two populations. In contrast, the data from which you are sampling might actually represent two different populations with respect to that parameter. For bootstrapping to provide reliable confidence intervals in that case you should be evaluating a parameter that is pivotal. As @AdamO has put it: "This means that if the underlying parameter changes, the shape of the distribution is only shifted by a constant, and the scale does not necessarily change. This is a strong assumption!" In that sense, the BCa confidence intervals are not assumption-free. It might be impossible in some cases to get reliable bootstrapped estimates of confidence intervals, as when sampling from a lognormal distribution without transformation. The answer linked at the beginning of the previous paragraph provides several references on these matters.
Comment: thank you so much for your very comprehensive and extremely useful answer! I will follow your advice and path of action.


Why thinner strings in a pair are on top position?

Question: When I play twelve string guitar, it bothers me that when I play the bass strings too gently, sometimes only the thinner string of the pair gets played, thus without the desired bass sound.
I wonder why it is like that, and mostly I woul like to know if there is a problem if I swap them.
Comment: being able to swap them depends on your instrument, specifically the nut. Generally the nut is slotted for the string gauges, so switching positions would require widening the thin string's slot to allow the new thicker string.  If you have a zero fret or other nut system you may not need to alter it, so answer depends.
Answer: When the pick touches the thicker string first, the likelihood that it passes by the second string entirely is higher.  On the backstroke, the pick is usually tilted stronger so that this is less likely to happen.
According to the Wikipedia article on twelve-string guitars, Rickenbacker's electric guitars have their courses wired reversely but most other makers do it with the higher note in upper position.
Comment: Makes perfect sense.


How to encode factors as dummy variables when using stepPlr?

Question: When using the step.plr() function in the stepPlr package, if my predictors are factors, do I need to encode my predictors as dummy variables manually before passing it to the function? I do know that I can specify "level", but how  the "level" parameter works is confusing to me.
My understanding is that I need to tell step.plr() explicitly which factors should be encoded as dummy variables and thus leaving one factor out intentionally.
Let's consider a simple example. Suppose I have 1 categorical predicator with 4 levels and binary response. Normally, if I use glm() to fit a logistic regression model, glm() would automatically convert the categorical predicator into 3 dummy variables. Now in stepPlr(), do I specify the "level" parameter for that predictor with 4 levels or 3 levels? The "Help" section is vague, and says:

If the j-th column of x is discrete, level[[ j ]] is the set of levels for the categorical factor.

Does it mean I should tell step.plr() about all 4 levels, or I should make an intelligent decision myself and tell step.plr() to use only 3 levels?
==============UPDATE (16 Oct 2012)=============
The following example will demonstrate what is the problem with step.plr()'s automatic dummy variable encoding. It is a slight modification of the code in the function's help section.
     set.seed(100)
n <- 100
p <- 3
z <- matrix(sample(seq(3),n*p,replace=TRUE),nrow=n)
x <- data.frame(x1=factor(z[ ,1]),x2=factor(z[ ,2]),
                x3=factor(sample(seq(3), n, replace=TRUE, prob=c(0.2, 0.5, 0.3))),
                x4=factor(sample(seq(3), n, replace=TRUE, prob=c(0.1, 0.3, 0.6))))
y <- sample(c(0,1),n,replace=TRUE)
fit <- step.plr(x,y, cp="aic")
summary(fit)

And here's an excerpt of the result:
Call:
plr(x = ix0, y = y, weights = weights, offset.subset = offset.subset,
    offset.coefficients = offset.coefficients, lambda = lambda,
    cp = cp)

Coefficients:
      Estimate Std.Error z value Pr(>|z|)
Intercept  0.91386   5.04780   0.181    0.856
x4.1       1.33787   4.61089   0.290    0.772
x4.2      -1.70462   4.91240  -0.347    0.729
x4.3       0.36675   3.18857   0.115    0.908
x3.1:x4.1  7.04901  14.35112   0.491    0.623
x3.1:x4.2 -5.50973  15.53674  -0.355    0.723
x3.1:x4.3 -0.50012   7.95651  -0.063    0.950

You can see that all levels, that is, (1,2,3), are used to fit the model. But normally you only need two dummy variables to encode a predictor with 3 levels.
On the other hand, if you use glm():
glm(y~.^2, data=x, family=binomial)

you will get the correct dummy variable encoding.
Answer: See the first example given in help for step.plr
n <- 100
p <- 3
z <- matrix(sample(seq(3),n*p,replace=TRUE),nrow=n)
x <- data.frame(x1=factor(z[ ,1]),x2=factor(z[ ,2]),x3=factor(z[ ,3]))
y <- sample(c(0,1),n,replace=TRUE)
fit <- step.plr(x,y)
# 'level' is automatically generated. Check 'fit$level'.

Does that answer your question?
Comment: I'm afraid that it does not answer my question. Please see 16 Oct 2012 update for more details. Thanks.
Comment: Evidently step.plr uses effect coding
Comment: effect coding it is. I checked the source code of step.plr() and it indeed uses effect coding. Thanks for the answer.


How to use a proxy in the SharpSVN client

Question: i use SharpSVN in my app to check out a repository from a http server. I'm behind a firewall and need to use a proxy server to connect.
Can i set this and when, where is it?
Thanks.
Andreas
Answer: If you use the default configuration (E.g. not setting your own config directory) Subversion stores its settings in %APPDATA%\Subversion and in HKEY_CURRENT_USER\Software\Tigris.org\Subversion. If you set your settings there they will be automatically applied via SharpSvn.
You could use a tool like AnkhSVN or TortoiseSVN to edit the registry settings via a GUI. They share these same setting locations.
It is possible to programmatically override these settings from SharpSvn if necessary, but using the central settings is in most cases much easier.
See http://svnbook.red-bean.com/en/1.7/svn.advanced.confarea.html#svn.advanced.confarea.opts.servers for details on what to configure in the files.


Does using Visual Studio with TFS require a persistent connection to TFS from VS?

Question: I'm an IT project manager. A developer on my team is complaining that she keeps losing her connection to TFS and that VS requires a constant connection to TFS to work for her. Our CIO is asking me why she doesn't only need a connection to TFS while checking in and out code. I do not know the answer.
Thank you,
Val
Comment: Why? Because TFS is based on an outdated source control paradigm. The workaround? See for example [How to work offline with TFS](https://stackoverflow.com/questions/934875/how-to-work-offline-with-tfs), or fix your network infrastructure. The solution? Upgrade your source control to a solution that uses Git.
Answer: TFVC, Team Foundation Version Control, is one of the ways to store sources in Team Foundation Server (TFS), if your TFS serves is 2015 or later, Git is the new default. TFVC is a centralized version control system and assumes your developer has a persistent connection to the server. This is especially true when the workspace of the developer is configured as a "server" workspace, in which case each file system operation is synced to the central server.
In Workspace Type = Server mode your options are:

Use the Go Offline option to temporarily disconnect from the server and work locally in isolation.
Of Change the workspace type to local, which creates a local folder with a compressed copy of each file in the workspace.

This will reduce the number of interactions with the server, making it more pleasant to work when authentication is messed up. But a developer should be checking in and out code at a regular interval, preferably each change that puts the code in a stable state. I'd get VERY frustrated when even something as a checkin/checkout requires an auth prompt.
But your real problem
Is not whether TFS is prompting for auth, it's why the workstation or the server infra isn't (allowing the) caching of the credentials. This can have many causes:

The TFS server isn't configured with a secure connection (https)
The TFS server name doesn't match the server configuration
A proxy server is interfering
A local development proxy (like Fiddler) is turned on and not configured to ignore the TFS server
The Active Directory policy is forcing the credentials to not be stored
The TPM of the computer isn't working well and keeps resetting
There is a VPN interfering
Some endpoint monitoring system is detecting suspicious behavior and is triggering a re-auth
An incorrect credential is cached in the Windows Credential Manager.
The TFS server is in the wrong internet security zone
The Internet security zone settings are configured to not store credentials
...
...

Solve that and the developer will be much happier.
And TFVC is getting old (and most teams have moved to Git)
As others already commented, TFVC is getting old and many development teams have migrated to Git. Git gives developers a local copy of the sources and its history to work with, giving much more power to the developers to work locally without a need to connect to a central server.
If migration isn't an option (yet), tools like git tfs can help a developer to start working in Git locally, while still connecting to a central TFVC server to send the changes to the rest of the team.
But the long-term solution is to upgrade your development tools and get rid of TFVC.
TFS is getting old (is now Azure DevOps Server)
And while you're at it, TFS is getting old. It has been renamed in 2018 and is now called Azure DevOps Server. Azure DevOps Server 2020 is the latest. If you're having issues with TFS, making sure it's up to date and installed on a recent Windows Server version helps too.


Game Programming - & Logical Operator and .getRGB() Method

Question: I have two question pertaining to the code below:
pixels = image.getRGB(0, 0, width, height, null, 0, width);

for(int i = 0; i < pixels.length; i++)
{
    pixels[i] = (pixels[i] & 0xff) / 64;
}

My first question is what does the last argument, which is set as width, do in the .getRGB method. The second is what does (pixels[i] & 0xff) / 64 do, since I have never encountered the & operator nor do I know what 0xff means, I assume, however, that it has something to do with altering the RGB value. This is for a 2D game, I am trying to make, as per a book I am currently reading.
Here is the full code: http://pastebin.com/fPjvrFWG
Thank you!
Comment: what particular class is `image` an instance of?
Comment: Done. Sorry, for it being vague.
Comment: BufferedImage, is what image is an instance of.
Comment: http://pastebin.com/fPjvrFWG, here is the full code.
Comment: what is `image`? [`java.awt.Image`](http://docs.oracle.com/javase/7/docs/api/java/awt/Image.html) doesn't have a `getRGB` method.
Comment: as for the second half - check any java tutorial that mentions bitwise operations
Answer: For the final scansize parameter, see the Javadocs:

With a specified coordinate (x, y) in the image, the ARGB pixel can be accessed in this way:
pixel = rgbArray[offset + (y-startY)*scansize + (x-startX)];

The intent of this is to allow your destination array to have a width that is different from the portion that is being extracted.
The & 0xff operator is extracting just the blue component of the ARGB pixel value, since the bits in the pixel are arranged thus:
AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB

So "anding" with 0xff produces:
00000000 00000000 00000000 BBBBBBBB

Then, the division by 64 is throwing away all but the two most significant bits of that blue value, i.e. 0 - 63 becomes 0, 64 - 127 becomes 1, 128 - 191 becomes 2, and 192 - 255 becomes 3.
Comment: Could you maybe give me an example about how this would work? I don't really understand. I get that my integer has 4 parts ARGB, but why would doing 0xff, return only B. The division by 64 I get now though. So, I suppose my new questions are why does the book only return the B? What connotations does that have? And also, how does doing 0xff return only the B, because from my knowledge the & operator does something like this: 000111 & 011101 = 000101
Comment: Ok, so I think what is happening is the code is trying to make the image monochromatic then add in color later, in order to make it run better, so if that is correct, please correct me if it is not, then the main thing I want to know is how exactly 0xff extracts the B portion.
Comment: I've added an explanation of how it's just the B value getting extracted, but I cannot offer you an explanation as to _why_, since that depends on the semantics of the game and code we haven't seen.
Comment: Thank you so much, so what exactly is 0xffffffff. Because to my knoweldge fffffffff is [11111111 11111111 11111111 11111111] in binary, so does x 0, just make all of those values 0, because 1 x 0 = 0? And if that is the case, wouldnt B = 0 also? Or am I wrong?
Comment: Sorry, the `0xffffffff` was a typo, I meant just `0xff`, i.e. `1111 1111` in binary.
Comment: Ok, well ff = 11111111, so 0xff = 00000000 right? Therefore, wouldn't AAAARRRRGGGGBBBB & 0xff = 00000000GGGGBBBB?, because only 8 0's?
Comment: No, the `0x` is just how hexadecimal constants are written in Java. `0xff` in an `int` is binary `00000000 00000000 00000000 11111111`.
Comment: Ok, I think I get it. Can you just clarify if my understanding is right? So 0x, is just you telling Java that the following ff is hex. ff is 11111111 in binary, which is 256 in decimal. RGB has values up to 256, since you are anding it pads the 11111111 with 0's before it, thus creating 00000000 00000000 00000000 11111111, meaning that everything but blue turns to 0.
Comment: Yes, that's right, except that `0xff` is _255_, not _256_.  RGB values go 0 .. 255
Comment: Thank you, so much. This really helped. Sorry for asking so many questions.


Sequelize Or condition in Join

Question: I'm trying to do a query with Sequelize ORM with custom join condition.
There is the example:
User.findAll({include: [{model: Post, where: {active: true}}]

This is the result of join condition:
INNER JOIN `posts` AS `post` ON `users`.`id` = `post`.`user_id` AND `post`.`active`=true

What I'm trying to do is replace the AND condition to OR and spect something like this:
INNER JOIN `posts` AS `post` ON `users`.`id` = `post`.`user_id` OR `post`.`active`=true

I don´t know if there is a way to do that.
Comment: Does it make sense to get ALL active posts even if they are not related to a certain user?
Comment: This is only an example and I want to replace AND to OR
Answer: You can't add conditions to a JOIN condition with OR. You can only add additional outside conditions among which you can use OR.
User.findAll({
   where: {
     [Op.or]: [
       { '$Post.somefield$': sequelize.col('some_user_field') },
       { '$Post.someotherfield$': sequelize.col('some_other_user_field') }
     ]
   },
  include: [{
    model: Post
  }
]})

This query will be like this in SQL:
SELECT * FROM USERS as `users`
INNER JOIN `posts` AS `post` ON `users`.`id` = `post`.`user_id`
WHERE
  `post`.`somefield`=`users`.`some_user_field`
 OR
  `post`.`someotherfield`=`users`.`some_other_user_field`

Sequelize Or condition in Join


How many different possible expressions can I have?

Question: I have three numbers $a,b$ and $c$
How many different additions can I have ?
$a + a + a = 3a$
$a + a + b = 2a + b$
However, $a + b + a =2a + b$ which is the same addition as above so I neglect it.
$b + b + b = 3b$
$a + b + c = a + b + c$
and so on , How many different sums can I have ? It's definitely not a permutation $3^3$ and not even a permutation with repetition and It is also definitely not $3!$
How many different additions and why ?
Answer: What you are looking for are combinations with repetition or combinations with replacement.
The formula for this is ${n+r-1\choose{r}}$, where $n$ is the number of objects you are choosing from, and $r$ is how many you are choosing.
In this case we have $n=3$ and $r=3$ so
${3+3-1\choose{3}} = {5\choose{3}} = 10$ combinations.
Answer: One combination is to use $1a, 1b,1c$. Thus, you have $1$ combination.
Another combination is to use $2a,\, 1b,\, 0c$ or $1a,\, 2b,\, 0c$ etc. (i.e. you use an element twice, another element once, and the other element not at all). So, you need all the arrangements, which are $3!=6$.
Following the same procedure the final way is to use $3a,\, 0b, \,0c$ or $0a,\, 3b,\, 0c$ etc. which gives just $3$ combinations.
So, all the possible combinations are $1+6+3=10.$
Answer: It could be determined by counting how many $a, b$ are selected from 0 to 3.
For examples,
2 'a's, 1 'b', 0 'c'
3 'a's, 0 'b', 0 'c'
1 'a's, 0 'b', 2 'c'
If a=0, we could choose b from 0 to 3. Thus, 4 cases are available. Because a and b are chosen, c is automatically determined.
If a=1, b could be from 0 to 2. ==> 3 cases.
If a=2, b could be either 0 or 1. ==> 2 cases.
If a=3, we don't have any choice. ==> 0 case.
Thus, 10 total cases are available.


Find the series expansion of 2 multiplied functions

Question:
The first three terms in the series expansion of $(1+x)^m$ are $1 + mx + \dfrac{m(m-1)x^2}{2}$.
Find the first 3 terms in the series expansion of $(1+x)^{m+1}(1-2x)^m$.

I don't really know how to do this, because I have always done these binomial expansion using binomial coefficients and Pascal's triangle.
Answer: The best way is to change your variables around so you don't get confused between $x$'s, $m$'s, and other variables. I recommend rewriting your original expansion as follows:
$${(1+x)}^m \implies {(1+u)}^t = 1 + tu + \frac{t(t-1)u^2}{2}$$
Then think of the second expression as using the arguments with particular values of $t$ and $u$:
$${(1+x)}^{m+1}{(1-2x)}^m \implies {(1+(x))}^{m+1}{(1+(-2x))}^{m} \\ = {(1+u_1)}^{t_1}{(1+u_2)}^{t_2}$$ where $u_1 = x; \quad t_1 = m+1; \quad u_2 = -2x; \quad t_2 = m$.
Then you can expand the expression above, using the first expansion, for the subscripted $u$'s and $t$'s to get:
$${(1+u_1)}^{t_1} = 1 + t_1u_1 + \frac{t_1[t_1-1]{u_1}^2}{2} \\ = 1 + (m+1)(x) + \frac{(m+1)[(m+1)-1](x)^2}{2} \\ = 1 + mx + x + \frac{(m+1)(m)x^2}{2}$$
And similarly for the second expression:
$${(1+u_2)}^{t_2} = 1 + t_2u_2 + \frac{t_2[t_2-1]{u_2}^2}{2} \\ = 1+ (m)(-2x) + \frac{(m)[(m)-1]{(-2x)}^2}{2} \\ = 1-2mx+\frac{m(m-1)4x^2}{2} \\ = 1-2mx+2m(m-1)x^2$$
Now all that needs to be done is multiply the two halves of the original product ${(1+u_1)}^{t_1}{(1+u_2)}^{t_2}$:
$${(1+u_1)}^{t_1}{(1+u_2)}^{t_2} = \left( 1 + mx + x + \frac{(m+1)(m)x^2}{2} \right) \left( 1-2mx+2m(m-1)x^2 \right)$$
At this point, the product is just tedium to find the first 3 terms of the expansion you're looking for.
Comment: That's clever, thanks.
Answer: You can use the Taylor series technique if you are familiar with it. Here are the three desired terms
$$ 1+ \left( 1-m \right) x + \frac{m}{2}( m-7) \,{x}^{2}.$$
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert #1 \right\vert}%
 \newcommand{\yy}{\Longleftrightarrow}$
$\large\tt Hint:$
\begin{align}
&\color{#0000ff}{\large\pars{1 + x}^{m + 1}\pars{1 - 2x}^{m}}
=
\sum_{\ell = 0}^{m + 1}{m + 1 \choose \ell}x^{\ell}
\sum_{\ell' = 0}^{m}{m \choose \ell'}\pars{-1}^{\ell'}2^{\ell'}x^{\ell'}
\\[3mm]&=
\sum_{\ell = 0}^{m + 1}{m + 1 \choose \ell}x^{\ell}
\sum_{\ell' = 0}^{m}{m \choose \ell'}\pars{-1}^{\ell'}2^{\ell'}
\sum_{n = 0}^{2m + 1}x^{n - \ell}\delta_{n - \ell,\ell'}
\\[3mm]&=
\sum_{n = 0}^{2m + 1}x^{n}
\sum_{\ell = 0}^{m + 1}{m + 1 \choose \ell}\pars{-1}^{n - \ell}2^{n - \ell}
{m \choose n - \ell}\sum_{\ell' = 0}^{m}
\delta_{\ell',n - \ell}
\\[3mm]&=
\sum_{n = 0}^{2m + 1}x^{n}\bracks{%
\sum_{{\vphantom{\Large A}\ell\ =\ 0} \atop {\vphantom{\LARGE A}0\ \leq\ n - \ell\ \leq\ m}}^{m + 1}{m + 1 \choose \ell}{m \choose n - \ell}\pars{-1}^{n - \ell}
2^{n - \ell}}
=
\color{#0000ff}{\large\sum_{n = 0}^{2m + 1}a_{n}x^{n}}
\end{align}

$$
a_{n}
\equiv
\sum_{{\vphantom{\Large A}\ell\ =\ 0}
      \atop
      {\vphantom{\LARGE A}n - m\ \leq\ \ell\ \leq\ n}}^{m + 1}
{m + 1 \choose \ell}{m \choose n - \ell}\pars{-2}^{n - \ell}
$$

\begin{align}
a_{0}
&=
\sum_{{\vphantom{\Large A}\ell\ =\ 0}
      \atop
      {\vphantom{\LARGE A}-m\ \leq\ \ell\ \leq\ 0}}^{m + 1}
{m + 1 \choose \ell}{m \choose 0 -\ell}\pars{-2}^{-\ell} = 1
\\[3mm]
a_{1}
&=
\sum_{{\vphantom{\Large A}\ell\ =\ 0}
      \atop
      {\vphantom{\LARGE A}1 - m\ \leq\ \ell\ \leq\ 1}}^{m + 1}
{m + 1 \choose \ell}{m \choose 1 - \ell}\pars{-2}^{1 - \ell}
\\[3mm]
a_{2}
&=
\sum_{{\vphantom{\Large A}\ell\ =\ 0}
      \atop
      {\vphantom{\LARGE A}2 - m\ \leq\ \ell\ \leq\ 2}}^{m + 1}
{m + 1 \choose \ell}{m \choose 2 - \ell}\pars{-2}^{2 - \ell}
\end{align}


Grouping fields with field group doesn't work on display of Drupal Commerce product in product variation

Question: I've got a content type for a product and fields for variation. I'm writing about fields in that variation. I have created new group containing some fields using field groups.
Let's say:
[Field group]
 1. Foo
 2. Bar

The group setup is done properly on content type/field display in product variation tab. I'm using drupal commerce, I have tried updating CRON, flushing cache, drinking beer, resaving content. It didn't help. Anyone has any idea?
Answer: The Field Group module provides the ability to group on both the edit form and the display independently.
This means to add a field group to the form you have to do so on admin/structure/types/manage/CONTENTTYPE and to add a field group for display you do it on admin/structure/types/manage/CONTENTTYPE/display (this is for nodes, this will be in different places for other entity types).
If you want the group on both the form and the display you have to add it in both places.
Comment: The answer doesn't address the question, which was regarding Field Group with the Commerce Product Form Management User Interface.

Currently, the field grouping capabilities doesn't work as of May 28th, 2015 with the latest modules installed.
Answer: My specific question instead of normal nodes was about drupal commerce product. Everything is ok if you create group for a content type and select for ex.
 wrapper. But groups are not showing when you change display in product variation (product-variation-types/product/display) and they also don't work with HTML5 wrapper (see bottom).
I've got code like this

    <field></field>

    <field></field>

    <field></field>

    <field></field>

    <field></field>

And I wanted to put the fields into a group:

        <field></field>

        <field></field>

        <field></field>

        <field></field>

HTML5 wrapper bug
But the result after selecting HTML5 wrapper was:

    <id="field-group">

        <field></field>

        <field></field>

        <field></field>

        <field></field>


Snooker fouls before tv

Question: When a foul occurs in snooker, they use "instant replay" or whatever to put the balls back in their original position if the opponent wants the shooter to try again.
How did they do this before TV? I mean, if the cue ball didn't touch anything, I could see both players agreeing on where it was, but sometimes many balls are moved.
And, what happened if the players could not agree on the spot?
Answer: The referee does the replacement in the same way every official has ever made a decision before TV replays regardless of the sport. They use their memory and their knowledge and the game-specific techniques they are trained in.
The snooker referee is only required to replace "the ones that matter". Obviously the cue ball counts, and any object balls that were close to its intended path or that have moved into an advantageous position as a result of the foul. A good referee notes in their mind the placement of the cue ball relative to landmarks on the table or in the venue, and where key object balls were placed relatively to the cue ball and similar landmarks.
Having made the replacement, they ask players if the arrangement is correct, and players may indicate (but not move) balls that need further correction. The referee holds the final decision in the case that players disagree with each other or with the referee.
Without a referee, of course, it is upto players to determine together where the balls should be placed, and local rules or specific competitions will have a method of resolving disagreement.
Comment: Also, before TV (and until the 80s)  the miss rule was only applied for an extremely obvious deliberate miss, unlike now when the balls can be replaced no matter how near the miss was.

Snooker fouls before tv


How to show that the push forward of a sigma algebra is a sigma algebra.

Question: Let $\mathcal{M}$ be a sigma algebra on $X$. Let $f:X\to Y$. Define $$ \mathcal{A}=\{B\subset Y : f^{-1}(B)\in \mathcal{M}\}. $$ The problem is to show that $\mathcal{A}$ is a sigma algebra on $Y$.
This is my attempt.
Clearly, $\emptyset \in \mathcal{A}$.
Let $\{B_k\}_{k=1}^\infty$ be a countable collection of sets such that $f^{-1}({B_k})\in \mathcal{M}$.
 Then $f^{-1}(\cup B_k)=\cup f^{-1}(B_k)\in \mathcal{M}$. So $\cup B_k \subset Y$ and hence $\cup B_k\in\mathcal{A}$.
 Also, $f^{-1}(B^c)=(f^{-1}(B))^c\in \mathcal{M}$ and so $B^c\in \mathcal{A}$.
Thus $\mathcal{A}$ is a sigma algebra on $Y$.
Please, is what I have done right?
Comment: Yes. The point being that $f^{-1}$ commutes with set operations. Which you should show...!
Comment: Looks fine to me, but I have a question: what motivated you to ask this question? No no, don't get me wrong, I am just trying to help: is there anything specific that is bothering you about your solution? Something that feels "not right?"
Answer: Your attempt is good.   The inverse image operation plays nicely with set operations.
Comment: @Jacob: You should probably call your construction a "pushforward" rather than a "pullback" since you started with a $\sigma$-algebra on $X$ and built a $\sigma$-algebra on $Y$.


Existe alguma maneira de alterar uma mensagem de um commit?

Question: Eu trabalho com git em todos os projetos da empresa onde trabalho. Infelizmente, alguns programadores acabam por colocar  uma mensagem qualquer, em um momento de pressa, num commit. Isso dificulta as coisas, pois ao invés de você ver a descrição do que foi feito no git log, você passa a ter que "chutar" pela data de um commit específico.
Alguns colocam coisas como git commit -am ":)" ou git commit -am "tudo".
Exemplo:
commit 18d76fbaa661945ef59f675092f5050d3d7016a3
Merge: 7f0aea2 8ca43f6
Author: XXX XXXX <xxx@email>
Date:   Wed Feb 17 10:26:40 2016 -0200

    all

commit 7f0aea214c26e84b18a8768a7d282b760b7a230a
Author: XXX XXXX <xxx@email>
Date:   Wed Feb 17 10:22:38 2016 -0200

    all

Eu gostaria de saber se existe alguma maneira de reverter tais lambanças.
Existe alguma forma de editar uma mensagem de um commit específico?
Comment: Tem um jeito mais fácil, faça um upgrade de programadores ou troque eles por versões mais novas onde esse bug já foi corrigido :D
Comment: O que posso fazer para melhorar minha pergunta? O voto negativo é nesse sentido?
Answer: Complementando a resposta do Rodrigo, se você quiser apenas alterar a mensagem do último commit, utilize git commit --amend -m "SUA NOVA MENSAGEM AQUI".
Mas se você quiser alterar qualquer outro commit, inclusive o primeiro commit do repositório, utilize git rebase -i --root
Em seu editor de texto padrão do terminal (nano, vim, etc) vai abrir um arquivo começando com algo similar a isso:
pick 4c5877b first commit
pick edbd6ae second commit

4c5877b e edbd6ae são os dois commits existentes no meu repositório de testes, e first commit e second commit são as mensagens de commit que eu usei.
Troque pick por r ou reword em todos os commits que você deseja alterar e salve o arquivo. No meu caso eu quis modificar o second commit, então ficou assim:
pick 4c5877b first commit
reword edbd6ae second commit

Vai aparecer no seu editor de texto as informações do(s) commit(s) que você quis alterar, incluindo a mensagem do(s) mesmo(s). Altere-a(s) e salve o(s) arquivo(s).
Meu git log antes do rebase:
commit edbd6ae914877887c8304895d3a2a1fc4d95769a
Author: xyz <email@example.com>
Date:   Mon Feb 22 20:23:22 2016 -0300

    second commit

commit 4c5877b870d177d5a9dd432ff87a7b006efbc29c
Author: xyz <email@example.com>
Date:   Mon Feb 22 20:23:22 2016 -0300

    first commit

e depois:
commit e462bfac89165e5af4e0aec60e6758330cbe196d
Author: xyz <firstname.lastname@example.com>
Date:   Mon Feb 22 20:23:22 2016 -0300

    MODIFICADO second commit

commit c3a909e630a806b01d099bf40319cdbc26c96a59
Author: xyz <email@example.com>
Date:   Mon Feb 22 20:23:22 2016 -0300

    first commit

Comment: Era isso mesmo que eu precisava, valeu :)
Answer: É possível alterar a mensagem mais recente com o comando:
git commit --amend
Para alterar mensagens mais antigas, é necessário alterar a base de onde você está trabalhando para que a mais recente seja a de cima.


Como mover as bordas de posição após o hover?

Question: Tenho essa div com bordas nos cantos e queria que a borda da direita fosse para baixo e a da esquerda para cima quando a div estiver em hover porém não consegui aplicar o efeito.
Segue abaixo o que tentei:

div.classe {
    position: relative;
    float: left;
    padding: 0 10px;
    width: 80%;
    height: 100px;
    background: rgba(38, 166, 91, 0.5);
    margin-top: 30px;
    transition: all 0.4s  ease-in-out;

}
div.classe:after {
    content:"";
    height: 70px;
    width: 70px;
    position: absolute;
    bottom: 0;
    left: 0;
    border-left: 4px solid #000;
    border-bottom: 4px solid #000;
    z-index:-1;
    margin-bottom:-4px;
    margin-left: -4px;
    border-color
}
div.classe:before {
    content:"";
    height: 70px;
    width: 70px;
    position: absolute;
    top: 0;
    right: 0;
    border-right: 4px solid #000;
    border-top: 4px solid #000;
    z-index:-1;
    margin-top:-4px;
    margin-right: -4px;
}
div.classe:hover{
  transform: translateY(-20px);
}
div.classe:hover:before{
    content:"";
    height: 70px;
    width: 70px;
    position: absolute;
    right: 0;
    top: 0;
    border-right: 4px solid #000;
    border-top: 4px solid #000;
    z-index:-1;
    margin-top:-4px;
    margin-right: -4px;
    border-color
}
div.classe:hover:after{
    content:"";
    height: 70px;
    width: 70px;
    position: absolute;
    bottom: 0;
    left: 0;
    border-left: 4px solid #000;
    border-bottom: 4px solid #000;
    z-index:-1;
    margin-bottom:-4px;
    margin-left: -4px;
}

texto qualquer

Answer: Você pode colocar o efeito após o :hover utilizando ::after ou ::before.
Segue exemplo:

div.classe {
    position: relative;
    float: left;
    padding: 0 10px;
    width: 80%;
    height: 100px;
    background: rgba(38, 166, 91, 0.5);
    margin-top: 30px;
    transition: all 0.4s ease-out;

}
div.classe:after {
    content:"";
    height: 70px;
    width: 70px;
    position: absolute;
    bottom: 0;
    left: 0;
    border-left: 4px solid #000;
    border-bottom: 4px solid #000;
    z-index:-1;
    margin-bottom:-4px;
    margin-left: -4px;
    border-color
}

div.classe:before {
    content:"";
    height: 70px;
    width: 70px;
    position: absolute;
    top: 0;
    right: 0;
    border-right: 4px solid #000;
    border-top: 4px solid #000;
    z-index:-1;
    margin-top:-4px;
    margin-right: -4px;
}

div.classe:hover{
  transform: translateY(-20px);
  -webkit-transition: 0.5s ease-in;
  -moz-transition: 0.5s ease-in;
  -o-transition: 0.5s ease-in;
  transition: 0.5s ease-in;
}

div.classe:hover::after{
  border:none;
  content:"";
  position: absolute;
  top: 0;
  left: 0;
  border-left: 4px solid #000;
  border-top: 4px solid #000;
}

div.classe:hover::before{
  transform: translateY(30px);
  border:none;
  content:"";
  position: absolute;
  bottom: 0;
  right: 0;
  border-right: 4px solid #000;
  border-bottom: 4px solid #000;
}

  texto qualquer

Seguindo a sugestão do Gabriel.H segue uma versão com "delay" na transição:

div.classe {
    position: relative;
    float: left;
    padding: 0 10px;
    width: 80%;
    height: 100px;
    background: rgba(38, 166, 91, 0.5);
    margin-top: 30px;
    transition: all 0.4s ease-out;

}
div.classe:after {
    content:"";
    height: 70px;
    width: 70px;
    position: absolute;
    bottom: 0;
    left: 0;
    border-left: 4px solid #000;
    border-bottom: 4px solid #000;
    z-index:-1;
    margin-bottom:-4px;
    margin-left: -4px;
    border-color
}

div.classe:before {
    content:"";
    height: 70px;
    width: 70px;
    position: absolute;
    top: 0;
    right: 0;
    border-right: 4px solid #000;
    border-top: 4px solid #000;
    z-index:-1;
    margin-top:-4px;
    margin-right: -4px;
}

div.classe:hover{
  transform: translateY(-20px);
  -webkit-transition: 0.5s ease-in;
  -moz-transition: 0.5s ease-in;
  -o-transition: 0.5s ease-in;
  transition: 0.5s ease-in;
}

div.classe:hover::after{
  border:none;
  content:"";
  position: absolute;
  top: 0;
  left: 0;
  border-left: 4px solid #000;
  border-top: 4px solid #000;
  -webkit-transition: 0.5s ease-in;
  -moz-transition: 0.5s ease-in;
  -o-transition: 0.5s ease-in;
  transition: 0.5s ease-in;
}

div.classe:hover::before{
  transform: translateY(30px);
  border:none;
  content:"";
  position: absolute;
  bottom: 0;
  right: 0;
  border-right: 4px solid #000;
  border-bottom: 4px solid #000;
  -webkit-transition: 0.5s ease-in;
  -moz-transition: 0.5s ease-in;
  -o-transition: 0.5s ease-in;
  transition: 0.5s ease-in;
}

  texto qualquer

Comment: Isso já resolveu muito meu problema, so uma pergunta tinha como fazer uma transição mais suave? tipo de deslisando pelas bordas?
Comment: Editei a pergunta veja agora.
Answer: Amigo se quiser uma transição mais suave , adicione isto
-webkit-transition: 0.5s ease-in;
-moz-transition: 0.5s ease-in;
-o-transition: 0.5s ease-in;
transition: 0.5s ease-in;

ao css da div.class, div.class:hover after and before
Comment: Adiconei na minha resposta, da uma olhada como ficou.
Comment: Tranquilo , não tinha certeza se ia funcionar por que eu mesmo nunca utilizei kkk
Comment: +1, estava pesquisando aqui kkk vou editar minha resposta adiconando uma versão com esse "delay"
Comment: kk , esta resolução funcionou pra você?


Probability using 2 urns

Question: There are $2$ urns:

Urn #1 contains $6$ red balls and $5$ blue balls
Urn #2 contains $1$ red ball, $3$ yellow balls and $8$ blue balls

A blue ball was drawn at random from one of the urns.
What are the chances that it was drawn from urn #1?
Am I on the right track with: $\frac{13}{23}-\frac{5}{11}\cdot\frac{8}{12}$?
Answer: Let $A$ denote the event of choosing urn #1.
Let $B$ denote the event of drawing a blue ball.
Then $P(A|B)=\frac{P(A\cap B)}{P(B)}=\frac{\frac{1}{2}\times\frac{5}{6+5}}{\frac{1}{2}\times\frac{5}{6+5}+\frac{1}{2}\times\frac{8}{1+3+8}}=\frac{15}{37}$

Probability using 2 urns