Differentiating between multiple runas account windows

Question: In past jobs I've used a lot of runas /user:.. in order to allow quick access between multiple accounts while logged in as a primary account. Both server side or and on workstations. We're looking at situations where sometimes a user might have multiple copies of the same application open under different multiple user contexts.
As such it would be extremely useful to have some kind of visual queue to differentiate based on the launching user.
In the past I always would just change the CMD prompt background colors. Here I need it for GUI applications. It looks like changes to the color scheme on Windows 7 / 2008 r2 read from the currently logged in user, not from that specific user's profile. That seems to invalidate my first choice.
What are my options?
Note:  I did think about asking this on SU not here.. Didn't think there would be many cases of people running applications under half a dozen different accounts from one active session.
Comment: This is an interesting question.  Short of looking in Task Manager and seeing what user the task is running under, I don't know of any way offhand.  I run into this too from time to time, but it is mostly on server consoles, so the user is either my account or the domain admin account.  I wonder if there is a desktop widget that would do this?
Comment: Very nice workaround...
Comment: @MikeAWood a little scripting proved to be my solution. :) Thought you might want to see.
Answer: I did find a way to address this via AutoIt. It isn't perfect but I can get most of my windows labeled. My users can launch this and have it run in the background as needed.
#Include <Array.au3>
#include <WinAPIEx.au3>
While ( True )
    Sleep( 100 )
    Local $PID = 0
    Do
        $handle = WinGetHandle("[ACTIVE]", "")
        $iPID = WinGetProcess($handle)
    Until $iPID > 0
    Local $aUser = _WinAPI_GetProcessUser($PID)
    $UserName=$aUser[0]
    $title = WinGetTitle ( $handle )
    $result = StringInStr($title, "Owned By")

    If ( $Result == 0 ) Then
        WinSetTitle($handle, "", $title & " - Owned By " & $UserName)
        $title = WinGetTitle ( $handle )
    EndIf
WEnd


how do i go about learning to play on roli seaboard

Question: I have zero experience playing any musical instrument. I received roli searboard as a gift . How should I go about learning to play this "new type of instrument" . I can of course turn pitch bend sensitivity all the way down and turn into an equivalent of a cheap midi piano keyboard and follow piano tutorials.
But that sounds wrong. wondering if anyone has any suggestions.
Edit: i have seaboard rise 25 which has 2 octaves
Answer: Any musical background you pick up can't hurt.  Call around to piano teachers and explain your situation; someone will probably be willing to help.  Or if you see a local keyboard player you like, ask if they'd give lessons.  If there's a local community college or similar that offers some kind of introduction to music theory, that could be helpful too.  I wouldn't worry too much about finding someone that specializes in synthesizers (much less Roli Seaboards); there are a lot of music fundamentals that are independent of the specific instrument.  You can figure out the specifics on your own.
One way to train your fingers and your ear is by trying to pick out tunes.  Any melody that you can sing, you can figure out how to play, with a lot of trial and error at first.  Start with the simplest possible tunes, like nursery rhymes.  See if you can play them starting on different keys.
Meanwhile, if you have music in mind that you want to make real--just go for it.  There's no magic--just keeping trying until it sounds like what you want.  Someone with more training might be able to get there faster, but in the end, if it sounds good, it is good.
Answer: You should read this book it basically breaks down the how to play piano like instruments for producers. It has fun excercises etc... and shows you the technical details in what makes music work in a simple way. Click the link and read the description and look inside to see for yourself. Read the reviews.
This book has helped me, I've tried to learn music theory before but it just went over my head. But in one night I already know how to play in three different musical modes.
Also Check out these youtubers:

 ,

Follow them as the cover the features of the roli Seaboard and talk about new updates.
https://www.amazon.com/Music-Theory-Electronic-Production-Beginners-ebook/dp/B0166SHTVM/ref=tmm_kin_swatch_0?_encoding=UTF8&qid=1514184075&sr=1-12
Comment: Hi Kai - link only answers are not useful here. Can you please include key concepts from those links here
Answer: pretty spendy present!  how many octaves?
even with 5 octaves, you're going to have trouble playing full songs.  you could maybe play some Bach pieces.
those things are made for synthesizer players.  piano is kind of a different instrument.  You ideally want at least 76 keys, preferably 88 to do all the songs.  With piano, you ideally have a piano teacher who gives you the full scale dive into what you've just jumped into and leads you carefully and quickly along.  Plan on doing an hour a day every day of your life.  That thing is a pretty specialized instrument.  A regular piano teacher probably won't be able to stand that thing and will tell you to buy at least a digital piano instead.
The alternative route, probably the one for you, is to just dink around with a synthesizer.  Not playing full songs, but adding short embellishments on top of an existing song.  so you'll need to pick out a good (probably software based) synthesizer and look for some synthesizer playing videos maybe.  There are piano teachers everywhere, but there are NOT synthesizer teachers everywhere.  They're few and far between.  Hopefully you are a serious nerd like me who gets into the inner workings of things like synthesizers.  Cuz it's kind of a deep topic, lots of software options to weed through.  Your path forward is not straightforward.
Musical instruments require dedication and a pretty good chunk of your life.  They are, however, very rewarding.
Comment: thank you for your response. I have the cheapest roli with 2 octaves. I am going to spend time on learning synthesis then, i have basic knowledge but not enough to be able to compose full tracks on roli.
Comment: Ideally I was hoping to learn to play sitar or flute on roli but that seems like a tall order .


Alternative way of calculating the intersection number on a surface

Question: Let $X$ be an algebraic surface over a field $k$ and let $D,E$ two smooth prime divisors on $X$. Assume that $e_x,f_x\in\mathcal O_{X,x}$ are the local equations at $x$ of $D$ and $E$ respectively. Let $v_{D,x}$ be the valuation at $x\in D$ (w.r.t the curve $D$). For any $x\in D$ there is a natural projection $\pi:\mathcal O_{X,x}\to k(D)$ (where $k(D)$ is the function field of the curve $D$ or equivalently the residue field at the generic point of $D$).
I'd like to understand why the following equality is true for any $x\in D\cap E$:
$$v_{D,x}(\pi(f_x))=\operatorname{length}_{\mathcal O_{X,x}}\left(\mathcal O_{X,x}/(e_x,f_x)\right)=:i_x(D,E)$$
In other words I'd like to understand why it is possible to calculate the local intersection number by means of the one dimensional valuation.
Answer: This is a local computation, so assume that $X = \operatorname{Spec} A$, and say $x\in D\cap E$ is given by the maximal ideal $\mathfrak{m}$. Then the natural projection is given by the projection $\pi: A_{\mathfrak{m}} \rightarrow A_{\mathfrak{m}}/e_x A_{\mathfrak{m}}$.
We claim that $v(\pi(f_x)) = length(A_{\mathfrak{m}}/(e_x,f_x))$. This reduces to the commutative algebra claim that if $(R,\mathfrak{m})$ is a discrete valuation ring with residue field $k$ where $R$ is a $k-$algebra containing $k$ mapping isomorphically to its residue field, and $f\in R$, then $\dim_k R/(f) = val(f)$. Note that the condition allows me to view $R/(f)$ as a $k-$vector space.
To see this, note that $val(f) = n \iff f = u \nu^n$ where $\nu$ is a local parameter for $R$, and $u\in R^{\times}$. So we see that $R/(f) = R/(\nu^n)$, and from the exactness of the following short exact sequence
$$0\rightarrow \mathfrak{m}/\mathfrak{m}^2 \rightarrow R/\mathfrak{m}^2 \rightarrow R/\mathfrak{m} \rightarrow 0$$
of $k-$vector spaces (and induction), we see that $\dim_k R/(\nu^n) = n$.
You get your original claim by letting $R=\mathcal{O}_{X,x}/(e_x)$ and $f=f_x$. To see the equality between length and dimension as a $k$-vector space, see Modules of Finite Length over Local Artinian Rings.


Filter custom message from Visual Studio 2015 output window

Question: At some point in the last couple of months, a lot of message along the lines of
Event 7 was called with 5 argument(s) , but it is defined with 6 paramenter(s).
Event 10 was called with 5 argument(s) , but it is defined with 6 paramenter(s).
Event 10 was called with 5 argument(s) , but it is defined with 6 paramenter(s).

started spamming my Visual Studio output window making it hard to find actual trace and debug messages.  Where are these messages coming from, and how do I disable them?
To try to solve this problem, I have tried several things.

Most of the answers point to configuring the checkboxes in the output window.  If I uncheck "Program Output" the problem messages go away, but so do the messages I want to keep.
I tried creating a custom TraceListener and set a breakpoint in the Write and WriteLine methods in the hopes that the call stack would tell me where the messages were being generated from.  I discovered that these messages are not coming from the typical Diagnotics.Debug or Diagnotics.Trace methods.
I tried redirecting the console via Console.SetOut() to a custom TextWriter that I could set breakpoints within.  Again, I could not find anything.

Any help would be appreciated.
Comment: @erdomke Did you find where this was coming from and/or how to fix it?
Comment: For which projects? [Stackify](http://stackoverflow.com/q/42123222/1997232) ? [Azure](https://social.msdn.microsoft.com/Forums/vstudio/en-US/f99be030-a2d9-4013-92f9-075bff0b318a/debugger-output-says-an-event-was-called-with-wrong-number-of-arguments-cant-find-source?forum=vsdebug) ? [Rebus](https://github.com/rebus-org/Rebus/issues/566) ?
Comment: I am using Stackify Prefix.  Good catch on that one.  I'm not sure how my searching didn't find it.  If you wrap that up as an answer, I will mark it as accepted.  Thanks!
Comment: You can just delete the question. The answer "It's not you, it's `Stackify`" is unlikely to be useful to others. It's very likely they will find that question too.
Comment: For my own knowledge, what search did you use to find the question?  Variations of "Event 7 was called with 5 argument(s) , but it is defined with 6 parameters)" in Google or "Visual Studio output window" didn't get me to that result in the first few pages.
Answer: As @Sinatr helpfully mentioned in his comment, this can be caused by several different system configurations which I did not find information on during my initial search.  In particular, more information can be found at the following links:

Stackify
Azure
Rebus

In my situation, the culprit appears to be the combination of Application Insights and Stackify Prefix as documented in the StackOverflow question linked above.
Answer: Ive found the assembly this string is coming from, but not yet how or where.
It is found in mscorlib.dll line 54673 in the raw dll (32 bit version): Event {0} was called with {1} argument(s) , but it is defined with {2} paramenter(s)
Its from the resource name value pairs, this one is named EventSource_EventParametersMismatch
This is being used from system\diagnostics\eventing\eventsource.cs
WriteToAllListeners
https://referencesource.microsoft.com/#mscorlib/system/diagnostics/eventing/eventsource.cs,7c04b58f26d81951


openvpn - ifconfig parameter

Question: What does ifconfig parameter in openvpn configuration file mean?
Here is an example file:
dev tun0
proto udp
comp-lzo
port 5073
remote 172.16.23.73 5073
ifconfig 172.17.3.41 172.17.3.43

Answer: From OpenVPNs own documentation:
# 10.1.0.2 is our local VPN endpoint (home).
# 10.1.0.1 is our remote VPN endpoint (office).
ifconfig 10.1.0.2 10.1.0.1

In other words this is when you want your VPN clients to assign their own VPN IP address.
The client will in my example have the IP address 10.1.0.2 and the VPN gateway will have the IP address 10.1.0.1.
Found it on my Ubuntu server under
/usr/share/doc/openvpn/examples/sample-config-files/static-home.conf

The alternative is using client-config-dir <path> in OpenVPN servers master file and let all clients connect to the server using a client certificate with unique CommonName in the certificate.
Lets say you have setup client-config-dir to point to the subdirectory ccd.
You can then create a file with a name matching the CommonName in each client certificate that contains the line ifconfig-push <IP address> <subnet mask>. Using my example above:
ifconfig-push 10.1.0.2 255.255.255.0

This assumes you have a line in the servers master config file that contains the line:
server 10.1.0.0 255.255.255.0

Comment: Thank you for explaining this!
Answer: It is to give the same VPN IP to the client. Read the Master config file. These details are already in the config file and commented out.

openvpn - ifconfig parameter


Function that maps 0 to 1 to 255 to 255

Question: Trying to come up with a function that takes a sequence of numbers from 0 to 1 and outputs a number between 255 and 255. That is, it goes from 255 to 0 and 0 to 255. I'f I come up with a solution I'll post it but in the meantime I could use some help on this.
Comment: I think he wants f(0)=f(1)=255 and f(1/2)=0, you can use f(x)=$255(2x-1)^2$
Comment: Yep close enough! A few minutes ago I came up with abs(2x-1). I guess it's one of those questions you ask and the answer comes to you.
Comment: Is this about subnet masking?
Comment: Nope, just animation related. Opacity goes 0 to 255 in this particular case.
Answer: I'm not sure whether I understand you correctly but there are an infinite number of functions that have the property you're describing. Examples:
$\left|-510x + 255\right|$ Wolfram Alpha
$1020\left(x - \frac 1 2\right)^2$ Wolfram Alpha
(Mark's example from the comments:)
$\displaystyle\frac{255(\cos 2πx+1)}{2}$ Wolfram Alpha
Comment: Can't blame you for not understanding, I'm not particularly eloquent when asking math related questions in english. Though your answer would work I ended up going with abs(2x-1) for the moment. Thank you.
Comment: Now I really don't understand! :) What does $|2x-1|$ have to do with $255$?
Comment: Woops,  |2x−1| * 255.
Comment: $\dfrac{255}{2}\left(\cos\left({2\pi}x\right)+1\right)$ might work more nicely depending on the application since the slope is flat at 0 and 1.
Answer: Not sure I understand. Do you mean 255 and 256? Do you mean 0.01 becomes 255.01, 0.2 becomes 255.2, 0.99 becomes 255.99? And then the 255+a bounces between 255+a and 0+a?
Now that I see you've posted  abs(2x-1)*255, it makes sense.
Another way to do it is something like
<code>shiftBits = max( ceil(x),1 )  or
shiftBits = x == 0 ? 1 : ceil(x);

value =  shiftLeft(0x7F, shiftBits)
</code>
I'm not specifying the programming language because I dont know what you're using.

Function that maps 0 to 1 to 255 to 255


Prevent indexing the article content after 15 lines.

Question: I am using search API and Solr .  I need to index only the first 15 lines of each  article .
the remaining lines after 15 lines has content which i don't want to index .
Please suggest if its possible .
Answer: Anything is possible :)
You can write a custom module to alter the behaviour of search api.
In the search api module directory there is a file search_api.api.php, which gives information on the functions you can use to alter its behaviour.
For this you would make a custom data alteration like this - replace modulename and ModuleName with the name of your module (case sensitive).
This part goes in your .module file:
/**
 * Define available data alterations.
 *
 * Registers one or more callbacks that can be called at index time to add
 * additional data to the indexed items (e.g. comments or attachments to nodes),
 * alter the data in other forms or remove items from the array.
 *
 * Data-alter callbacks (which are called "Data alterations" in the UI) are
 * classes implementing the SearchApiAlterCallbackInterface interface.
 *
 * @see SearchApiAlterCallbackInterface
 *
 * @return array
 *   An associative array keyed by the callback IDs and containing arrays with
 *   the following keys:
 *   - name: The name to display for this callback.
 *   - description: A short description of what the callback does.
 *   - class: The callback class.
 *   - weight: (optional) Defines the order in which callbacks are displayed
 *     (and, therefore, invoked) by default. Defaults to 0.
 */
function modulename_search_api_alter_callback_info() {
  $callbacks['modulename_character_limit'] = array(
    'name' => t('Character limit'),
    'description' => t('Limit the number of characters that get indexed for a field.'),
    'class' => 'ModuleNameCharacterLimit',
    'weight' => 100, // Probably better for this one to run later than others so they get to run on the full content before you trim it. Can still be reordered via the UI though.
  );

  return $callbacks;
}

This goes in a file named modulename_processor_character_limit.inc that goes in a sub-directory of your module called 'includes':
<?php

/**
 * @file
 * Contains ModuleNameCharacterLimit.
 */

/**
 * Processor for limiting the number of characters of a field that are indexed.
 */
class ModuleNameCharacterLimit extends SearchApiAbstractProcessor {

  public function configurationForm() {
    $form = parent::configurationForm();
    $form += array(
      'char_limit' => array(
        '#type' => 'textfield',
        '#title' => t('Character limit'),
        '#description' => t('The maximum number of characters of the field that will be added to the index.'),
        '#default_value' => $this->options['char_limit'],
        '#required' => TRUE,
        '#element_validate' => array('element_validate_integer_positive'),
      ),
    );

    return $form;
  }

  protected function processFieldValue(&$value) {
    // Chop unwanted characters from the value.
    $value = substr($value, 0, $this->options['char_limit']);
  }

}

This goes in your module's info file:
files[] = includes/modulename_processor_character_limit.inc

This will add a data alteration you can configure via the search api UI where you do things like configure the HTML filter.
You can set the number of characters to limit indexing to for our fields. - In your case, set to 15 and away you go.
(Full disclosure - I haven't tested this :))
[Edit]
As per your comment below, if you want to remove all text after a specific string (in this case "The below lines are confidential" you can do away with the char_limit setting and have a setting where you configure the text to check for (I'm calling it search_text) then change the processFieldValue() function to be:
protected function processFieldValue(&$value) {
  // If the text is found anywhere in the value.
  if (($pos = strpos($value, $this->options['search_text'])) !== FALSE) {
    // Cut off everything after that.
    // The $pos is the start of the string so if you want to also
    // exclude the string itself use $pos, otherwise to include the
    // string use $pos + strlen($this->options['search_text'])
    $value = substr($value, 0, $pos);
  }
}

Note that strpos() will return the position of the first occurance if the string occurs multiple times, which I would think is what you would want in this case.
See PHP string functions for more info on these and other string manipulation functions.
Comment: Hi Rooby ,Thanks for such a detailed solution ! Can I stop the Indexing of subsequent part of article which starts before a specific  text (example : when text start with " The below lines are confidential" , any subsequent lines after the text should be ignored for indexing ) ?
Comment: You can use the same approach to make any alterations to the indexed text. You could make a single complex data alteration or make multiple simpler ones. I've added a part about the removing text after a specific string.
Comment: Thanks a lot Rooby !!  your solutions worked . Thanks again.
Comment: Good to hear. If you select it as the correct answer it the system will flag it as being properly answered.


Graph Theory and Dijkstra's Algoirthm

Question: I am trying to use Dijkstra's Algorithm to calculate the best route the score the most objectives in a game within 60 seconds. However, some objectives in the game grant more points when scored. Is there any way I can account for it? Using weighted graphs, I can make certain paths longer than others making it take more time in my situation, however it does not help me with my main issue. If anyone can help me in addressing this situation, or tell me about another pathfinding algorithm that may help me account for this, it would be greatly appreciated.
Answer: Yes, you have to use weighted graph for problems like this. The Algorithm stays the same except that the length of paths change .

Graph Theory and Dijkstra's Algoirthm


Bayesian inferential target

Question: In frequentist, i.e., sampling-based statistics, we envision a target population to which inference is made.  Notwithstanding the fact that our so-called random samples from this population are usually more convenience-based samples, we try to infer from a sample to the population.  For example in a randomized clinical trial we pretend we have a random sample of patients with heart failure and try to make an inference about the mean treatment effect in the world population of heart failure patients.
On the other hand, in Bayesian inference we make probability statements about the unknown mean treatment effect without necessarily speaking about a "population".  What is the exact statement of what we are inferring?  Is it that the treatment was actually effective in the group of patients we analyzed?  Some deeper inference?
Update
It seems that it is safe to phrase the inferential target as a parameter in the underlying data generation process.  This is somewhat more general than envisioning a certain human population.  This generality allows for one to envision not only making an inference to a population but inference to repeated experiments involving the subjects initially included in the analysis.  For example, one might estimate a parameter for the process that generated the observations for a specific set of subjects, were those subjects to be repeatedly studied afresh (as is done in crossover studies with no carryover effects).  Such repetitions would observe different random errors for those subjects in measuring their outcomes.
There may be yet a more general way to phrase the target.
Comment: I find it difficult to envision a sampling distribution without a corresponding sample space.
Comment: I disagree that a Bayesian approach does not envision a population from which a sample is extracted, as the whole Bayesian apparatus relies on the sampling distribution.
Comment: Where in Bayesian inference does it rely on sampling?  Bayesian inference relies on a data distribution for sure, but doesn't involve the sample space to my understanding.
Comment: Isn't the zeroth assumption of any inference, Bayesian or frequentist, that the sample is representative of the population?
Comment: Bayesian methods can be used to estimate the probability of a one-time event such as a war between country X and country Y with 5 years, given data and prior probabilities.  So not sure about that.
Comment: I am puzzled by this discussion.  Bayesian methods involve priors and likelihoods.  So inference involves data from a population distribution for the likelihood part and a prior distribution that for the unknown parameter.
Comment: I may be nitpicking but the use of the word _population_ here is not clear.  Perhaps it is better to say "... data from an assumed data generating model ..." ?
Comment: Based on your update, I have a suggestion then.  I have been thinking about this problem for some time, for a different reason.  I may have accidentally made a significant update in the understanding of the statistical mechanics of cancer.  If we adopt Cox's and Jaynes understanding of plausabilities and the relationship to propositional calculus, then we can frame both the Bayesian and Frequentist problem in a language of logical assertions versus its plausibility in describing the real world.  A population statement is a statement of boundaries.  (continued in next comment)
Comment: Giraffes are not humans, but giraffes and humans are animals.  If you use a likelihood function that is simultaneously true for both humans and giraffes with the same parameter values, then the population is not humans.  It may not be animals, but it is not humans.  It may be mammals or some other subset of animals.  Likewise, humans may be perceived as the population for some drug, but it may be two alleles in the human population that behave differently when the drug is used.  The true populations are the people demarcated by the allele boundary.(continued next comment)
Comment: I would assert that the logical population a la Cox and Jaynes and the true population as bounded by the likelihood function and data generation function with identical parameterizations only match to the extent those logical assertions and the data to support them are sufficiently complete to detect a change in Bayesian model at the true boundary.  Short of that, you have an incomplete discussion because you are in an inductive trap.  Inductive reasoning is a form of incomplete reasoning.  Short of that, you run into things such as Yule's paradox.  (continued)
Comment: Rarely will the true population and the true population boundary be known in the deep sense you are looking for because our species created Aristotelian categories may not be real, though we behave as though they are.  Because of this we are left with operational definitions and statistics is quite happy with them and ignores the Platonic ideal form, which is what the true bounded population is.  Nonetheless, we may never get anything done if we don't.  Platonic thought is problematic too.  Can you imagine finding all the boundaries to all the problems?  Hope this is what you were looking for
Answer: "What is the exact statement of what we are inferring? Is it that the treatment was actually effective in the group of patients we analyzed? Some deeper inference?"
I think you are confusing the terms of art with the discussion.  One of the challenges of talking about things in multiple paradigms is that the different paradigms may use the same words to define different things, or they may not directly discuss something that is of critical importance to one paradigm, but not the other.  Both Frequentists and Bayesians, for example, have a concept called an "expectation," but they both define it in a manner that is nonsensical in the other paradigm.
I think this is what is happening here.  Sampling statistics have to concern themselves with the "population," precisely because they work in the sample space.  It isn't that a Bayesian does not care, it is that it doesn't impact their calculation on anything as directly.
A second problem is that Bayesian statistics isn't one field as there are multiple axiomatic structures you could use.  How you discuss reality may change if you use de Finetti's axioms instead of Cox's.  It also could depend upon whether you are an objectivist Bayesian who believes as Frequentists do that population parameters are fixed points, but whose location is unknown, versus subjectivist Bayesians who believe that the population parameter is a distribution that nature draws from and not a fixed point.
Someone like Jaynes, who uses Cox's postulates, would create hypothesis in terms of logical assertions.  For example, hypothesis one could be that a drug is non-harmful.  Hypothesis two would be that it is harmful.  Implicitly, this is a universal statement and hence a population statement.  The population is never mentioned.
Both methods depend upon the sample for inference, but a Bayesian can have an infinite number of hypothesis.  It is more important for a Bayesian to be clear in what they are asserting and why.
There is one other difference that is important.  When you use a Frequentist method you are concerned with the sampling distribution of the statistic and not the sampling distribution of the data.  Infinitely many distributions will have a population mean and they will all use either a t-test or z-test.  The Bayesian is concerned with the sampling distribution of the data, but not the parameters.
Consider a set of independent events that map to a probability over the set [0,1] in $d$ dimensions.  It will be approximately multivariate normal as the sample size becomes large enough.  Now let us assume that although the events are independent, the components that make up the dimensions are not.  They are part of a system.  Let us also assume they share a common variance, $\sigma^2_i=\sigma^2_j,\forall{i,j}\in{D}$, and that information about any one mean exists in the other means.
The Bayesian posterior for the set $\mu_i,i\in{1\dots{d}}$ for independent dimensions with independent variances and no shared information on the means would look very different from one where you assume a common variance $\sigma^2$ and shared information.  The Frequentist tests would be no different but the Bayesian posteriors would be.
Bayesian methods are concerned about the population through the likelihood function because it models how the data is generated in the first place in nature.  That is why Bayesian model selection methods are so important, because you may not know the true model in nature that the population uses.
Answer: This question seems to be based on a misconception. The difference between Bayesian and frequentist inferential frameworks is not that one is "sampling-based" and the other is not. It is resampling methods that yield results with the limited direct scope of inference like the statement "Is ... the treatment ... actually effective in the group of patients we analyzed?".
As I see it, there are several differences between the frequentist and Bayesian frameworks that assume greater or lesser importance depending on context.
One important difference is that frequentist approaches can only yield probabilities of the frequency of events flavour whereas the Bayesian approaches can yield probabilities of the fractional belief flavour. Thus whereas a Bayesian method might yield a result in the form of a rational belief about the effect of a treatment on a set of patients, a frequentist one will yield a statement about how often such a treatment effect might be observed in the long run given a specified value of the parameter of interest. Any connection between the frequentist result and belief is non-statistical.
Frequentist methods treat parameters as fixed where Bayesian methods treat them as variable. That leads to a difference in the treatment of evidence. Evidence provided by observations usually enters Bayesian methods in the form of a likelihood function which has at least one axis (dimension) corresponding to the parameter(s) of interest. Frequentist methods often focus on a single (null) value for the parameter of interest and therefore rarely utilise the whole likelihood function. Frequentist approaches therefore do not weigh the evidential support of all possible parameter values and the data are taken to either support the null (fail to un-support it?) or support an unspecified point within a diffuse non-null alternative.
The final notable difference that I will mention is one that is often described as being the primary difference: Bayesian methods can explicitly take existing information or opinion into account in the statistical calculations whereas frequentist methods cannot. If a non-misleading prior is available then using it seems to be a good thing, but many people are worried by the possibility of subjectivity in statistical inference.
Answer: A paper that greatly clarified these issues for me was "Models for Nonresponse in Sample Surveys" by Rod Little.
It discusses models which include as inferential targets both 1. summary quantities for actually-existing populations, and 2. parameters specifying hypothetical "superpopulations". It is also exceptionally clear.
Comment: What does it have to do with Bayesian inference?
Comment: It gives a concrete example of using Bayes with an actual population quantity, rather than a parameter, as the inferential target.

Bayesian inferential target


Where does multilevlel modeling fit in with causal inference?

Question: I am just now exploring the world of multilevel modeling and I am wondering how to contextualize MLM within the broader toolkit of causal inference techniques. In one of my graduate econometrics course, I was taught the fixed effects v. random effects dichotomy that Huntington-Klein helpfully breaks down and criticizes (random effects are only plausible with no correlation between fixed effects and right-hand side variables). In my brief exploration of Bayesian statistics via McElreaths Statistical Rethinking, he argues that MLMs should probably be the default over the standard regression model in most disciplines.
Conceptually, some of these ideas are fairly new to me, especially with how MLMs fit into the causal inference toolkit. As a result, I have three questions on the topic:

If MLMs incorporate fixed effects, should one consider using fixed effects anymore as a tool to make causal inferences?
If MLMs provide more detail on group or unit-specific intercepts and slopes, should users consider using standard regression adjustment anymore?
Where do MLMs fit into the broader causal inference toolkit. Given that regression is still used for estimation with most strategies (matching, DID, IV, RDD, etc.), can one use MLMs instead of the standard regression model for these contexts? Should one consider using MLMs?
Answer: I think this question is conflating a few distinct issues.
First of all, the terms "multilevel modeling," "random effects," and "fixed effects" are all used in different ways by different people. This post outlines FIVE different ways people define the difference between fixed and random effects.
Second, the most common use of MLM is for when you have observations "nested" at multiple levels (so students nested within schools, or observations nested within people in a longitudinal dataset). The question there is how you should deal with the higher level "units" (schools or people). One approach is to treat them as "fixed effects" (basically include a dummy variable for each "group"). On on hand, this  approach controls for ALL possible bias at the group level, so that's good. On the other hand, precisely because of that, it doesn't allow you to actually analyze the effect of any group level variable (like school size, or "race" in a longitudinal dataset). Treating the groups as "random effects" (allowing the intercept and/or one or more coefficient to vary randomly at the group level) allows you to control for other group level variables (and to do various other cool things like empirical Bayes estimation of group level characteristics), but also opens you up to group level bias if you haven't controlled for all of the important group level factors (which is always the case to some extent).
So in a nutshell, that's the trade off between fixed and random effects for using MLM to analyzed clustered data. How you navigate that trade off depends on your research question and how the data are set up.
Now, as you note, some Bayesians (like Andrew Gelman and perhaps also McElreaths) advocate using MLM (the "random effects" approach) even when there is no "nesting" of data, because Bayesians see all model parameters as inherently "random." But this is a more complicated approach and, in my experience, isn't yet super common among day-to-day statisticians due to various philosophical and logistical issues.
Also, any time you run a normal OLS model and include dummy variables for race, you could also correctly say that you are including "fixed effects" for race....but people don't usually consider that "multilevel modeling."
What does all of this have to do with causal inference? Nothing and everything. Causal inference is really tough, and "running a regression model"  on observational data is generally regarded as a pretty suboptimal way to establish causality...although sometimes it's all we've got. The extent to which we can interpret the results of a model in causal terms depends both on the model specification and the underlying theory behind it. MLM is just one way of specifying models to deal with particular problems that might contribute to bias or error in our estimates of coefficients and/or standard errors. If deployed well MLM might make a causal interpretation of a particular coefficient in a particular model more defensible, or it might not. But like any kind of model specification MLM (either fixed or random effects) has no inherent power to make models results causally interpretable, any more than "including an interaction term" or "including a control for age," or any other way we might modify the specification of a model.
Answer: In causal inference, this is the question of conditional treatment effects
"Regression" simply describes the procedure of fitting predictions from a set of features to a target value. MLM is no less regression than OLS, so there is no dichotomy. MLM proposes to use dummy variables for group memberships that can be used for group-specific intercepts or in interaction terms with other variables. These variables are predictors as much as any other, and how they should be included in causal inference depends on the directed acyclic graph assumed to describe the data generating process.
OLS. Assume a student's effort $X$ causes their test performance $Y$, but is confounded by the classroom $C$ they are in. One could use $C$ as a control variable such that $Y_i \sim \beta_1 X_i + \beta_2 C_i$.
MLM. Alternatively, one could use a MLM approach. Let $Y_{ij}$ be student $i$ in class $j$. We can then model student performances as $Y_{ij} \sim \beta_{j} X_{ij}$ where $\beta_j$ is the slope for classroom $j$.
In this case, instead of assuming that classroom $C$ confounds a universal causal relationship, the MLM approach models a classroom-specific slope. The underlying causal model is that the classroom variable $C$ interacts with the causal effect of student effort $X$ on performances $Y$.

In causal inference: CATE vs. ATE
The idea that a causal effect may be heterogeneous across different groups is well known in the causal inference literature. The primary estimand used to capture this concept is the "conditional average treatment effect" (CATE), which contrasts with the "average treatment effect" (ATE) that is the standard estimand for causal effects. Estimating the CATE is very similar to MLM. The idea is to estimate a causal effect conditional on other features, which can be understood as estimating the slope within subgroups in a linear model. Thus, what MLM is to OLS in statistical inference, CATE is to ATE in causal inference. Note that estimating the CATE poses a lot of additional difficulties compared to estimating the ATE, which complicates its application.
Comment: The CATE/ATE comparison is very useful. Although, it then leaves me with questions of the comparative advantage for modeling heterogenous treatment effects using a MLM instead of a standard OLS or some GLM model with an interaction term.


Remove Rendering from Sitecore Item

Question: I have  to remove all instance of a rendering by rendering id. I tried below code but its not working.
LayoutField layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);
LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());

//Create a RenderingDefinition and add the reference of sublayout or rendering
RenderingDefinition renderingDefinition = new RenderingDefinition();
renderingDefinition.ItemID = sublayoutId;

var d = layoutDefinition.GetDevice(deviceDefinition.ID.ToString());
d.Renderings.Remove(renderingDefinition);

item.Editing.BeginEdit();
layoutField.Value = layoutDefinition.ToXml();
item.Editing.EndEdit();

I have referred:

http://blog.ryanbailey.co.nz/2016/08/sitecore-remove-renderings-or.html
Programmatically removing sublayouts in Sitecore
Comment: At what moment are you removing the rendering? Is it a one off execution?
Answer: Try code below. I haven't tested it but instead of creating a RenderingDefinition object and removing it from the list (which won't work cause it's not the same instance of the object), it filters the existing array of renderings comparing ItemId property:
LayoutField layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);
LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());

var d = layoutDefinition.GetDevice(deviceDefinition.ID.ToString());

IEnumerable<RenderingDefinition> renderingsArray = d.Renderings.ToArray().Cast<RenderingDefinition>();
d.Renderings = new ArrayList(renderingsArray.Where(r => r.ItemID != sublayoutId).ToList());

item.Editing.BeginEdit();
layoutField.Value = layoutDefinition.ToXml();
item.Editing.EndEdit();

Comment: Getting error "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'int'"    in line # 6
Comment: I've updated the answer to use `IEnumerable` explicitly instead of using `var`. Try now.

Remove Rendering from Sitecore Item


Extrair dados do SAP através do Excel

Question: Olá!

Estou tentando integrar o Excel com o SAP via VBA. Gostaria de rodar a transação "MB51" com alguns parâmetros como data, depósito e movimento e trazer os dados obtidos para a planilha do Excel via VBA.

Tenho tentado realizar esta tarefa com base no seguinte código:
Sub SAP()

Dim sap As Object
Dim conn As Object

Set sap = CreateObject("SAP.Functions")
Set conn = sap.Connection
conn.System = "S0P"
conn.Client = ""
conn.User = ""
conn.Password = ""
conn.Language = "PT"

If conn.logon(0, False) <> True Then
    MsgBox "Logon to the SAP system is not possible", vbOKOnly, "Comment"
End If

Set SapGuiAuto = GetObject("SAPGUI")          'Utiliza o objeto da interface gráfica do SAP
Set SAPApp = SapGuiAuto.GetScriptingEngine    'Conecta ao SAP que está rodando no momento
Set SAPCon = SAPApp.Children(0)               'Encontra o primeiro sistema que está conectado
Set session = SAPCon.Children(0)              'Encontra a primeira sessão (janela) dessa conexão

If Not IsObject(Application) Then
   Set SapGuiAuto = GetObject("SAPGUI")
End If
If Not IsObject(Connection) Then
End If
If Not IsObject(session) Then
End If
If IsObject(WScript) Then
   WScript.ConnectObject session, "on"
   WScript.ConnectObject Application, "on"
End If
session.findById("wnd[0]").maximize

Dim objExcel
Dim objSheet, intRow, aux, Log
Set objExcel = GetObject(, "Excel.Application")
Set objSheet = objExcel.ActiveWorkbook.ActiveSheet

DataInicial = Range("H2")
DataFinal = Range("H3")

session.findById("wnd[0]/tbar[0]/okcd").Text = "/NMB51"

End Sub

Adicionei a referência "SAP GUI Scripiting API" no Excel mas sempre que o código chega na linha:
Set SapGuiAuto = GetObject("SAPGUI")

Recebo a mensagem de erro

Alguém pode me ajudar ou indicar o caminho?
Answer: Tente excluir essa linha,
Set SapGuiAuto = GetObject("SAPGUI")          'Utiliza o objeto da interface gráfica do SAP

Sub testar()

Dim objExcel
Dim objSheet, intRow, aux, Log
Set objExcel = GetObject(, "Excel.Application")
Set objSheet = objExcel.ActiveWorkbook.ActiveSheet

    If Not IsObject(Applicationa) Then
       Set SapGuiAuto = GetObject("SAPGUI")
       Set Applicationa = SapGuiAuto.GetScriptingEngine
    End If

    If Not IsObject(Connection) Then
       Set Connection = Applicationa.Children(0)
    End If

    If Not IsObject(session) Then
       Set session = Connection.Children(0)
    End If

    If IsObject(WScript) Then

       WScript.ConnectObject session, "on"
       WScript.ConnectObject Application, "on"

    End If

session.findById("wnd[0]").maximize

DataInicial = Range("H2")
DataFinal = Range("H3")

session.findById("wnd[0]/tbar[0]/okcd").Text = "/NMB51"

End Sub

Também e necessário ativar a opção SAP GUI Configuration
Answer: Faça a conexão do Excel - SAP através do gravador de script. Deppois de gravar todo o script, é só substituir as quatorze linhas iniciais pela linha
Set session = GetObject("SAPGUI").GetScriptingEngine.Children(0).Children(0)
Isso conecta o Excel ao SAP

Extrair dados do SAP através do Excel


How to make json array parsing work on the server side

Question: I have an action on my server side:
public void Action(Container container)
{
}

where container is:
public class Container
{
   public string[] Arr;
}

From the client side, I'm invoking this action in the way below:
$.post("Controller/Action", { Arr: "abc" }, null, "json");

After this, the Arr in container contains one element "abc".
But, while invoking action the way below:
$.post("Controller/Action", { Arr: ["abc", "def"] }, null, "json");

the json array is not deserializing on the server side. The Arr in container is NULL.
How to make this simple thing work ?
Regards
Answer: If you are using jquery 1.4 try this:
$.ajax({
    url: 'Controller/Action',
    type: 'post',
    data: { Arr: [ 'abc', 'def' ] },
    traditional: true,
    dataType: 'json'
});

Notice the traditional flag.
Or if you prefer to continue using $.post():
$.post(
    'Controller/Action',
    $.param({ Arr: [ 'abc', 'def'] }, true),
    null,
    'json'
);


ERROR: Error installing rails zeitwerk requires Ruby version >= 2.4.4

Question: I recently changed my laptop and tried installing rails with
gem install rails

and I got this error
ERROR:  Error installing rails:
    zeitwerk requires Ruby version >= 2.4.4.

I have installed ruby version 2.4.4, 2.5.7, and 2.6.5 and I'm still getting the same error.
Any pointers how to resolve this will be greatly appreciated. thanks
Comment: How did you install Ruby, and how do you know what versions of Ruby you have, and how do you know that you're using Ruby >= 2.4.4 when you try to install Rails?
Comment: I installed ruby using  ```rbenv install  2.5.7 ``` and switched to 2.5.7 with ```rbenv global 2.5.7```
Comment: Did you `rbenv rehash`? https://github.com/rbenv/rbenv#rbenv-rehash What does `ruby -v` return?
Comment: yes I did ```rbenv rehash```  and ```ruby  -v``` returns ```ruby 2.5.7p206 (2019-10-01 revision 67816) [x86_64-darwin18]```.
Comment: I had the same error, try:
`rvm install 2.4.4` and then `rvm use 2.4.4`
Comment: @AyoguChibueze, did you solve this issue?
Comment: @codemick yes I uninstalled everything and started afresh. Just ensure all your gem are installed in one folder and the version manager you are using has access to it.
Answer: In directory wanted use rvm use ruby-2.5.7 command line to force the usage of this specific version of ruby and after gem install rails. Just tryed minutes ago and works fine
Answer: Another workaround for this specific issue if you don't care about having a newer version of Ruby (and rails), you can just install the most recent compatible version of rails with your version of ruby, a similar example with sprockets which requires ruby v2.5.0 solved by installing an older version of rails v4.1.16 looking at the dependencies graph:
sudo gem install rails -v 4.1.16


Dúvida teórica sobre while e indentação

Question: count = 0
while (count < 10):
    # Ponto A
    print ("Olá...", count)
    count =  count + 1
    # Ponto B
# Ponto C

Por que

count < 10 é sempre true no ponto B.

não é verdadeiro se o "Ponto B" pertence a mesma indentação do "Ponto A" dentro do while?
Outra pergunta:
i = 6
while (i > 0):
    i = i - 3
    print (i)

Por que a saída é 3 e 0 e não somente 3?
Muito obrigada!
Answer: Vc perguntou por que no código abaixo:
(1) i = 6
(2) while (i > 0):
(3)   i = i - 3;
(4)   print (i)

A saída é 3 e 0 e não somente 3. A resposta é simples, mas requer que você considere como o Python interpreta cada linha de comando. Pra facilitar, eu enumerei as linhas no código acima, ok?
A primeira linha executada é (1). Ela simplesmente atribui o valor 6 à variável i. A segunda linha executada é (2). Ela verifica se i > 0, e como i vale 6 (neste momento), isso é verdadeiro e o Python permite que a execução entre no laço. Assim, a próxima linha executada é (3), que faz com que i receba i - 3. Como nesse momento i vale 6, o resultado é i = 6 - 3, logo i = 3. Esse valor é o impresso na próxima linha, como esperado.
A execução então retorna à linha (2). O valor atual de i é 3 (que aliás, foi o último impresso). Como i > 0 (porque 3 > 0) é verdadeiro, o processamento entra novamente no laço. A linha (3) faz a subtração novamente, fazendo com que i passe a ter o valor 0 (já que faz i = 3 - 3). A linha (4) então imprime o valor atual de i, que é 0.
Finalmente a execução retorna à linha (2), mas dessa vez o processamento não entra no laço pois a condição não é mais verdadeira.
Experimente executar esse código:
i = 6
while True:
  i = i - 3
  if(i > 0):
    print (i)
  else:
    break

Observe que nesse código a condição do laço é de fato sempre verdadeira (afinal, é fixo True), e a condição correta (a sua condição original) foi movida pra dentro do laço em um if. Analise com esse novo código como o computador processa linha a linha de forma sequencial, acompanhando o valor atual da variável em cada passo (esse procedimento costuma - ou costumava - se chamar "teste de mesa"). Vai te ajudar a entender como a "lógica" influencia na resolução de problemas. :)
Answer:
count < 10 é sempre true no ponto B.

Na verdade não é. No ponto B o count será o count anterior +1. Seu máximo será 9, pois o while pára se o count for igual a 10. Teste seu script.
i = 6
while (i > 0):
  i = i - 3;
  print (i)

Primeiro: A identação utilizada está fora das recomendações. Dentro de um loop, função, classe ou o que seja, o recomendado e comumente utilizado são 4 espaços. Isso é importante para manter uma padronização e uma boa organização visual do código, assim se demais pessoas forem utilizar o código, estarão familiarizados com a formatação.
Segundo: O ponto e vírgula é desnecessário.
Terceiro e resposta da pergunta: Pense como o script:
O ientra no loop como 6, se torna 3 e é impresso. O loop recomeça com o i como 3, se torna 0 e é impresso novamente. Só então que o i é testado novamente (dessa vez sendo 0) e não entra no loop.
Comment: Realmente, errei em dizer que está errado. Deveria ter dito que está fora das recomendações.

Dúvida teórica sobre while e indentação


iTunes for iPhone in a corporate environment

Question: We cannot obtain iPhones in my work environment due to "the whole music management problem on servers."  Our management is concerned about users putting MP3 files on their laptops or on a server filesystem. After reading Apple's iPhone Enterprise Deployment Guide, it seems the only portions of ITunes that can be restricted are the same things the "Parental Controls" choices give you.
Is there any alternative here? Any better means to support the iPhone in a corporate environment that may not require ITunes?
Answer: We have iPhones deployed to 90+% of our employees.  We allowed users to use iTunes for music before they had iPhones, and we continue to allow them to use it now.
To relieve the burden of storing and backing up their music collection on our networked filesystems, we simply redirect the iTunes library to their local machine's hard drive with no encryption or backup.  On Mac OS X workstations, we use MCX Redirection to specify this.  On linux you can do it manually with symlinks and some scripting.  I'm sure there's a way to do it on Windows fairly easily too.
Answer: You really only need iTunes for activating the iPhone, but I'm guessing the concern is what will prevent the users from attaching their iPhone to iTunes at home an loading it up with music. If you block iTunes (or more so the access to iTunes) at the office, there would probably be little risk of a user saving music on their workstation or file servers (there are lots of tools for filtering media files on file servers). Of course there are other issues that can arise from someone installing hardcore rap (or Brian Adams) music on their (actually a corporate asset) iPhone, and possible offending other employees.
I'm really not sure what options you have, as I'm not aware of there being any security policies (I don't believe iPhone has that capability) that you can apply to an iPhone (like a Blackberry/BES solutions).  Perhaps Apple or a third party vendor will put something together, but then I'm not sure if that's really a direction Apple wants to go with the iPhone.
I would pursue a well written usage policy with your IT/Corporate security.  It's not perfect, but at least you can get an employee to agree (in writing) not to load the phone up with music or unsupported apps under penalty of termination.
Just my 2 cents.
Answer: There's an Apple-provided iPhone enterprise configuration utility described and available here, this seems to provide a lot of options for configuring your iPhones for enterprise, although the documentation doesn't mention anything about being able to do exactly what you want.
The iTunes restrictions which are apparently available described in this PDF, I tried to copy-and-paste them here but the PDF messed the text up...
Answer: We got iPhones for our users this past summer after a lot of debate.. in the end we were told by the President that that is what we were getting and to make it work :)  We don't allow iTunes on the network (outside of IT for updating purposes) - it's blocked by our webfilter, plus the users don't have admin rights on their machines, so they can't install it. I tried the iPhone policy that Apple provided, but it didn't always apply the same across the board, so we ditched it and just use the built in exchange mobile policy for password and screen lock enforcement and it works well. The users have a general list of do and don't installs (ie: you can't install bump, or any other apps that might allow the contacts to be removed from the phone), and our general use policy which covers internet use, etc., applies to the phones. Each time there is an update to the phone (which seems to be monthly thus far) the phones are turned in for updates as well as audits for things we don't want on them. If something is there, it's removed and the user is warned, eventually they will either lose the right to the phone or be dismissed. So far, it's been working well, no problems or incidences yet. HTH...


Make icon searchable

Question: I have font awesome spans however I am using data tables which have a search bar.
Here is my code:

<span class='gray_star' id='<?= $p->id?>' >

Is there a way that if i type "red" in my search bar, the red star will display and if I type green, green star with show and etc?
Comment: You could use the onChange event to listen for your input to change. Then use a switch to determine the input. Then you can use the removeClass and addClass on your
Answer: Something like this?

$(function() {

  $("#x").on("input",function() {
    var val = this.value;
    if (["red","yellow","green"].indexOf(val) !=-1) {
      $(".star").hide();
      $("."+val+"_star").show();
    }
    else {
      $(".star").show();
    }
  })
})
.red_star { color:red; }
.yellow_star { color:yellow; }
.green_star { color:green;  }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<input id="x" type="text" />

<span class='gray_star' id='<?= $p->id?>' >

Comment: yes but i dont want the circles to hide at first, i want them all to display then if i use the search, it filters the color i searched on

Make icon searchable


Access callback parameters called by async

Question: I have a function that returns a callback containing some data, how can I run it with async and access the data when async completes?
Example:
var async = require('async');

function provisionServer(server, callback) {
  return callback('abcd');
}

getServerQueue(function (err, servers) {
  async.each(servers, provisionServer, function (err) {
    if (err)
      logger.error("[async provisionServer] " + err);
    else {
      console.log("How can I get the 'abcd' from the provisionServer callback?");
      async.each(servers, dequeueServer, function (err,result) {
      if (err)
        logger.error("[async dequeueServer] " + err);
      else {

      }
  });
});

Answer: Use async.map instead of async.each:
function provisionServer(server, callback) {
  return callback(null, 'abcd');
}

getServerQueue(function (err, servers) {
  async.map(servers, provisionServer, function (err, results) {
    if (err)
      logger.error("[async provisionServer] " + err);
    else {
      console.dir(results);
      async.each(servers, dequeueServer, function (err, result) {
      if (err)
        logger.error("[async dequeueServer] " + err);
      else {

      }
  });
});

Answer: There seems to be a little confusion around the two callbacks at play here.
Here is how it can be broken down:
var list_of_stuff = [1,2,3];
async.each(list_of_stuff, iterator_fn, error_fn);

The first param is the list of stuff you want iterated over. The second is the iterator function you want to call per item. Note that this function takes in as parameters the item of interest and a callback which that invocation of the iterator will use to signal completion, and looks like so:
function iterator_fn(item, iterator_callback) {...}

The next function passed in is the error_fn, and this is just a plain ol error handler:
function error_fn(error) {...}

Comment: Woah, my answer got cut off.. regardless - you can use async.parallel to return a list of results from the parallell run functions.


Algebraic sum of any number of irreducible fractions whose denominators are all co- prime, cannot be an integer

Question: Let there be two numbers: $\frac{a}{b}+\frac{c}{d}$, s.t. $(a,b)=(c,d)=(b,d)=1$.
The sum is assumed (for indirect, or contradiction approach) to be $k \in \mathbb {Z}$.
$$\frac{a}{b}+\frac{c}{d}=k $$
$$\Rightarrow ad+bc=kbd$$
$$>ad=kbd-cb \Rightarrow ad=b(kd-c), \text{not possible as  } b\nmid ad$$ $$>cb=kbd-ad \Rightarrow cb=d(kb-a), \text{not possible as  } d\nmid bc$$
Hence proved.
How to extend (hopefully, the only approach would by induction) for sum of more than two fractions?

Also, have another question that concerns with providing a proof using better symbolic logic ( don't know how to state better), the derivation of $(a,c)=1$, by using the three equalities ($(a,b)=(c,d)=(b,d)=1$).
Any way to prove - or is there no way to prove as $(a,c)$ can go both ways; i.e. $=1, \ne 1$, as @MooS's  comment to his answer shows.
My incomplete proof attempt is:
Also, stated using Bezout's identity:
$$ax + by =1 , cx + dy =1, bx + dy =1, \exists x,y \in \mathbb{Z} $$
(Have taken $x,y$ to mean dummy variables, and may not actually be the same for all three equalities).
Comment: It might be nitpicking, but the assertion is false: $\frac{1}{1}+\frac{1}{1}=2$
Comment: I hope it would work for $a,b,c,d \ne 1$.
Comment: You only need one of the fractions to be an "actual" fraction. The numerators are not relevant.
Comment: Why only one? Also, why numerators are not relevant? Do you mean that the numerators can be simply $1$?
Answer: This would be my proof for the case of two summands:
Actually one only needs to assume that $(b,d)=1$ and that one of the fractions is not an integer, w.l.o.g assume $\frac{a}{b} \notin \mathbb Z$.
If $\frac{a}{b}+\frac{c}{d} \in \mathbb Z$, we have $ad+bc = 0 \mod{bd}$.
Reduce this modulo $b$ to get $ad = 0 \mod b$. Since $d$ is co-prime to $b$, we obtain $a = 0 \mod b$, a contradiction to $\frac{a}{b} \notin \mathbb Z$.

For more summands (assuming the denominators are pairwise co-prime and one of the fractions is not an integer), the induction step is actually trivial, because if you take the sum of two fractions, the common denominator will still be co-prime to all other denominators.
Comment: Why do you want to prove that? It is not needed and more importantly it just plain wrong: $\frac{2}{3}+\frac{2}{5}$ satisfies all your assumptions, but the numerators are not co-prime.
Comment: Please elaborate the line : "Reduce this module ..."
Comment: Typo. Reduce this modulo.
Comment: Any help regarding the second proof for proving $(a,c) = 1$.
Comment: Thanks a ton for that. I hope a hint to prove this 'new' fact, i.e., $(a,b)=(c,d)=(b,d)=1, \text{ and } \frac{a}{b} + \frac{c}{d} \ne \text { any integer}$, then $(a,c)$ can have any value. I hope it cannot be proven, as the value of $(a,c)$ can be both ways, i.e. $=1$, or $\ne 1$. If you could give some insight into such proofs, I would be highly thankful.
Comment: So you are telling me you cannot use my example in the comment above to produce examples for any value of $(a,c)$? This should be obvious.
Comment: Does this obviousness (if you have interpreted me correctly) has any sort of proof in maths for both yes and no answers, i.e. $(a,c)$ can be any value $=1, \ne 1$?
Comment: Let $e$ be any value you wish and let $p,q$ be two primes co-prime to $d$. $e/p + e/q$ works.
Comment: But, why not just $b,d$ with $(b,d)=1$.
Comment: We have $(b,d)=1$ in my example. I do not see your problem to be honest.
Comment: If you have another question, you should take some time to carefully formulate it and ask a new question. No more comments here.
Comment: Confused, and need source to prepare next question better. So, final comment for a good source, which has details.


Time Complexity of Russian Peasant Algorithm

Question: I'm trying to figure out the time complexity of this:
#include <iostream>
using namespace std;
unsigned int russianPeasant(unsigned int a, unsigned int b)
{
    int result = 0;
    while (b > 0)
    {
        if (b & 1)
            result = result + a;
        a = a << 1;
        b = b >> 1;
    }
    return result;
}
int main()
{
    unsigned int a,b;
    cout << "Enter two numbers to multiply" << endl;
    cin >> a >> b;
    cout << "product: "<< russianPeasant(a, b) << endl;
    return 0;
}

(from here)
I'm seeing on some websites it's O(logn), but I know the fastest time complexity for integer multiplication is O(nlogn). What is the time complexity and how does it compare to other multiplication algorithms?
Answer: There are at least two important points to consider when comparing claims about time complexity:

There is bit complexity and arithmetic complexity. The choice has an impact on how we assess the complexity of the addition and bit shift operations that occur in the code. When assessing code that uses fixed sized integers, like unsigned int, then arithmetic complexity is the right choice. But if we take a more theoretical approach where numbers have no limited range, then bit complexity is the choice to make.

We need to agree on what  means. When you recall that "...the fastest time complexity for integer multiplication is O(nlogn)" then be aware that here  refers to the number of digits of the operands. While those that state a time complexity of O(log) for the code you presented, define  as the value of the input, i.e. + (or max(, )).

If we would define  as the number of digits in  and , then the complexity becomes O(). If we would not define the input with the unsigned int data type, but some BigInteger data type (which allows for an arbitrary number of digits in the input numbers), the addition and shift operations no longer have a constant time (bit) complexity, but O().
So now we are on the same terms and can really compare:
With  defined as the number of digits in the input numbers, and support for arbitrary large numbers, the presented code has a O(²) time complexity.
Answer: Here n is the size in bits of the parameters.
If it is an algorithm (means that int type is not bounded in size). You pass O(n) times in the while loop, but inside the loop there is an addition which takes O(n) times. Thus O(n^2) at the end. This provided that shifting is in constant time (but a clever data structure can lead to it).
But as we know the size of ints, all of this can be considered as constant time.


Construct a polynomial of least degree possible with given information: real roots $-1$ (With multiplicity 2 and 1) and $(2,f(2))=(2,4)$

Question: A am to construct a polynomial with given information:
real roots $-1$ (With multiplicity 2 and 1) and $(2,f(2))=(2,4)$
The answer is: $f(x)=\frac{4}{9}(x^3+x^2-x-1)$
This is an extension exercise at the end of a book. In this particular case I don't even know how to get started or how to approach, I cannot see the bigger picture. For this reason I have not shown steps already taken or what I have tried already.
How can I arrive at $f(x)=\frac{4}{9}(x^3+x^2-x-1)$? Granular, baby steps greatly appreciated where possible.
Comment: You say "with multiplicity $2$ ande $1$", which suggests **two** roots are given. Did you mean the real roots to be $\pm 1$? Because by inspection both $+1$ and $-1$ are roots of the answer. In that case, the minimal polynomial is necessarily of the form $$f(x) = C(x-r_1)^{m_1}(x-r_2)^{m_2}$$ where the root $r_k$ has multiplicity $m_k$. You just have to find $C$ so that $f(2) = 4$.
Comment: Did you mean real roots $-1$ (with multiplicity $2$) and $1$?  In that case, $f(x) = a(x + 1)^2(x - 1)$, so $f(2) = a(2 + 1)^2(2 - 1) = 9a = 4 \implies a = 4/9$, so $f(x) = \frac{4}{9}(x + 1)^2(x - 1)$.
Answer: Here is how to find a cubic polynomial. Let $$f(x)=A(x+1)^2(x+d)$$
where $d \ne 1$, $A \ne 0$.
When $x=2$, we have $4=9A(2+d)$
$$d=\frac{4}{9A}-2$$
$$f(x) = A(x+1)^2(x+\frac{4}{9A}-2)$$
Try to pick a suitable value of $A$ to get what you want.

Actually if we consider $f(x)=B(x+1)^2$, when $x=2$, we have $4=9B$ satisfy the condition unless I misinterpreted your question.
If the question says there is a root with multiplicity $2$ and another root with multiplicity $1$, then the polynomial is at least cubic.


Regex para não escapar apenas < > =?

Question: Atualmente tenho o seguinte regex:
"/([^\w\.\,]+\s*)/"

Ele escapa, letras, números, vírgulas e pontos seguidos ou não de espaço. Como faço para deixar ele escapar tudo, exceto os caracteres: < > = !
Comment: Vc quer que case somente os caracteres `< > = !` isso?
Comment: Sim, apenas esses caracteres, seguidos ou não de espaço
Answer: Tente isso, fará com que ele aceite somente os caracteres < > ! =:
/[<>=!]/g

Exemplo: https://regex101.com/r/eF5pG8/1
Já isso fará com que ele aceite tudo exceto os caracteres < > ! =:
/[^<>=!]/g

Exemplo: https://regex101.com/r/eF5pG8/3
Comment: Parênteses e `|` dentro de colchetes são tomados literalmente, não como sintaxe especial. Essa regex também não aceita `(`, `|` nem `)`. Se você quer negar um conjunto de caracteres, faça simplesmente `/[^<>=!]/g`. P.S. E a do comentário do @LeonardoVIlarinho aceita `(`, `|` e `)` quando não devia aceitar.
Comment: @mgibsonbr, você tem rezão, não tinha me atentado a isso. Editarei a resposta com sua sugestão. Obrigado.
Comment: Funcionou, assim também (que fiz de acordo com sua resposta anterior) `[(<|>|=|!)]`.

Regex para não escapar apenas < > =?


Facebook iOS Mobile Web JS SDK Error

Question: We already have Facebook working on our main desktop app without an issue. When I added the same setup code to our mobile site I received an error from the JavaScript SDK:
Received message of type object from https://s-static.ak.facebook.com, expected a string
Then, I changed the setup code to an exact replica from here: https://developers.facebook.com/docs/guides/mobile/web/ and received the exact same message.
This error only shows when the user-agent is iOS or Android in Chrome Developer Tools or in the iOS Simulator. When it's running from the desktop, we aren't seeing this error.
Any idea what's going on here?
Thanks :)
Answer: With all due respect, I believe that bokonic's answer is missing the point. The immediate reason of the message you're receiving is most likely javascript postMessage method. It is used to communicate your website with an object returned by window.open or an iframe's embedded website.
window.parent.postMessage(message, targetOrigin);

You might want to have a look at this article to see how it works.
According to MDN reference first argument of the postMessage method can be of any type. Still, Prior to Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), the message parameter must be a string.
I tested the method on Chrome 28.0.1500.72 (latest version when writing this answer) and it works fine when passing an object but still throws the warning message to the console. I believe that facebook feels uncomfortable with passing some rich data as a string so they pass it as an object and simply doesn't care about the warning. Or, since there is a workaround (e.g. JSON.stringify), they have a bug they don't know about.
Comment: seems correct but actually the warning message is coming from within the facebook sdk ITSELF—its not a part of the browser or anything, its part of the facebook sdk. (this can trivially be confirmed by a breakpoint on the source of the console output) this is really annoying if your app happens to use postMessage for anything, because facebook will happily spam the console with a million "warning" messages for a bounty of events not intended for it.
Comment: I think this is more correct answer. The warning happening because of the window.postMessage method.I ended up here with same warning, but not because of emulator. I used an extra postMessage and FB sdk is listening for the message too & throwing error since I was sending an object!
Answer: I had the same error. This isn't necessarily the reason you're getting it, but I ended up looking at the packets being received by my iphone simulator, and here's the error from s-statick.ak:
[truncated] Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings.  It must match the Website URL or Canvas URL, or the domain must be a subdomain of one o

For me, the error is that on my device(s), I'm accessing the site through an ip address (192.168.xx etc) and on local development I have hosts routing localhost to a url that is in my facebook app config... so the IP isn't configured for the app.
Facebook won't let me use an IP address, so it seems like the only option is a test deploy or a DNS server. Hope this helps you out.
Comment: This makes perfect sense and something I should have considered. Thanks for the helpful answer.

Facebook iOS Mobile Web JS SDK Error


Non trivial algebraic places

Question: Zariski and Samuel II states if a field K over k has positive trans. degree an algebraic place of K/k exists. (Ch. VI, The 5, corr. 2). Could someone supply a non trivial example of such a place? Thanks.
Answer: $$\mathcal{P}(f(x))=f(0)$$ is an rational place on $k(x)$.

Non trivial algebraic places


Area enclosed by general equation of second degree

Question: What is the area of the figure enclosed by the curve: $5x^2+6xy+2y^2+7x+6y+6=0$.
My attempt: $2y^2+6(x+1)x+5x^2+7x+6=0$.
$\displaystyle y=\frac{-6(x+1)\pm\sqrt{36(x+1)^2-4(5x^2+7x+6)}}{4}$
$\displaystyle y =\frac{-3(x+1)\pm \sqrt{4x^2+11x+3}}{2}$
How do I solve it?
Comment: [Change coordinates like this](https://en.wikipedia.org/wiki/Conic_section#Conversion_to_canonical_form)
Comment: This is an ellipse.
Answer: Factorize the given expression from the roots you derived and plot the equation for confirmation.
Study the graph. Recognize that the blue ellipse with axes parallel to axes has been shifted up by pushing up thin slices to form the given oblique ellipse leaving area unchanged. This follows geometrization of area/volume concepts.
Accordingly Area $ = \frac{\pi}{4} .d_1. d_2  = \frac{\pi}{4} .1 .2 = \pi/2$
Answer: As you integrate between two curves $y_+(x)$ and $y_-(x)$, you can just consider $y_+(x)-y_-(x)$, which is (fixing your calculation errors)
$$\frac{\sqrt{(6x+6)^2-4\cdot2\cdot(5x^2+7x+6)}}{2}=\sqrt{-x^2+4x-3}=\sqrt{1-(x-2)^2},$$
by completing the square.
This is just the area of a half unit circle,
$$\frac{\pi}2.$$

For completeness,
$$I:=\int_1^3\sqrt{1-(x-2)^2}dx=\int_{-1}^1\sqrt{1-x^2}dx=\left.x\sqrt{1-x^2}\right|_{-1}^1+\int_{-1}^1\frac{x^2}{\sqrt{1-x^2}}dx
\\=\int_{-1}^1\frac{1-(1-x^2)}{\sqrt{1-x^2}}dx=\left.\arcsin x\right|_{-1}^1-I$$
justifies the claim.
Answer: I get that ellipse major semi-axis is
$$a=\frac{3+\sqrt5}{2\sqrt2}$$
minor semi-axis is
$$b=\frac{3-\sqrt5}{2\sqrt2}$$
Area is
$$S=\pi ab=\pi\cdot\frac{3+\sqrt5}{2\sqrt2}\cdot\frac{3-\sqrt5}{2\sqrt2}=\frac{\pi}{2}$$
Comment: please explain How you get


Euler angles vs. Quaternions - problems caused by the tension between internal storage and presentation to the user?

Question: Quaternions are arguably an appropriate choice for representing object rotations internally. They are simple and efficient to interpolate and represent a single orientation unambiguously.
However, presenting quaternions in the user interface is generally inappropriate - Euler angles are generally much more familiar to users, and their values are a little more intuitive and predictable.
Euler angles suffer from being complicated at the code level - they require that an order of rotation is stored, and composing a practical orientation (be it matrix or quaternion) using this order and associated angles is cumbersome, to say the least.
Reliable interpolations are most conveniently performed using quaternion representation - so does this mean we must convert constantly between an Euler representation and a quaternion representation? Is this feasible in terms of performance?
Can we store the orientations as quaternions and convert them only for displayed to the user? This may not be possible because for any given orientation there is exactly one quaternion representation but many Euler representations. How do we 'pick' the Euler representation that corresponds to the one that originally defined that orientation? It seems like an impossible task - we've effectively lost information when converting to a quaternion.
Could we store as Euler angles and then convert to quaternions as needed? This probably isn't scalable - conversion from an Euler angle to a quaternion, interpolation, and then conversion back again is likely to be relatively expensive code.
Could we simply store both representations and use the most appropriate for any given situation? A large cost in terms of memory (imagine animation curves for a skeleton with around sixty bones) and keeping these values synchronised could be expensive, or at least cumbersome.
Has anybody seen, used or though up any clever solution to this problem? Surely the three options above aren't out only ones? Are there any other problem domains similar to this that have been solved?
Answer: I am an aerospace engineer; I have been using quaternions for spacecraft attitude control and navigation for going on three decades.  Here are some thoughts on your situation:

Performing any kind of process that changes orientation with Euler angles is verging on impossible.  Euler angles suffer from singularities - angles will instantaneously change by up to 180 degrees as other angles go through the singularity; Euler angles are virtually impossible to use for sequential rotations.  Quaternions do not suffer from either of these problems
There are 12 different possible Euler angle rotation sequences - XYZ, XYX, XZY, etc.  There is no one "simplest" or "right" set of Euler angles.  To derive a set of Euler angles, you must know which rotation sequence you are using and stick to it.
I suggest you perform all storage and rotation operations with quaternions and only convert a quaternion to Euler angles when output is required.  When you do this, you must define which Euler rotation sequence you are using.

I have algorithms for all these operations and many more: quaternions to/from Euler angles of any rotation sequence to/from rotation matrices (direction cosine matrices), quaternion interpolation matching position, rate, etc. at end or intermediate points, rigid and flexible body dynamics and kinematics using quaternions.
Please contact me if I can be of assistance at
email@example.com
Comment: Accepting this answer because it appears to have the most votes. However, 1) Yeah, unfortunately I'm working in the animation domain and artists expect to have Euler angles 2) Yep, and again animators expect to be able to set the rotation order on their bones arbitrarily so I have to support all permutations 3) That is more or less what I am doing in the end.
Answer: You asked this question 12 years ago and I am telling you the answer you checked is completely wrong. That guy doesn't know what he's talking about.
If you restrict the domain of Euler Angles (let's go with yaw pitch roll) to -180 to 180, every single quaternion has at least TWO sets of YPRs (yaw pitch roll) that represents it. There is NO WAY to know which YPR is correct without additional assumptions.
The best solution is to ALWAYS store YPRs internally then when you need to do a computation, convert the YPR to a quaternion. That is the proper answer.
Doing computations with quaternions will again yield multiple possible solutions however because you only stored the YPR internally you will be able to use the original YPR to help you find correct YPR that was derived from the Quaternion.
That guys 3 decades of experience doesn't mean jack. Most likely he's dealing with a restricted system. If 2 axises or more of rotation are restricted to only be able to sweep 180 degrees (-90 to 90 in this case), THEN and only THEN will there be a single YPR represented for every quaternion. Because the guy is an aerospace engineer I am pretty sure that's what he's dealing with since physical gimbals usually have restricted angles of rotation.
Comment: Assuming you don't need the exact YPR values but only the resulting rotation: why would you introduce ambiguity/complexity(assuming YPR/specifying YPR at every step) into your system in addition to a greater computational load? In most applications you need the resulting orientation so the exact YPR values do not matter.  Also converting Euler angles into different coordinate systems as required with robotics does not sound fun.
Comment: @baumflaum quaternions are a fantasy value like imaginary numbers. If I want to present a real rotation to a physical gimbal, I have to give that gimbal a YPR. Each motor on the gimbal needs to know how many radians to turn. A quaternion is useless in the physical world. A physical gimbal restricted to -180 to 180 on all axis has two YPRs for each quaternion. This is not a math trick.
Comment: @baumflaum The physical gimbal itself for each orientation the motors have a total of 2 sets or YPR rotations that can achieve the identical orientation in space. The is important because whatever rotational configuration the gimbal is in it's relative thresholds to it's max range of motion is different. Quaternions mask this duality in the physical gimbal. If you restrict pitch from -90 to 90 for ypr, this duality no longer exists.
Comment: @baumflaum The robotics systems you've dealt with have likely did this... If this is done then yes... There's a one to one mapping from positive unit quaternions to restricted YPRs and a library can abstract away the need to touch YPR (although ypr is still the command sent to the motors) Check your robot gimbals. One axis must be specially restricted to a 180 degree sweep, while the others are open to 360 degree sweeps.
Comment: Sorry to say but this is completely wrong. Your gimbal is just your specific implementation of the orientation control. You should convert from and to that specific implementation only at the interface level. The fact that any orientation can be represented by one canonical Quaternion but multiple YPRs is a problem of Euler angles, not a problem of Quaternions (they are in fact the solution to that problem, exactly as with gimbal lock).
Comment: You're not understanding the concept. Multiple YPR configurations happen in REAL LIFE. That means a physical gimbal can point at a SINGLE orientation, but the rotational mechanisms can HAVE TWO DIFFERENT CONFIGURATIONS to achieve that. This configuration information is often needed as the range of motion is effected depending on the configuration of the rotational mechanisms. (20, 20, 0) = (300, 160, 180). In the preceding example the 2nd equivalent euler angle is nearer to the end of the range of motion. Quaternions unfortunately, HIDE this information.
Comment: @matthias_buehlmann forgot to tag you above.

Anyway it's very easy to see the problem. Imagine a gimbal in real life that takes a quaternion as input and rotates it's motors to achieve the orientation picked by the input quaternion. Let's say you input a quaternion equivalent to the euler angles: (20, 20, 0) OR (300, 160, 180).

Which euler angle does the gimbal pick? It's ambiguous. Because the quaternion doesn't hold enough information.
Answer: I am a fan of quaternions.  In order to make them work, could you reconsider your presentation to the user?  Instead of presenting the rotation to the user as a series of Euler angles in text form, you might instead pick some simple 3D object and apply the quaternion rotation to the object to display visually the rotation in effect.
Comment: If only :) But I'd be surprised if you could get away with it in practice.

As far as I'm aware, normal workflow for a 3D artist will almost always involving knowing the actual numbers - so while you might provide them Max/Maya style rotation gadgets, at some point they're going to want that rotation to be _exactly_ 30 degrees, or at least see exactly what that rotation is.
Answer: Why not use Quarternions in code and convert the Q to angles when needed for display ?
Comment: You mean store as quaternions and convert to Euler angles as needed? Because of the reasons I outlined above - there are many Euler representations for a single orientation... which one do you present to the user?
Comment: Why don't you pick a convention? Say two rotations in the lab frame and one rotation in the body frame. This requires you to keep body coordinates for every object, but an artist might like that.
Answer: You can represent the rotation as axis + rotation angle, which is essentially the same as quaternion (up to a sign)
Answer: I don't think it makes sense to use Euler angles internally - you'll want to use quaternions for all your calculations and usually won't be able to afford the conversions going on everywhere. As for the converting it back to Euler angles for the UI - would it be that bad if the user only gets an angle that is equivalent to the original input but is represented differently? If you do the conversion right, you should end up with the "simplest" Euler angles for any given quaternion.
Comment: I'd love to get away with that, but I suspect in practice the 'simplest' Euler angles are almost as difficult for an artist to deal with as quaternions (in that they aren't always intuitive). Animation data presented as curves would present a particular challenge I think, as it may look quite different from what the artist expects.
Answer: How many conversions are we talking about.  It looks like you're paying for about two transcendental operations per conversion, which on modern hardware is available in the order of 100millions per second.  I'd store both, Quaternions for accuracy and aesthetics and euler rotations for preserving user info.  Maybe add a flag to indicate which is preferred for any given object.  On top of that, you only have to perform the conversion once per rotated member.  Once you've computed a transformation matrix, its multiply-adds until you run out of vertexes.
Comment: This would be true if I was worried about a per-vertex cost or performing transforms for rendering - I'm mainly concerned with blending multiple animations together for a skeleton. So we're talking around fifty bones and perhaps 5 - 10 animations active at the same time. At this stage I'm hoping to store the animation data as quaternions, but I also need to present the animation curves as Euler angles to the user.
Comment: 10 bodies with 50 members each is 500 members, times 72 fps is 36000 conversions.  Not very many.  You could do 1000 times that and still be using very little cpu
Comment: That's a good point. Maybe it really needs to be profiled before writing it off as a solution. But it just seems so inelegant to have to convert constantly! Incidentally, it isn't 10 separate characters with 50 bones, it is a single character with 10 animations active at the same time and blending between them (i.e. a walk with a fast walk and an upper body turn). But I suspect the calculation is the same.


move Sprite only on x-axis

Question: I am working with Ray Wenderlich's 2D Game Development Book and I make use of a function out of this book to control the movement of a sprite, here called 'passenger'. The example in the book is moving the sprite on a x and y axis, where as I only would need to move the sprite along the x axis, but I can not get it working.
Here is 'my' code - well the code I am using
    func move(sprite: SKSpriteNode, velocity: CGPoint){
    let amountToMove = CGPoint(x: velocity.x * CGFloat(dt),
                               y: velocity.y * CGFloat(dt))
    sprite.position = CGPoint(
        x: sprite.position.x + amountToMove.x,
        y: sprite.position.y + amountToMove.y)
}

func movePassengerToward(location: CGPoint) {
    let offset = CGPoint(x: location.x - passenger.position.x, y: location.y - passenger.position.y)
    let length = sqrt(Double(offset.x * offset.x + offset.y * offset.y))
    let direction = CGPoint(x: offset.x / CGFloat(length),
                            y: offset.y / CGFloat(length))
    velocity = CGPoint(x: direction.x * passengerMovePointsPerSec,
                       y: direction.y * passengerMovePointsPerSec)
}

and I trigger these functions from the update loop like this:
if let lastTaxiLocation = lastTaxiLocation {
let diff = lastTaxiLocation - passenger.position
if diff.length() <= passengerMovePointsPerSec * CGFloat(dt){
    passenger.position = lastTaxiLocation
    velocity = CGPoint.zero
} else {
    move(sprite: passenger, velocity: velocity)
    print("update loop")
    }
}

Does anyone have an idea for this issue?
Answer: Try setting only the X component in your move function:
sprite.position.x = sprite.position.x + amountToMove.x

move Sprite only on x-axis


Seaborn issue with catplot

Question: I was following the code in the new seaborn 0.9.0 release as displayed on the site and I got an error when typing in the following code. The code came from the bottom of this page https://seaborn.pydata.org/tutorial/categorical.html
<code>import seaborn as sns
tips = sns.load_dataset("tips")
sns.catplot(x="day", y="total_bill", hue="smoker",
            col="time", aspect=.6,
            kind="swarm", data=tips);
</code>
This is the output from running the above code. I have tried creating a new environment and everything has been updated. I still do not know why it is not working.
<code>---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-21-c1ae50b18a54> in <module>
      3 sns.catplot(x="day", y="total_bill", hue="smoker",
      4             col="time", aspect=.6,
----> 5             kind="swarm", data=tips);
      6 get_ipython().run_line_magic('version_information', '')

~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/categorical.py in catplot(x, y, hue, data, row, col, col_wrap, estimator, ci, n_boot, units, order, hue_order, row_order, col_order, kind, height, aspect, orient, color, palette, legend, legend_out, sharex, sharey, margin_titles, facet_kws, **kwargs)
   3753
   3754     # Draw the plot onto the facets
-> 3755     g.map_dataframe(plot_func, x, y, hue, **plot_kws)
   3756
   3757     # Special case axis labels for a count type plot

~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/axisgrid.py in map_dataframe(self, func, *args, **kwargs)
    818
    819             # Draw the plot
--> 820             self._facet_plot(func, ax, args, kwargs)
    821
    822         # Finalize the annotations and layout

~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/axisgrid.py in _facet_plot(self, func, ax, plot_args, plot_kwargs)
    836
    837         # Draw the plot
--> 838         func(*plot_args, **plot_kwargs)
    839
    840         # Sort out the supporting information

~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/categorical.py in swarmplot(x, y, hue, data, order, hue_order, dodge, orient, color, palette, size, edgecolor, linewidth, ax, **kwargs)
   2989                        linewidth=linewidth))
   2990
-> 2991     plotter.plot(ax, kwargs)
   2992     return ax
   2993

~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/categorical.py in plot(self, ax, kws)
   1444     def plot(self, ax, kws):
   1445         """Make the full plot."""
-> 1446         self.draw_swarmplot(ax, kws)
   1447         self.add_legend_data(ax)
   1448         self.annotate_axes(ax)

~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/categorical.py in draw_swarmplot(self, ax, kws)
   1404                 kws.update(c=point_colors)
   1405                 if self.orient == "v":
-> 1406                     points = ax.scatter(cat_pos, swarm_data, s=s, **kws)
   1407                 else:
   1408                     points = ax.scatter(swarm_data, cat_pos, s=s, **kws)

~/anaconda3/envs/python3/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
   1803                         "the Matplotlib list!)" % (label_namer, func.__name__),
   1804                         RuntimeWarning, stacklevel=2)
-> 1805             return func(ax, *args, **kwargs)
   1806
   1807         inner.__doc__ = _add_data_doc(inner.__doc__,

~/anaconda3/envs/python3/lib/python3.7/site-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
   4193                 isinstance(c, str) or
   4194                 (isinstance(c, collections.Iterable) and
-> 4195                     isinstance(c[0], str))):
   4196             c_array = None
   4197         else:

IndexError: index 0 is out of bounds for axis 0 with size 0
</code>
Answer: This is unfortunately a bug in matplotlib 3.0.1. It's been reported here and fixed by pull/12673.
Options you have are to install either matplotlib 3.0.0 or 3.0.2.

Seaborn issue with catplot


Percussion duration notation issue

Question: As I understand it:
For most percussion instruments "notes" don't really have durations in the same sense as other instruments.  Percussion instruments are struck, and thus usually sound with a quick attack and decay, which is (generally) uncontrolled by the performer.  Therefore, when notating music for percussion it is usually most useful to use note values that are no longer than a single beat (of the given time signature).
Cymbals (and similar) are often notated with cross note heads (like a ghost note).  For percussion, the cross note head emphasises the somewhat meaninglessness of the duration value of percussion notes, unlike the emphasis of the pitchlessness of a true ghost note.

At the end of some music I am writing:  the last notes in the piece occur on the 3rd beat of a bar of 4/4.
This leaves a problem as for what to write for the percussion (tambourine) on the last two beats:

A cross headed minim / half note could be used here (to match with the other instruments note values):

But the symbol for this isn't used very often, and is very ugly.  And as mentioned before, the percussion probably shouldn't have note values that are greater than a beat.

Alternatively, the percussion line could end with a crotchet / quarter note on beat 3, followed by a rest to fill the bar:

It looks really weird to have that (basically meaningless) lonely rest.
A literal interpretation of this would suggests that the percussionist is to play on beat 3, "hold" for the fermata/pause, and then rest for a beat before the end (this is accentuated by the rallentando), — but this just seems absurd.

For either of these options, I think the intended meaning is probably clear, but they both seem like sloppy notation.
What is the best engraving practice for this type of scenario?
Is one of these option is preferable? or is there another way of notating this?
Comment: Well, for starters, I don't recall *ever* seeing the "bordered" cross note you have in your first example. The "rounded" cross note head exists and is common, so I'd use that. Now, the point is that you probably don't want a roll there, right? So I wouldn't be too worried about the rest after that: using a full half there could lead to confusion ("did he forgot to put the cuts for the roll?").
Comment: I wanted to mention the circled cross notehead, since I'm pretty certain I've seen it before, but I couldn't find any examples of it being used, except for open hi-hats on a drum kit part.  Regardless, I think the meaning will be clear for either symbol.
Answer: The U.S. Army band (see the "Percussion Clinic" download) indicates tambourine to be given with standard noteheads, which eliminates the problem described.
Here is the one notation example that specifically includes a half-note:

The Percussion II part for Tchaikovsky's Nutcracker also uses standard note heads for the tambourine. The below image is "Trépak", the final four measures.

(SOURCE: IMSLP, page 24 of the PDF)
Comment: I think this is the most obvious solution, but where does that leave any other instruments which "should" use a cross notehead and might need a half note?
Comment: @Edward Good question -- and a quick search suggests it hasn't yet been asked.
Comment: Playing _a roll_ for the duration of a half-note isn't exactly the same as playing _a single note_ for the duration of a half-note.

Also, in my score, if I needed a percussion roll of greater duration than a beat, I think I'd used consecutive rolled quarter-notes.
Comment: @ElementsinSpace My intention was only to show that standard note heads, including half-notes, can be used for tambourine. The fact that the examples are rolls is just incidental.
Answer: The fermata you use means that the note value is actually more than its usual value/length. So some of the written parts are ambiguous.
It's established that most percussion has a very short sustain value. Cymbals are obviously the odd ones out, and most people understand that their sustain is much longer. But I think most writers are more concentrated on when the sound starts as oppose to when it finishes. So the strike is what is embodied in the notation. For example, a kick drum may have a crotchet showing when it gets its beat, but it'll never be sounding at the end of that crotchet, unlike a piano played crotchet. Pretty pointless writing a quaver followed by a quave rest, as we all know that's actually what will happen anyway.
So in reality it's only sustainable sounds, like cymbals or tambourines, that need more careful notation. So careful attention needs to be afforded to the notation there. As there actually is a start and end to their sounding.
Answer: In most of the charts I've seen, cymbal durations using half or whole notes are written using a diamond shaped note head instead of an x shaped head.
For drumset notation this can cause a little confusion, as some copyists will use the x shape for a ride cymbal and a diamond shape for a crash, but this is easily solved by writing the crash on a ledger line and including a notation key.  But since your chart is for tambourine, the diamond shaped head seems to me to be the simplest solution.
Comment: Changing the angle of a tambourine controls the decay of the sound envelope.  A percussionist seeing a long single note will hold the hoop vertically, which allow the "jingle" to continue for a little bit. Holding the hoop at 45º cuts off the jingle vibrations.  Granted, it's not like dampening a tympani head, but percussionists have more control over duration than you might think.
Comment: Yeah okay, but what is a single long note on a tambourine or similar?  It'll sound the same as a short note followed by a rest, won't it?
Comment: Not exactly.  When the rest arrives a percussionist may need to dampen the instrument, but he/she won't if it's written as a long note.
Comment: I don't think you can really dampen a tambourine.

Percussion duration notation issue