What is the difference between splicing and superimposition?

Question: In music editing, what is the difference between these two terms? Both involve overlaying some track onto another, but I don't see the difference, even though I am told by my professor there is one. Could anybody explain this to me?
Comment: 'Splicing' is a throwback to the days of tape, and physically cutting/taping together pieces of tape.  Thus this refers to the sequencing of audio.  'Superimposition', I'd imagine from the sound of it, refers to 'multitracking' - recording the audio of two sources simultaneously, so that you hear both recordings at the same time.
Answer: With spliced, you hear one then the other.

With superimposed, you hear both at the same time.


How does the boot package in R handle collecting bootstrap samples if strata are not specified but the function separates the dataset by strata?

Question: My current understanding is
1) if strata are not specified, then boot randomly selects rows with replacement from the entire dataset. If dataset is actually stratified then boot would often return uneven sample sizes. In contrast 2) if strata are specified, then boot randomly selects rows with replacement from within each stratum and independent of the other strata.  In this case boot would always return the same sample sizes.
My statistic is the ratio of the means from two different groups and thus I set up my boot call with strata, which I believe then collects bootstrap samples from within each group before running my function. However, to double check my understanding I ran boot with and without strata and was surprised to find the results very similar.  Am I misunderstanding how boot handles strata? Or would these approaches differ only rarely, such as when boot randomly collects a very uneven set of bootstrap samples?
Any explanation of why these two approaches produce similar results is appreciated.
Below is R code for a sample dataset that represents a true value of my statistic  as 10. I've run boot with and without strata specified. I find the estimated confidence intervals are slightly narrower when the strata are specified, but I expected a more dramatic difference.
require(boot)
    # relative yield takes a matrix or dataframe and finds the ratio
    # of the means: treatmentMean/controlMean.
    # data structure:
    # first column is strata, control = 1 and treatment = 2
    # second column is response, or the data to be bootstrapped
    rel.yield <- function(D,i) {
      trt <- D[i,1]
      resp <- D[i,2]
      mean(resp[trt==2]) / mean(resp[trt==1])
    }

    # some data that has a true rel.yield of 10
    sub.pop <- matrix(data = c(rep(1,15),rep(2,15),rnorm(15,2,1),rnorm(15,20,1)),
                      nrow = 30, ncol = 2, dimnames = list((1:30),c('trt','resp')))

    # with strata specified
    b <- boot(sub.pop, rel.yield, R = 1000, strata = sub.pop[,1])
    #without strata specified
    c <- boot(sub.pop, rel.yield, R = 1000)

    # note the distributions of t* are similar
    par(mfrow=c(1,2))
    hist(b$t)
    abline(v=mean(b$t))
    hist(c$t)
    abline(v=mean(c$t))

    # and the CI estimates are also similar
    boot.ci(b)
    boot.ci(c)

Answer: Your understanding 1) and 2) are correct; the strata option makes bootstrap samples within each strata independently, whereas the non-strata option makes bootstrap samples of all the data meaning that bootstrap samples will not contain the same number of samples from within each strata.
As to why they are similar; it is just a matter of sample size. When running the above example (seed 42 and 10,000 bootstrap repli), I obtain

Standard error of stratified bootstrap estimator: 0.8502739
Standard error of estimator: 0.8691592

After increasing the sample size to 10 (not 30), I obtain (with seed 42)

Standard error of stratified bootstrap estimator: 1.032356
Standard error of estimator: 1.131476
Comment: Thanks for this clear answer.  I am going to paste the code below that I used to replicate your answer (in case anyone else wants to play around with the number of replicates and see how it affects standard errors).
Answer: This is how I interpreted the correct answer from svendvn above in case anybody wishes to see the code:
require(boot)
# relative yield takes a matrix or dataframe and finds the ratio
# of the means: treatmentMean/controlMean.
# data structure:
# first column is strata, control = 1 and treatment = 2
# second column is response, or the data to be bootstrapped
rel.yield <- function(D,i) {
  trt <- D[i,1]
  resp <- D[i,2]
  mean(resp[trt==2]) / mean(resp[trt==1])
}

# some data that has a true rel.yield of 10
set.seed(42)
nTrt <- 15
sub.pop <- matrix(data = c(rep(1,nTrt),rep(2,nTrt),rnorm(nTrt,2,1),rnorm(nTrt,20,1)),
                  nrow = nTrt*2, ncol = 2, dimnames = list((1:(nTrt*2)),c('trt','resp')))

(estRelYeild <- mean(sub.pop[sub.pop[,1]==2,2])/mean(sub.pop[sub.pop[,1]==1,2]))
# with strata specified
(b <- boot(sub.pop, rel.yield, R = 1E4, strata = sub.pop[,1]))
#without strata specified
(c <- boot(sub.pop, rel.yield, R = 1E4))

# After decreasing the sample size to 10 (not 30), I obtain (with seed 42)
set.seed(42)
nTrt <- 5
sub.pop <- matrix(data = c(rep(1,nTrt),rep(2,nTrt),rnorm(nTrt,2,1),rnorm(nTrt,20,1)),
                  nrow = nTrt*2, ncol = 2, dimnames = list((1:(nTrt*2)),c('trt','resp')))
(estRelYeild <- mean(sub.pop[sub.pop[,1]==2,2])/mean(sub.pop[sub.pop[,1]==1,2]))
# with strata specified
(b <- boot(sub.pop, rel.yield, R = 1E4, strata = sub.pop[,1]))
#without strata specified
(c <- boot(sub.pop, rel.yield, R = 1E4))


Configuring keyboard settings within PDFView form fields

Question: I'm working on an app which loads PDF files from a server and displays those PDF files within a PDFView.  The files contain form fields in which the user is to type.  That's works fine.  The PDF files are to be used in an education setting, where the spelling should not be autocorrected and predictive text should not be available.
I have not found the means to disable autocorrect in a PDFView, along the lines of autocorrectionType = false in a UITextField.
I'm aware the user can manually disable autocorrection and predictive text in device settings.  That's not a viable option in this case (likely user confusion and no means to verify).  I'm ok if there's a way to disable autocorrect app-wide.
We're creating the PDF files in-house, so we're ok if there's something we can do while generating the files.  Adobe Acrobat is a "check spelling" option on form fields, but the setting has no effect, at least within PDFView.
Thanks.
Answer: I found a solution.  It's a hack, but I'll take what I can get.
I found that when a user taps a PDF text field, PDFKit hides the PDF text field and overlays a UITextView at the same location.  It makes that UITextView the first responder and brings up the keyboard.  That UITextView remains until the user taps elsewhere, when it is removed and replaced with a PDF text field containing the contents of the (now dead) UITextView.
The UITextView in question is buried deep inside PDFView, within private UIView subclasses.
Below is the code I'm using.  It starts with a view (the PDFView) and deep-dives looking for any UITextView it can find.  When found, it resigns as first responder, changes parameters, and becomes the first responder again.  The user will see the typeahead buttons appear briefly then disappear.  I haven't found a way around this, as we don't gain access to the UITextView until it is already the first responder.
The code here is called via a timer executing every 0.1 seconds.  I'm sure there are more efficient ways to do this but this works, and barely registers on the CPU meter.
This code also sets the pasteDelegate of the UITextView because in my case I want to override and prevent pasting of text into the UITextView. The code to do that is simple; in textPasteConfigurationSupporting just return [item setNoResult].
As with all hacks like this, be sure to test with all versions of iOS your app supports - including future versions.  Apple could easily change their PDFKit implementation causing this to break or misbehave.  Or better, they could add a supported means to do this.
-(void)lookForTextViewsInView:(UIView *)view
  for (UIView *subview in view.subviews) {
    if ([subview isKindOfClass:[UITextView class]]) {
        UITextView *textView = (UITextView *)subview;
        //NSLog(@"Found text field with contents: %@",textView.text);
        if (textView.autocapitalizationType == UITextAutocapitalizationTypeNone &&
            textView.autocorrectionType == UITextAutocorrectionTypeNo &&
            textView.spellCheckingType == UITextSpellCheckingTypeNo &&
            textView.pasteDelegate == self) {
            //NSLog(@"textView %@ is already adjusted", textView.text);
            return;
        }
        if (textView.isFirstResponder) {
            //NSLog(@"Adjusting and resetting first responder of %@",textView.text);
            [textView resignFirstResponder];
            textView.autocapitalizationType = UITextAutocapitalizationTypeNone;
            textView.autocorrectionType = UITextAutocorrectionTypeNo;
            textView.spellCheckingType = UITextSpellCheckingTypeNo;
            textView.pasteDelegate = self;
            [textView becomeFirstResponder];
        } else {
            //I don't think this ever fires, but here for completion's sake
            //NSLog(@"Adjusting without resetting first responder of %@",textView.text);
            textView.autocapitalizationType = UITextAutocapitalizationTypeNone;
            textView.autocorrectionType = UITextAutocorrectionTypeNo;
            textView.spellCheckingType = UITextSpellCheckingTypeNo;
            textView.pasteDelegate = self;
        }
    } else {
        //NSLog(@"%@ is not a UITextView", [subview class]);
        [self lookForTextViewsInView:subview];
    }
  }
}

Comment: If anyone cares to use this but be more efficient: I just saw PDFViewAnnotationHitNotification, a notification which fires when the user taps an annotation.  I haven't tested this, so no guarantees...


Login com Asp.net 4.5 (Entity Framework)?

Question: Como consigo fazer um Select utilizando Entity Framework, e verificar se o registro existe ?
Exemplo:
txtlogin.text
txtsenha.text

Tabela Login.

campo usuario
campo senha

valida() classe criada para executar o comando e ao selecionar o valida() ele vai verificar se existe o usuario e senha via Entity Framework
Comment: Você não pode validar antes de enviar para o Entity? de qualquer modo, cadê o código, tem como você colocar? Não da para usar Data anotations? https://msdn.microsoft.com/en-us/library/gg193959(v=vs.113).aspx
Answer: Eu uso assim:
using(var context = new SeuContexto()){
      var Usuario = context.login.firstOrDefault(x=> x.usuario == txtlogin.text && x.senha == txtsenha.text)
      if(Usuario != null)
      {
            //Existe o usuário
      }else
      {
            //Se voltar nulo, não existe o usuário com esta senha
      }
}

Answer: Você pode usar o método Any() do LINQ. Ele retorna true se existir algum (any em inglês) registro. Se não existir retorna false. Ex:
if(contexto.Entidade.Any(x => x.Login == txtLogin.Text && x.Senha == txtSenha.Text))
{
    //existe
}
else
{
    //não existe
}

A documentação do método Any() você pode ver aqui.


How to fix floppy scores

Question: I use a standard Manhasset stand, but whenever I try to work with a large format score (11x17), the top of it flops over the back of the stand desk.  To clarify, the score is 17 inches tall and 11 wide, 22 wide when opened.
They make extenders, but they only make the stand wider - not taller.  Does anyone have a simple/cheap trick to get tall scores to play nicely?
Comment: Oh, also in the "simple answers" category: there are stands with larger desks, intended for conductors. [This one](https://shop.manhasset-specialty.com/c/conductor-music-stand) has a desk 15.5" high, which leaves only 1.5" sticking beyond the top.
Comment: Until today I was virgin to the world of the floppotron.  I haven't lived.
Comment: @Tim I've conducted from scores that were printed or copied onto 11x17 paper in "portrait" orientation and then bound such that the open book was slightly more than 22 inches wide and 17 inches tall.  For the metrically inclined, 11 inches is 279 mm, and 17 inches is 432 mm.
Comment: Now we need to know how high the original platter is!
Comment: @Tim I believe it's 12.5 inches -- 31.75 cm.
Comment: Disappointed that the question is not in fact about [floppy music](https://www.youtube.com/watch?v=3KS02q0BUnY)!
Answer: Print it on better paper -- if you can (commercially available performance materials are never printed on paper as flimsy as most people use in their printers and photocopiers).
But good paper can be costly, especially at that size.  A large piece of cardboard, fixed to the stand with paperclips or clothespins, can serve to extend its surface area and support s larger score.
You can cut the cardboard to the size and shape you need.  For better appearance, you can use some black construction paper, or something more creative in contexts where that would be appreciated.
Comment: Somewhere between cardboard and plywood is [foam core](https://www.dickblick.com/products/elmers-blackcore-foam-board/) which will be available in black, and still quite lightweight.  Another way to attach the board to the desk is with [Command picture hanging strips](https://www.command.com/3M/en_US/command/products/~/Command-Large-Picture-Hanging-Strips/?N=5924736+3294529207+3294737318&preselect=8706801+3293786499&rt=rud), which won't be visible and will allow for easy removal of the board.
Comment: Looks like there might be some 17x11 (portrait) binders available. That is one way to put some cardboard behind it. If the paper is that floppy then maybe it can be hole punched and put in a binder.
Comment: If you go with a homemade extension Velcro is a good choice for attaching it as needed to the stand and it won't be visible or interfere with the music. It can also be detached when not in use.
Comment: I often print on 28# laser paper, which is about the best I can afford/the best my local print shop has to offer.  For smaller scores, adding a few sheets of cardstock before binding helps, but for anything more than 100 pages it isn't enough support.
Comment: @nuggethead if corrugated cardboard isn't stiff enough there's always plywood.
Comment: I feel like plywood would start to get on the "too heavy" side, and would result in the stand frequently knocking over.  Balsa wood might be another possible intermediate material as well.
Answer: Phoog's idea is a great simple solution. If you need a more permanent one, you'll need to pop rivet, screw or weld an extension to the top, which may impede the foldability of the stand.
Looking at the stand, it looks like the top is wood, so you could put a couple of small hinges to make an extension for the top, so the extra will fold down towards you. It'd still work if the original is metal. Again, pops or small nuts/bolts will do the joining to a piece of plywood, of similar thickness to the original. Maybe a little higher, to make room for a light, or the inevitable clothes pegs for the outside windy gig.
Comment: Yes, I do use those (under duress!) But all my charts are on A4. My big problem is in the other dimension - I need 4 stands to hold up the sometimes 8-10 sheets that keyboard players have! I'm going to stick to trumpet or clarinet in the next life...
Comment: I was going to suggest "semi-permanent": buy the plastic horizontal extenders, which "wrap" the desk, and then affix to them a thin sheet of ply (or lexan etc) that also extends the desk vertically. Then you can remove them when you don't need them, but the attachment to the desk is more stable than using clips or clothespins.
Comment: @AndyBonner - or, indeed, a piece of perspex that's big enough for the whole job. That's what I've ended up with on one stand.
Comment: @RedSonja - sounds like not a bad idea. I've ended up welding up a stand that's around 48" wide, so 6 sheets sits on it happily. It slots into the back of the k'bd stand. For the windy days, I've attached a sheet of see-through plastic (similar to what's used in rag-top car roof back windows), held at the bottom with some button magnets. Hence steel, rather than ali. But heavier!
Comment: A standard Manhasset stand is made of sheet metal with textured black paint.  I've certainly seen examples of these stands with customizations in line with the suggestions here.
Comment: @Tim our piano player has an aluminium sheet he takes everywhere, long enough for about 5 A4 sheets. It fits in the keyboard gig bag. It has a hinged bit at the bottom to keep sheets in place and fits nicely on a music stand. He has a load of bulldog clips to keep everything organised.
Answer: One sort of fix is to use three or four of those "wind clips", but just attach them to the stand itself, sticking up as far as you like, to provide support for the music. (Not clipping the music itself, just having detachable clip-ons to the stand itself.)
I don't know the official name for these clips, but they are like giant clothespins, about 10 inches long, and the clip-part happens to be transparent, so that when used to hold music on a stand outdoors in wind, one can see through them. So, in addition to potentially extending the stand itself, they have other good uses.

How to fix floppy scores


How do I get the (date)timestamp since last cron run?

Question: I'm building a module but am stuck..
I need the timestamp from the previous cron as I run a hook_cron job so I can check which nodes are new and email those.
So I need the date/time stamp from the last cron run but how do I get there'?
Answer: A UNIX timestamp of the last cron run can be fetched with:
variable_get('cron_last');

If you need to, you can easily manipulate a UNIX timestamp with PHP's date function.
Answer: hook_requirement() function can help you.
Check this out: http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_requirements/7
In your module file write hook_requirement() function.
function hook_requirements($phase) {
if ($phase == 'runtime') {
    $cron_last = variable_get('cron_last');

    if (is_numeric($cron_last)) {
      $requirements['cron']['value'] = $t('Last run !time ago', array('!time' => format_interval(REQUEST_TIME - $cron_last)));
    }
    else {
      $requirements['cron'] = array(
        'description' => $t('Cron has not run. It appears cron jobs have not been setup on your system. Check the help pages for configuring cron jobs.', array('@url' => 'http://drupal.org/cron')),
        'severity' => REQUIREMENT_ERROR,
        'value' => $t('Never run'),
      );
    }

    $requirements['cron']['description'] .= ' ' . $t('You can run cron manually.', array('@cron' => url('admin/reports/status/run-cron')));

    $requirements['cron']['title'] = $t('Cron maintenance tasks');
  }
}

Comment: helpfull but I like bart's answer better because it's simpler +1
Comment: hook_requirements() only gets invoked for the "runtime" phase from the status report page callback (cf, http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/invokes/hook_requirements/7).  I don't see how this would help determine which nodes are new.


Apart from  Is there any other options for drawing line in Bootstrap3?

Question: I found
 tag in BootStrap3 is having much margin. I am developing page which has compact look during this
 is not looking good on my page. Can you have any other options which allows me to draw a line in Bootstrap 3 ? Or how to remove margin of
 tag of BootStrap3.
Answer: Surely you have custom CSS for your project. Add a bit more:
hr.my-class {margin: 0;}

Or simply:
hr {margin: 0;}

Answer: Since you asked for "another way" to draw a line.  Often, I've used a bottom border for a tag as a sort of underline/divider, e.g.
.underline {
    border:solid #CCC;border-width:0 0 1px 0;
}

You could drop this into a heading tag, into your .row, or whatever and get an underline that will not take up any space other than the height of the line itself.
Comment: Or simply `border-bottom: 1px solid #ccc`. You may also need to add `padding-bottom` for a nicer appearance.


Evaluate the following using Simpson's rule

Question: I was asked to evaluate the following using Simpson's rule (by using 2 strips). Below is the function and my answer to it. What am I doing wrong?

$$\begin{align}
\color{red}{\int_1^{1.6}\dfrac{\sin2t}{t}\,\mathrm dt} & \color{blue}{=\int_1^{1.6}\dfrac{\cos2t^2-\sin2t}{t^2}=\dfrac{0.6}2\big[f(1)+4(1.3)+f(3)\big]} \\\,\\
&\color{blue}{=\big[-1.32-5.1+0.6\big]}
\end{align}$$

When I plugged in the values I put my calculator in Radian mode but the answer I get is negative. The correct answer is 0.2460
Thank you.
Answer: Your formula is wrong. With $f(x) = \sin(2x)/x\;$ you get using the simple Simpson rule
$$\frac{0.6}{6}\left(f(1.0) + 4f(1.3)+f(1.6)\right)\approx 0.245897.$$
and if you take two strips, you get
$$\frac{0.6}{6}\left(f(1.0) + 4 f(1.15)+ 2 f(1.3)+ 4 f(1.45)+f(1.6)\right) \approx 0.245982.$$
What is purpose of the $\cos\;$ expression?
Comment: Oh I see. I guess I forgot that the whole point of using this formula is for functions that can not be integrated! thanks
Answer: Formula for Simpson's rule is h/2 ( f(a) + 4*f(a+h) + f(a+2h) )
Here h = 0.6 and you have chosen a = 1, then why is a+h = 1.3 ?
Comment: I used h= b-a/2 and the simpson formula is h/n [f(1) + 4f(x1) + 2f(x2) + ... f(xn)]. So is the integration part correct?


Console writing, delete characters

Question: My question concerns deleting already written chars in the console. Is there a way to do it?
Lets say i write 10 spaces to the console. Can i delete some to make space for other chars without the output exeeding 10 chars?  I use a special libary given, with functions for writing in the console etc.
Answer: Use '\b'. It erases one character, and the cursor moves back:
std::cout << "nawaz"; //screen shows : nawaz
std::cout << '\b'; //'z' is erased, now screen shows : nawa

Comment: Will never delete new lines.
Comment: Huh, I've been programming C++ for many years and never knew about that escape code.
Answer: do {

cout<<"\b"<<num--;

}

while ( num >0 );

Comment: so to delete the current space, i have to move the cursor to the right and then write the \b, thanks :)
Comment: @Alon_A: is that supposed to be `"\b"` instead of `"\n"`?
Comment: @MooingDuck: Yep, fixed it :)
Answer: Depends on the type of terminal you're using, you could use the escape codes to control it.
For Windows, there are also API functions, if I remember correctly.

Console writing, delete characters


What could be using an HTTP request method of "-"

Question: Got an apache log entry that looks like this, actually I have a bunch of them spread out over time.
XXX.XXX.XXX.XXX - - [27/Apr/2012:14:39:52 -0500] "-" 408 - "-" "-"

It wasn't a GET or POST, the method was "-".
Anyone else seen requests like this?  It wasn't from the penetration tester, but I have it from LOTS of other IPs from Apr of 2012 up until and including today.
We failed it with a 408, just wondering what someone might be trying and googling for minus sign does NOT work.
Answer: 408 is Request Timeout. This means that the client connected but didn't actually send any data for a while, and the server gave up and dropped the connection with this error. This is also why nothing else was logged; no data was actually sent from the client.
Apache's default timeout in this case is 300 seconds (5 minutes); it is configurable, but this generally shouldn't need to be changed.
Comment: I had just assumed 408 was one of the permission errors, but since its timed out, that makes more sense.
Answer: It means that Apache doesn't know what the request method is. In this case it was caused by a timeout (i.e. the client never sent a request). It's also common with 400 Bad Request responses where the client sends an invalid request (such as trying to speak TLS to a non-TLS port and vice versa), or closes the TCP connection as soon as it is establised without sending anything (such as monitoring services performing a TCP connection check).
Answer: Could be caused by slowloris or similiar attacks. The idea is to open as many connection as possible as long as possible. Timeout is by default 300 seconds in Apache.
If you use a preforking server it's easy to reach MaxClients and make the website unaccessible. If the Apache is misconfigured lots of forked processing can cause excessive swapping and kill the machine or slowing it down to a crawl.
mpm_event or a good configured mpm_worker should be harder targets for slowloris. Other mitigations are reducing Timeout to a lower value. I guess it depends on your clients. You probably don't want to kill dail-up users with a time too low timeout. 5 minutes on the other hand is probably too much.


Branch points of a dihedral Galois branched cover of a complex torus

Question: Let $\Lambda$ be a lattice in $\mathbb{C}$ and $X = \mathbb{C}/\Lambda$ be a complex torus. Exercise 6 of chapter 3 of Tamás Szamuely's book "Galois Groups and Fundamental Groups" (actually, the updated version in the erratum here) asks to show that $X$ have a Galois branched cover $Y \to X$, ramified over a single point of $x$, with Galois group $D_n$ (the dihedral group of order $2n$), and that such a cover must have $4$ branch points if $n$ is even, and $2$ if $n$ is odd.
I didn't have any trouble to show the existence of a Galois $D_n$-cover ramified over a single point of $X$, but I am at loss when it comes to show that the number of branch points is $4$ or $2$.
I am trying the odd case first. By considering the maximal cyclic subgroup of order $n$ of $D_n$, I can factor the cover $Y \to X$ to $Y \to Z \to X$, where $Z \to X$ is Galois, of group $\mathbb{Z}/2\mathbb{Z}$, and $Y \to Z$ is of group $\mathbb{Z}/n\mathbb{Z}$. Using Riemann-Hurwitz, I can show the cover $Y \to X$ is actually unramified, and that $Y$ is another complex torus, so that $Y \to Z$ is ramified over two points (which are the preimages in $Y$ of the point of $X$ at which $Z$ is ramified). I expect that the ramification of those points should be "nice", i.e that at those point have exactly one point in their preimage and that the ramification index (relative to $Y \to Z$) at these points of $Y$ is $n$, but I do not know how to show this. I tried further quotienting, but this is getting nowhere as it doesn't end up using the fact that the whole automorphism group is $D_n$.
Also, I feel like this approach has a flaw somewhere, since this would work as well in the even case (except if at some point in the proof of the fact that the points of $y$ have ramification $n$, the fact that $n$ is odd becomes essential), so I do not understand where the parity of $n$ should begin to be relevant in that approach.
For another approach, I know that there are $2$ characters $D_n \to \mathbb{C}^\times$ if $n$ is odd and $4$ such characters if $n$ is even, so I guess there has to be some connection with these characters. I guess the monodromy representation at each of those branch points give a character $D_n \to \mathbb{C}^\times$ but I don't know how to show that the branch point is uniquely determined by this character.
Any help or hint would be appreciated.

Edit: I had a look in Rick Miranda's "Algebraic curves and Riemann Surfaces", there is a chapter about monodromy, which contains a proposition that looks relevant to my problem. That is: there is an equivalence between Galois covers of degree $2n$ $X \setminus \{z_0\}$ and transitive actions of $\pi_1(X \setminus \{z_0\}, z)$ on a finite set of $2n$ elements (that part is the classical equivalence for covers), and the ramification indices can be computed by taking a small loop around $z_0$, and looking at the cycle decomposition of the permutation it induces.
But now, I am even more confused. There are two "obvious" actions of $D_{n}$ on a set with $2n$ elements: that is, its right/left action on itself, or its action by conjugation on itself. In both case, I have identified that the "small loop" around the removed point should actually correspond to the product of the two generating loops. Yet, when I use sage to compute the associated permutation of this representation, I get a composition of $n$ transpositions, regardless of parity, what goes wrong here? Is it my representation, the "small loop" around the removed point, or this approach as a whole?
It should be noted that in the book version of the exercise (not the erratum), the statement is to show there are $n$ branches points when $n$ is even, this is what I find in my computations above. Is the erratum version of the exercise even correct?

In a more concise manner, the question is the following: how many branch points does a Galois ramified cover of a complex torus with Galois group $D_n$ and ramified over a single point of the torus have, and how to show it?
Answer: I found an answer to my question and will post it here for closure.
The confusion about the number of branch points of the branched cover I constructed comes from the fact that I misindentified the "small loop" around the removed point of the torus. In the question, I wrote that this loop corresponds to the product of the two generators of the fundamental group of the torus minus point. But in fact, as one can see by identifying the torus with a square with glued edges, the "small loop" around a removed point is homotopic to the path going through the boundary of the square, which is the commutator of the two generators, and not their generators!
And now, everything goes as expected. The branched $D_n$-cover corresponds to the set $D_n$ with $D_n$ acting on it through the right action, and the commutator of the two generators of $D_n$ acts a product of two $n$-cycles if $n$ is odd, or the product of four $m$-cycles if $n = 2m$. The proposition from Miranda's book I mentionned in my first edit gives the result.


How do I know if a link has the "active" class?

Question: I've added a custom twig template for links--language-block.html.twig.
Inside of it, I want to render additional HTML when the current item is active. But I can't figure out how to check when the current item is active.
{% if links -%}
  {%- if attributes.hasClass('inline') -%}

  {%- else -%}

  {%- endif -%}
    {%- for key, item in links -%}

      {% if item.attributes.hasClass('is-active') %} << this is always false

foobar

      {%- endif -%}

        {%- if item.link -%}
          {{ item.link }}

          {# Deutsch  #}
        {%- elseif item.text_attributes -%}
          {{ item.text }}
        {%- else -%}
          {{ item.text }}
        {%- endif -%}

    {%- endfor -%}

{%- endif %}

How can I check if the link as the active class?
Comment: When you inspect element, do you see the `is-active` class?
Comment: @leymannx, yes, this is the best choice. For anonymous requests there is also a PHP option in a response subscriber, see https://drupal.stackexchange.com/a/235108/47547
Comment: @NoSssweat in the end result yes, but not in the twig template. even using `kint` the final `a` tag has not the active class, only in the browser. it is not javascript, i've checked that
Comment: An alternative would be to **get the current page url or the node title** and use that as your if statement.
Comment: Having the same issue. Did you manage to figure out why this is not working?
Comment: Having the same issue here. I'm still looking into where the is-active class is coming from.
Comment: The active class is not (always) rendered on server-side, see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Utility%21LinkGenerator.php/function/LinkGenerator%3A%3Agenerate/8.2.x and the magic regarding `set_active_class`. But I also don't know how to reliably check for active classes.
Comment: In the end the best choice maybe is to do this via JS.
Answer: In some cases, the active state is not set by design due potential problems with caching. This behavior is documented in this change record.

Setting the active class is now an opt-in feature:
l() and LinkGenerator::generate() now have a set_active_class option that defaults to FALSE
  theme_links() now accepts a set_active_class key that defaults to FALSE
  Those links that you'd expect to get the active class set, do get it: menu links, language switching links …
The output of l(), LinkGenerator::generate() and theme_links() no longer contains the active class, even if you do opt in. Instead, they get a data-drupal-link-system-path attribute, and if there's a GET query, they also get a data-drupal-link-query attribute…

In those cases, where it is not set on server side, you can take a look at core/misc/active-link.js to get an idea how to manipulate the active state on client side.
Comment: Yes this behaviour can be confusing to those of us used to how things worked in previous versions of Drupal. Wasted a lot of time figuring this out for myself.
Answer: It seems you can just use "is_active". This works for me:
{% set link = link|merge({ '#attributes': { 'class': [ 'classes', 'if', 'active'] } }) %}
{% if is_active %}
{% set link = link|merge({ '#attributes': { 'class': [ 'classes', 'if', 'not', 'active'] } }) %}
{% endif %}

{{ link }}

Comment: Really? Even in a cached and unauthenticated session?
Comment: Cant find a menu where I use this where the user is not logged in. Will get back to you if I find a case.
Answer: In Drupal 8 the "is-active" class is added in two different ways:

For anonymous users it's added in the server side.
For authenticated users it's using javascript to add the class, as this allows for better cacheability.

You might consider adding the
 in JS when the DOM is ready, to make sure the class has been added to the DOM.
Answer: For core/themes/classy/templates/navigation/menu.html.twig:
{#
/**
 * @file
 * Theme override to display a menu.
 *
 * Available variables:
 * - menu_name: The machine name of the menu.
 * - items: A nested list of menu items. Each menu item contains:
 *   - attributes: HTML attributes for the menu item.
 *   - below: The menu item child items.
 *   - title: The menu link title.
 *   - url: The menu link url, instance of \Drupal\Core\Url
 *   - localized_options: Menu link localized options.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 */
#}

Then you can write:
{% if item.in_active_trail %}

foobar

{% endif %}

Answer: Define a JS library with a dependency on the core/drupal.active-link library:
mytheme/mytheme.libraries.yml
remove-active-links:
  version: 1.x
  js:
    js/remove-active-links.js: { }
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupal.active-link

Then your JS code knows which link has an is-active class and you can add HTML or remove the link wrapper like in this example:
mytheme/js/remove-active-links.js
(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.removeActiveLinks = {
    attach: function (context) {

      $(context).find('a.is-active').contents().unwrap();

    }
  };

})(jQuery, Drupal);

For more info and an alternative PHP solution (only for anonymous requests) see this answer Don't link menu in the active page


Forecasting sales (in units) for thousand of products

Question: I've got into this internship  in a retail company and they asked me to think a way to forecast their daily sales (in units) in all their stores (with thousands of skus each one).
At first I thought the simplest way, using some exponential smoothing technique, Holt Winter or something like that, or even sarima or arimax, but after analyzing their data, it turned out it has many products with zero sale days (As far as I remember, arima and exponential smoothing has troubles with many zero values and with more than one seasonal pattern, here I bet we'd have weekly, daily and monthly seasonal pattern), so I'm having doubts about using them.
Another possibility would be use some multivariate regression incorporating variables like day of the week, month, year, holidays, sales off days, etc.  but the problem here is that I would have to include the sku and the store as categorical variables with hundreds of levels, is that correct?
Another possibility more complex would be to use the same regression variables with neural networks or  random forest regression with boosting, but again, what to do about that huge amount of levels?
I'm Also considering   take week as the deepest level in the forecast, and then using some weights to distribute if necessary (daily). Finally, one approach I didn't mention was to make some variables based on the autocorrelation function  to try to model the period dependency structure  such as  sales of the week of one month ago, one year ago and probably the slope in those periods, then using some regression model adjustment.
So here I am, asking for some guidance, maybe a book, an idea, an example. Anything would be very appreciated.
ps: Sorry, english is not my first language.
Answer: A simple approach would be to use a regression with dummies to account for seasonality and promotions (if your retailer has them). I would recommend negative binomial regression or Poisson regression because of the slow mover problem you have identified.
You can do this on weekly level and distribute the forecast to days using weights, as you propose, or work directly on daily level with weekday dummies. The latter would be easier if your retailer has promotions whose length does not exactly coincide with calendar weeks.
You can build one giant model with lots of dummies for products and stores (or, more sophisticatedly, a hierarchical model), or go the simpler route of separate models per prod-loc. If you have many parameters and few observations, some kind of regularization may be helpful.
Previous threads may be useful, in particular this one. I like to believe that an article I wrote (Kolassa, 2016, International Journal of Forecasting) might be enlightening.


Appending NSDictionary to other NSDictionary

Question: I have one NSDictionary and it loads up UITableView. If a user scrolls more and more, I call API and pull new data. This data is again in the form of an NSDictionary. Is it possible to add the new NSDictionary to the existing one?
Answer: You looking for this guy:
[NSMutableDictionary addEntriesFromDictionary:]

Make sure your UITableView dictionary is an NSMutableDictionary!
Check it here
Comment: Yes, but why do you want duplicate entries of keys in a dictionary?
Comment: @DawnSong I would just create a category on NSDictionary if I were you with the following method:

`+ (instancetype)dictionaryByAddingEntriesFromDictionary:(NSDictionary *)dictionary {
    NSMutableDictionary *combinedDictionary = [NSMutableDictionary dictionaryWithDictionary:self];
    [combinedDictionary addEntriesFromDictionary:dictionary];

    return combinedDictionary;
}`

Sorry for the formatting issues.  StackOverflow doesn't allow friendly multi-line code formatting in comments.
Comment: What I want is `-[NSDictionary dictionaryByAddEntriesFromDictionary:]`, however, there is no such a method in `NSDictionary`.
Comment: Obviously, it's just dictionaries' union operation, not duplicate entries. @JohanKarlsson
Comment: I think the real question is about how to do this WITHOUT intermediate mutable objects. The main benefit for such a thing (which exists for NSString, for instance) is being thread safe.
Comment: If the NSMutableDictionary is only intermediate, then it does not matter if it's thread safe because you would simply return an NSDictionary after you had finished merging in another dictionary.  All of the work will be done in one thread.
Answer: Use NSMutableDictionary addEntriesFromDictionary to add the two dictionaries to a new mutable dictionary.   You can then create an NSDictionary from the mutable one, but it's not usually necessary to have a dictionary non-mutable.
Answer: Is your NSDictionary full of other NSDictionaries? It sounds like you would need an NSMutableArray that you could add NSDictionaries to at the end. Assuming you can control the flow of data coming in and wouldn't run the risk of duplicates in your array, you could certainly append the data.
NSMutableArray *array = [[NSMutableArray alloc] init];
arrayCount = [array count]; // check the item count
[array addObject:dictToAppend];

Without seeing how you are implementing it, I can't provide more detailed code examples. Appending items is easy to do, but know it can only be done with mutable versions of Arrays or Dictionaries. Hope this helps a little.


How do I move user folders for many users to a new server?

Question: I need to move two users folders on two separate drives on a main DC to another shared folder on a NAS. These user folders are the users main home drives.
What is the best way to do this without doing it one at a time.
Answer: Try using xcopy or robocopy from the Microsoft Windows Resource Kit (and optional GUI) to do the copying of data.
Answer: Robocopy is your friend.
Comment: You can specify UNC paths in the Robocopy arguments, thus you can use it anywhere to copy from A to B, so long as they are both accessible to you.
Comment: You can preserve ntfs permissions using the /COPYALL switch.  Have you tried using Robocopy?  Why are you saying it does not work?  You don't have to run robocopy from the NAS, you can run it from the DC.
Comment: Robocopy does not work. I need to move all the user home folders to a NAS. I cant run Robocopy from there. Unless I can run robocopy from a remote server, moving the user files from the DC to the new NAS. Is this possible? Can I move these home folders and save their rights with robocopy to the NAS?
Comment: You are correct. robycopy is getting done what I need it to do. The issue I have now is that the permissions do not carry over to the NAS. I am trying to figure out how to get the user folders that were moved with robocopy from the DC to the NAS to be accessible to the users once I change their home drive mapping. Once I changed the home drive mapping in AD it worked (as in it mapped the users folder on the NAS) but not the user folder for that user, just the users folder that contains all the user folders and the account has access to read all the folders in there. Which cant happen.
Comment: its a linksys/ cisco NAS and has only limited interface for security settings, it only allows 21 people to be assigned to one share for some reason. So I am trying to work out how to not have to set up separate shares for each user account. I want to do it in a mass change. It looks like I am still going to have to do each one individually, unless I can find a way to make a mass change in rights for each new user share on the NAS.
Answer: It seems that I found the solution to my issue. The NAS cannot do what I thought it could. It is a NSS6000 Linksys and it seems that the limitations in the security rights interface is hindering the rights I need to be able to set.
So I am going to order a new file server that will be the primary user home drive server and set this server up as a member server in our domain.
Thanks for all your help. I did not know that robocopy has a new version called RichCopy, and it has a really cool interface GUI.
Thanks all.


Asp menu control formatting sitemapnode

Question: I'm trying to figured out how to separately format sitemapnodes which do not have a URL associated. Here's a code example:
<code><siteMapNode title="TheThingIWantFormattedSeparately">
  <siteMapNode url="~/pages/customer.aspx" title="Customer"/>
  <siteMapNode url="~/pages/contract.aspx" title="Contract"/>
</code>
So I'm wanting the FIRST sitemapnode to look different than the other sitemapnodes. Is this possible? I'm digging around but am not finding much out there.
Answer: Not 100% sure, but this might help: CSS friendly menus with ASP.NET Menu control, jQuery and Superfish.

Asp menu control formatting sitemapnode


How to set mysql port for Drupal and Drush

Question: My site was running fine with the following default setting in settings.php file:
<code>'host' => 'localhost',
'port' => ''
</code>
Then I created a separate mysql instance on another port:
<code>'host' => 'localhost',
'port' => '123'
</code>
But this does not affect drupal - it still connects to the old db on default port!
With the following settings drupal connects to the new db, but now I can`t make archive-dumps with drush. Drush reports an "Unknown MYSQL server host error".
<code>'host' => 'localhost:123',
'port' => ''
</code>
Answer: For the port configuration in settings.php you can do by following(in example i used MYSQL in 33066) and the value of port is integer not string:
<code>//D6 DB config
$db_url = 'mysqli://mysqluser:mysqlpassword@dbhost:33066/yourdb';

//D7 DB config
$databases = array('default' => array('default' => array(
  'driver' => 'mysql',
  'database' => 'yourdb',
  'username' => 'mysqluser',
  'password' => 'mysqlpassword',
  'host' => 'dbhost',
  'port' => 33066 )));
</code>
Comment: That is what I tried.

> But this does not affect drupal - it still connects to the old db on default port!
Comment: Drush only get configuration from /sites/default/settings.php. Did you place your settings file in /sites/yoursite.abc/settings.php?
Comment: Drush is using /sites/yoursite.abc/settings.php, at least for archive-dump command, where I tell it which site to archive. And yes, I am changing only mysite/settings.php. With 'localhost' it is working, with 'localhost:portnum' - not.


Is there any difference between the size of a cricket ball for men and women in cricket? if yes then Why?

Question: Cricket ball is heavy weighted in both cases for men and women but is there any difference between the size of cricket ball that is used for women and men? if the answer is yes then what the reason behind this difference?
Answer: The weight of the ball in women's cricket must be in between(139.98 to 150.61 grams). Whereas for men it is somewhere between (Appx 155.9–163 gm)
https://www.quora.com/How-is-women%E2%80%99s-cricket-different-than-mens-cricket
https://www.quora.com/Does-women-cricketers-use-the-same-kind-of-hard-ball-used-by-mens-cricketers
womans are considered weaker than men that's why the ball is lesser in weight
Answer: The laws are perfectly clear. Women's cricket uses a ball that has slightly less mass and may be slightly smaller than the ball used for men's cricket.

4.1 Weight and size
The ball, when new, shall weigh not less than 5.5 ounces/155.9 g, nor more than 5.75 ounces/163 g, and shall measure not less than 8.81 in/22.4 cm, nor more than 9 in/22.9 cm in circumference.
...
4.6 Specifications
The specifications as described in 4.1 shall apply to men's cricket only.  The following specifications shall apply to:
4.6.1 Women's cricket
Weight: from 4.94 ounces/140 g to 5.31 ounces 151 g
Circumference: from 8.25 in/21.0 cm to 8.88 in/22.5 cm.

The difference is due to traditionalist views of women as a physically weaker sex requiring some allowance for their perceived inability to handle "proper" equipment.


onClick event not working when changing the parameter name

Question:

So I have an event on Click . it works when i pass "id" as parameter but doesn't work when i pass "key" , even though all the properties of id and key are same(see the image).
below is the method
I have already made all the properties of ID and KEY same , but it seems not to work.

onClick={ () => this.props.onDelete(this.props.key)}

VS
onClick={ () => this.props.onDelete(this.props.id)}

Comment: [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551)
Comment: What "doesn't work" about it?  What debugging have you done?  Please provide a runnable [mcve] which demonstrates the problem and indicate specifically what problem you are observing.
Answer: key is a reserved prop in a React component. You won't be able to access it in child component. If you need it, give it some other name.
Answer: The key property is used by React under the hood, and is not exposed to us inside the component.
You can see more info in the official documentation:
https://reactjs.org/docs/lists-and-keys.html#keys-must-only-be-unique-among-siblings
(Keys serve as a hint to React but they don't get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name)


Form Recognizer Train Fails InvalidContentSourceFormat: Invalid content source: Could not read build content

Question: I spent a good amount of time marking up custom extraction models on some PDF docs in Form Recognizer. I see the forms in blob, the app has Reader access to the blob, and I see labels.json and ocr.json files are created in the blob.  When I try to train the model I get the error:  InvalidContentSourceFormat: Invalid content source: Could not read build content.
I don't see any relevant logs or error messages, but I'm sure I'm not looking in the right place. I"m a bit of newbie to Azure so I appreciate your input and assistance!
I have looked at activity logs for the blob storage, checked if the resource group is locked, checked that the Form Recognizer has a reader role for the blob.
Answer: Based on the scenario, I have created a custom form recognizer training using this and sample pdf form data
The error message "InvalidContentSourceFormat: Invalid content source: Could not read build content" indicates that there is an issue with the content source access you are trying to use to train the model.
As per the details provided in question I have generated a SAS URL to blob storage  container with Read Permission and it was giving access error.
To solve this, while generating the SAS URL to blob storage container give these permissions:

Read
List

Generate SAS URL:(https://i.imgur.com/qYh2wzT.png)
As mention in the azure sample code,
With this I'm able to access the data and train the model.
Data Access:(https://i.imgur.com/jKT4qct.png)
Training:(https://i.imgur.com/x5krhN2.png)
Please also check/validate these in the sample code for more details:

prefix
includeSubFolders
useLabelFile
layout of labels.json and OCR.json


answer verification, permutations (ways to make n words out of m letters)

Question:
How many ways are there to make different words (not necessarily meaningful) by changing order of letters in the word $b_1b_1...b_1b_2b_2...b_2...b_mb_m...b_m$, where $b_1$ appears $k_1$ times, $b_2$ appears $k_2$ times, ... , $b_m$ appears $k_m$ times.

My answer is $$\sum_{k_1+k_2+...+k_m = n \\ 0\leq k_i \leq n}\quad\Large\frac{n!}{k_1!k_2!...k_m!}b_1^{k_1}b_2^{k_2}...b_m^{k_m}$$
Is this correct?
Comment: Try out some small example to test your formula, with say one **a**, two **b's**, three **c's**
Comment: What does it mean to raise $b_1$ to some power?
Comment: If all the numbers would have been distinct, you would have $n!$ ways. If you make 4 of them the same, you can permute the 4 by fixing the others in $4!$ ways, so you're counting every case $4!$ times. So, there would be $n!/4!$ ways. Try to extend this to more groups of the same thing
Comment: I have written an answer to point out a possible source of your confusion.
Comment: @trueblueanil would the answer be 60?
Comment: @DavidP It means permutations of $b_1$ identical letters? So for k=3, $b_1^k$ would be ways to make 3 letter words out of $\alpha,\beta,\gamma$, so 3*2*1 = 3!
Comment: @trueblueanil Isn't that what the question is asking?
Answer: Your answer of $60$ corresponds to $\large\frac{6!}{1!2!3!}$, the first part of your formula, which represents the number of permutations of a $n$ letter word with $k_1$ of the first kind, $k_2$ of the second kind,.... $\Sigma k_i = n$
This represents the multinomial coefficient
What you have possibly mixed it up with is the Multinomial Theorem, which states
If events $E_1, E_2, ... E_k$ can occur with probabilities $p_1, p_2, ... p_k$ respectively, then the probability that events $E_1, E_2, ... E_k$ will occur $X_1, X_2, ... X_k$ times respectively is
$$\Large\frac{N!}{X_1!X_2! ... X_k!}p_1^{X_1}p_2^{X_2}... p_k^{X_k}$$
where $X_1 + X_2 + ... X_k = N$
Comment: Yea, just the **multinomial coefficient**
Comment: Actually, the formula should be written as $\large\frac{n!}{k_1!k_2!...k_m!},\;{k_1+k_2+...+k_m = n;\; 0\leq k_i \leq n}$
Comment: Or if you insist on a sigma sign, $\large\frac{n!}{k_1!k_2!...k_m!},\;{ 0\leq k_i \leq n;\;\; \Sigma k_1 = n}$
Comment: Glad to be of help !\;\; :)
Comment: You might also like to see a simpler treatment of the problem https://math.stackexchange.com/questions/1759845/how-do-i-calculate-the-number-of-unique-permutations-in-a-list-with-repeated-ele/1759860#1759860
Comment: Thanks for the answer! So the answer to the original question would just be $$\sum_{k_1+k_2+...+k_m = n \\ 0\leq k_i \leq n}\quad\Large\frac{n!}{k_1!k_2!...k_m!}$$ ?
Comment: So we only have one term, $\quad\Large\frac{n!}{k_1!k_2!...k_m!}$ ? No summing up?
Comment: Or does multinomial coefficient include the sigma?
Comment: Thank you! That was huge help.


XPathNavigator.Evaluate returning incorrect value?

Question: I'm expecting this code to return true but it doesn't ? What am I missing here.
<code> string xml = @"<!DOCTYPE root [ <!ELEMENT e (e*) ><!ATTLIST e  id    ID    #REQUIRED>]>
         <data><e id=""NUM_CPUS"">2</e><e id=""ACE_PRESENT"">1</e></data>";
  XPathDocument doc = new XPathDocument(new StringReader(xml));
  string expr = "(id('NUM_CPUS'))>=1 and (id('ACE_PRESENT'))=1";
  XPathNavigator nav = doc.CreateNavigator();

  XPathExpression query = nav.Compile(expr);

  object result = nav.Evaluate(query);
  bool b = bool.Parse(result.ToString());

  if (!b)
    throw new Exception("Should be true");
</code>
Comment: The returned `false` is correct, because the string value of `0` is 0, but the expression checks if it is equal to 1. 0 = 1 is `false`
Comment: Answered my own question, you must have the DTD at the top:

]>
Comment: If you know the XPath expression evaluates to a boolean value then you can simply do `bool result = (bool)nav.Evaluate(query);`, there is no need to convert to a string to then parse that as a boolean. As for your sample, it returns false I think, even as edited as it has `0` but checks `(id('ACE_PRESENT'))=1`. But if hadn't had any DTD before declaring attributes of type ID then yes, with XPath 1.0 a DTD needs to define ID attributes to be able to use the `id` function successfully.
Answer: Adding the header, makes this work:
<code><!DOCTYPE root [ <!ELEMENT e (e*) ><!ATTLIST e  id    ID    #REQUIRED>]>
</code>
Comment: Without the header, you will always get false


Converter numero para minuto e subtrair esses minutos de uma coluna que contenha data e hora R

Question: Bom dia, possuo uma coluna (minutos1) que possui dados da quantidade de min (105,90,80)
Preciso transformar esses minutos em horas (HH:MM), após isso subtrair essas horas criadas de outra coluna inicio (DD/MM/AAAA HH:MM) que possui dados em  data e hora e minuto ("2018-06-01 12:00", "2018-06-01 11:00", "2018-06-01 15:20")
Muito obrigado desde já.
Comment: @MarcusNunes você está coberto de razão. É mais fácil criar uma nova pergunta do que se debruçar em tentativas
Comment: @MarcusNunes Entendo que agora ele esteja querendo o contrário. Nessa pergunta que você linkou, ele gostaria de transformar horas em minutos e, agora, ele quer transformar minutos em horas e depois fazer umas operações.
Comment: Luis recomendo que você, ao criar uma pergunta aqui no site, coloque o seu banco de dados, ou uma parte dele para que a gente possa te ajudar de forma mais fácil. Pesquise sobre o comando `dput` no `R`
Comment: Entendo o teu ponto de vista, mas uma pergunta não seria o inverso da outra? Imagino que o AP consiga interpretar o código fornecido no link que coloquei e realizar a operação inversa caso se tente. Veja que a pergunta sequer tem uma tentativa de solução.
Comment: Boa tarde pessoal, desculpa a demora em responder,

O que acontece tenho uma coluna Tempototal = c("15/08/2018 06:00", "16/08/2018 10:35")
solo = c("01:00", "02:00")

e inicio.de.uso que tem que ser  c("15/08/2018 05:00", "16/08/2018 08:35")

Por isso pedi a primeira pergunta, agora tenho que converter os minutos em horas, subtrair esses minutos da coluna tempototal, e criar uma nova coluna com o campo data e a hora dessa subtração.
Answer: Criei um banco de dados com o exemplo das variáveis que você informou para facilitar.
dados <- data.frame(
  inicio = c("2018-06-01 12:00", "2018-06-01 11:00", "2018-06-01 15:20"),
  minuto1 = c(105, 90, 80) )

Utilizei o pacote chron
library(chron)

#criação da variável horas_inicias, extraindo essa informação de inicio
dados$horas_inicio <- as.character(substr(dados$inicio, 12, 16))
#acréscimo de segundos para utilizar a função times
dados$horas_inicio <- paste0(dados$horas_inicio, ":00")
#transformação da variável para tempo
dados$horas_inicio <- times(dados$horas_inicio)
#criação da variável horas, transformando minutos
dados$horas <- times((dados$minuto1%/%60 +  dados$minuto1%%60 /60)/24)
#cálculo da diferença de tempo entre as variáveis criadas
dados$diferença <- dados$horas_inicio - dados$horas

Comment: Rafael muito obrigado mais uma vez pela ajuda.


Generate distributions in c++11

Question: I am using the following code to generate exponential distribution between [0,1] and normal distribution between [0,1]:
#include <iostream>
#include <algorithm>
#include "boost/random.hpp"
#include "boost/generator_iterator.hpp"
using namespace std;

int main()
{
   typedef boost::mt19937 RNGType;
   RNGType rng;

   //for generating exponential distribution
   boost::exponential_distribution<0,1> one_to_six;
   boost::variate_generator< RNGType, boost::exponential_distribution<> >
                dice(rng, one_to_six);
   double number = dice();
   cout<<"random number according to exponential distribution="<<number<<"\n";

   //for generating normal distribution
   boost::normal_distribution<0,1> one_to_six1;
   boost::variate_generator< RNGType, boost::normal_distribution<> >
                dice1(rng, one_to_six1);
   double number1 = dice1();
   cout<<"random number according to normal distribution="<<number<<"\n";
}

But I dont know why I am getting error with the code. Can someone please help me figure out as to where am I going wrong. I am using c++11.
The error which I am getting is:
 no known conversion for argument 2 from 'int' to 'boost::normal_distribution<>'

As suggested by Barry I tried to change the code to:
int main()
{
   typedef boost::mt19937 RNGType;
   RNGType rng;

   //for generating exponential distribution
   boost::exponential_distribution<double> one_to_six;;
   boost::variate_generator< RNGType, boost::exponential_distribution<> >
                dice(rng, one_to_six);
   double number = dice();
   cout<<"random number according to exponential distribution="<<number<<"\n";

   //for generating normal distribution
   boost::normal_distribution<double> one_to_six1;
   boost::variate_generator< RNGType, boost::normal_distribution<> >
                dice1(rng, one_to_six1);
   double number1 = dice1();
   cout<<"random number according to normal distribution="<<number<<"\n";
}

But I am still getting the error:note: boost::variate_generator::variate_generator(Engine, Distribution)
Comment: What error are you getting?
Comment: @JimLewis I have posted the error.
Comment: You define `one_to_six` twice as different types. This is illegal. Please post actual code?
Comment: @nneonneo Thanks for pointing out...that was a typo...sorry for it
Answer: Always post and read the compiler errors. In this case, it's very clear:
main.cpp:13:36: error: template argument for template type parameter must be a type
   boost::exponential_distribution<0,1> one_to_six;
                                   ^
/usr/local/include/boost/random/exponential_distribution.hpp:37:16: note: template parameter is declared here
template<class RealType = double>
               ^
main.cpp:20:31: error: template argument for template type parameter must be a type
   boost::normal_distribution<0,1> one_to_six;
                              ^
/usr/local/include/boost/random/normal_distribution.hpp:256:16: note: template parameter is declared here
template<class RealType = double>
               ^
2 errors generated.

boost::exponential_distribution is defined as:
template <class RealType = double,
          class Policy   = policies::policy<> >
class exponential_distribution;

So you probably need:
boost::exponential_distribution<double> one_to_six;

And the same for your normal_distribution variable. Which, additionally, should take a different name, because currently you have two variables named one_to_six in the same scope.
Comment: I modified the code as you suggested but I am still getting the error as specified in the edit in my question
Comment: @JannatArora Compiles for me. What version of boost?
Comment: Thanks a lot...compiles for me too but I am not able to get exponential distribution between [0,1] ..the number which it generates is 1.45
Comment: @JannatArora If it compiles for you, why are you saying you are still getting a compile error?
Comment: Sorry I modified my question..I was making a silly mistake earlier..now it compiles well for me...thanks to you...but I am not able to get exponential distribution between [0,1] ..the number which it generates is 1.45
Comment: @JannatArora If you have a new question, ask a new question. Don't change this question to ask something else entirely.
Comment: Ok..sorry .. I'll post this as another question :)

Generate distributions in c++11


Como formatar uma data no formato 'dd/MM/yyyy'?

Question: Como obter uma string formatada de um objeto do tipo Date no formato dd/MM/yyyy?
Answer: Utilize os filtros do AngularJS
Para formatar as datas no Angular, existe o Angular Filter que é muito útil e fácil de usar, seja na view ou nos controllers. O filter ainda pode ser usado para formatar qualquer tipo de objeto. Para data existem várias combinações possíveis.
Como usar filters?
Em um template HTML
{{ filter_expression | filter : expression : comparator}}
No código javascript (Diretivas, controllers, etc)
$filter('filter')(array, expression, comparator)
Como formatar datas?
Você pode converter seu objeto do tipo Date em qualquer string baseado na configurações, veja alguns exemplos:

yyyy ano com 4 dígitos
MM mês com 2 dígitos (01-12)
M mês com 1 ou 2 dígitos (1-12)
dd dia com dois dígitos (01-31)
ddia com 1 ou 2 dígitos (1-31)
ou veja a lista completa na documentação do Angular

Há ainda a possibilidade de adicionar o Angular Locale em seu projeto para utilizar os formatos no idioma que desejar, no nosso caso PT-BR ou PT-PT.
Exemplo de código - Template HTML

angular
  .module('myApp', [])
  .controller('myController', myController);

myController.$inject = ['$scope'];

function myController($scope) {
  $scope.data = new Date(2014, 11 - 1, 13, 17, 17, 47, 0);
}

Valor original: {{ data }}

dd/MM/yyyy: {{ data | date: 'dd/MM/yyyy' }}

Data completa: {{ data | date: 'fullDate' }}

Exemplo de código - Controller

angular
  .module('myApp', [])
  .controller('myController', myController);

myController.$inject = ['$scope', '$filter'];

function myController($scope, $filter) {
  var data = new Date(2014, 11 - 1, 13, 17, 17, 47, 0);
  $scope.data = data;
  $scope.dataFormatada = $filter('date')(data, 'dd/MM/yyyy');
}

Original: {{ data }}

Formatada: {{ dataFormatada }}

Comment: Eita, tava fazendo um exemplo no controller e não vi que já tinha editado :p
Comment: @Techies coloquei logo depois.. hehe De qualquer forma vou usar seu link do locale na minha resposta.
Comment: Tranquilo, rs eu que não tinha visto.
Answer: A resposta do @Pedro já responde sua dúvida, porém gostaria de mostrar um exemplo onde podemos trabalhar com filtros direto no Controller:

var myApp = angular.module('myApp',[]);

myApp.controller("MyCtrl", function($scope, $filter){
 var data = "2016-02-18T10:23Z";
     $scope.dataFormatada = $filter('date')(data, 'dd/MM/yyyy');
});

  Data Formatada, {{dataFormatada}}!

OBS: Para trabalhar com datas no nosso formato recomendo dar uma olhada no locale
Answer: este filtro me ajuda a lidar com os timestamps
dateFilter.js
angular.module("zendapp").filter("brdateFilter", function(){
return function(input) {
    var o = input.replace(/-/g, "/"); // Troca hifen por barra
    return Date.parse(o + " -0000");
};
});

index.html
{{row.created_at.date | brdateFilter | date:"dd/MM/yyyy HH:mm"}}


ESLint throwing "Parsing error: Unexpected token :" on variable that ends in :

Question: I am working on the jest project and the linter is throwing me an issue...

error  Parsing error: Unexpected token :

I have been playing with the lint configuration a bit and I am not sure what I messed up but when I go to the code I see...
const BULLET: string = chalk.bold('\u25cf');

This seems weird to me (a name ending in :) is this a common React practice or just a typo? Is there a way to tell ESLint to ignore this convention throughout?
Comment: It is invalid JS. You sure you're not using TypeScript?
Comment: Because the project uses TypeScript? And *is* in the Jest `devDependencies`, because there's TypeScript code in it.
Comment: This is not TS. It's flow syntax. You need eslint plugin for flow and mark the file with //@flow comment.
Comment: I want to agree with you but here is the FB code...

https://github.com/facebook/jest/blob/master/packages/jest-validate/src/utils.js (ln 14)

Why is it on their master branch?
Comment: Like are you sure it isn't a babel or React thing?
Comment: See the link but I don't see TS as a dependency
Comment: interesting I missed it the first time but it is still odd the extension isn't TS
Comment: Ahhh I have removed all those temporarily I will try adding them back!
Answer: This is  flow syntax. You need to mark your file with
//@flow

And probably also add Babel and ESlint plugin for flow syntax.
See https://flow.org/en/
Comment: @Jackie Of course, for example https://www.npmjs.com/package/flow-node But if you don't want to use flow, why don't you just remove the annotations? To just make ESLint understand it, there is the plugin https://github.com/gajus/eslint-plugin-flowtype
Comment: @Jackie You are right, I am gonna remove my comments about that. They use babel themselves to translate their code, nothing more. The same is valid for the eslint flow plugin though.
Comment: Lets take this https://github.com/jrgleason/jest/blob/master/packages/jest-validate/src/__tests__/fixtures/jest_config.js as an example. I have added plugin: [ 'flowtype' ] but when I run I still get the error on the string:. I am not using the babel-parser is that a problem for flow? I want to avoid it
Comment: @jackie Its no valid javascript, you need some kind of preprocessor, at least to remove the annotations.
Comment: Is there a way to do that without Babel?
Comment: Thanks yeah I don't want to remove it because it isn't my project.
Comment: So the flow-node looks like it just removes the annotations. Does that mean I would have to run eslint once with just the flow rules, then remove annotations, then run eslint again? Maybe you are right about removing it, what would be the replacement?
Comment: @Jackie For ESLint just use that eslint plugin I have linked above.
Comment: eslint plugin uses Babel. Seems so redundant
Comment: And I would still need to run eslint 2x once before removing annotations and once after
Comment: RT I was thinking about that I can easily run flow (I tried `./node_modules/.bin/flow check`). But I don't know how to then remove the annotations without changing the file. Maybe I need to configure to use Webpack so that it is just a stream.
Comment: yeah but going to Webpack is a big step, guess I'll have to bite the bullet thanks for the help.
Answer: Looks like I'm wrong; this is indeed Flow syntax. See the other response for the correct answer.
That's Typescript syntax. You should configure your linter to support typescript.
For ESLint:
npm install --save-dev typescript-eslint-parser

And in your ESLint configuration file:
"parser": "typescript-eslint-parser"

Comment: Interesting that it has a .js extension. Must be a babel thing?
Comment: Flow, not typescript.


Finalizar video de youtube embedado em as3

Question: Estou usando um video do youtube embedado em um flash. Quando o video termina, fica com a tela padrão do youtube de final de video, e sugere videos para o usuário.
Existe um modo de definir para o video pausar no seu frame final ou ir para outro frame assim que o video terminar?
Answer: Se o que você quer é não exibir os vídeos relacionados no final do vídeo, basta acrescentar o parametro rel=0 no final da url.
Por exemplo:

Mais informações:
https://developers.google.com/youtube/player_parameters?hl=pt-br

rel players compatíveis:  HTML5, AS3 /  0 ou 1. O valor padrão é 1. Este parâmetro indica se o player deve exibir vídeos
  relacionados quando a reprodução do vídeo inicial acaba.
Comment: Opa funcionou bem, agradeço. Li essa documentação e pelo visto pulei o a parte sobre o rel.


Combining AND and OR in Rules

Question: I'm trying to set up a rule (using the Rules module) with AND and OR conditions.
I have a content type with a field A (date) and field B (time slot).
The rule needs to check if field A is either e.g. a Monday or a Wednesday AND if the time slot in field B is either 16:00 or 17:00 or 18:00 or 19:00 (on a Monday) OR 13:00 or 14:00 or 15:00 or 16:00 (on a Wednesday).
If it meets those criteria it has to perform an action.
I've set up my rule as shown in the screenshot, but alas whatever combination or indentation I use, it won't work ...
Who can shed some light on this? Much appreciated.
Comment: I think you only need one "OR" and 8 "AND"s: (Monday AND 16:00) OR (Monday AND 17:00) OR ... OR (Wednesday AND 15:00) OR (Wednesday AND 16:00). *Or* have I misunderstood your situation?
Comment: Hey b@Jeroen , I think your comment might also work, though you'd be testing "Is it Monday" 4 times (I think), What your comment doesn't say is how the "indents" should like (as you must know: crucial to get it to work). Why not post an answer similar to mine (feel free to copy/past my layout I used and adapt it to what you suggested). If you do, and assuming both answers are correct, Colin is going to have a hard time to select which one to "accept", no?
Comment: Merci for your (late) accept of my answer ... So what's next, no other Rules-related questions anymore?
Answer: You need 2 extra ANDs, right below the highest level (1st) OR.
And EACH of the 2 ORs you already have, and the Data comparison that preceeds those ORs, you need to move them below the extra AND. So that in the end it looks like so:

OR

AND

Data Comparison (A=Maandag)

OR

Text Comparison (B=16:00)

Text Comparison (B=17:00)

Text Comparison (B=18:00)

Text Comparison (B=19:00)

AND

Data Comparison (A=Woensdag)

OR

Text Comparison (B=13:00)

Text Comparison (B=14:00)

Text Comparison (B=15:00)

Text Comparison (B=16:00)

Here is how "I" would translate the above logic:

We accept a date that is either on Monday (line 2 to 8) OR (line 1) Wednesday  (line 9 to 15).
If you want a date that is a Monday (= line 3), we insist (via the AND in line 2) that you pick a timeslot that fits for us on Monday.
To pick a timeslot for Monday, you have a choice (OR in line 4) of 4 options (ie those in line 5, 6, 7 or 8).
Similar Rules, oeps rules, apply for Wednesday, as expressed in line 9 to 15.

If after these changes your Rules Action(s) still don't get executed (because something else is wrong in any of these Rules Conditions, and/or you're not using an appropriate Rules Event), then move on to Rules debugging, as explained in "How can I display the value of a variable inside a condition?".
PS: just to make sure your "Text Comparison" condition behaves as you expect/hope it to do, create a temporary clone of your rule with only 1 Rules Condition (= 1 such text comparison), with same Rules Event and same Rules Action. That way you can either narrow down your problem, or exclude that as a possible reason why it still doesn't work.
Comment: Thanks, seems logic now when I see it. But ... it doesn't seem to work. When I choose monday, no matter what time, it still evaluates as false. "The condition data_is evaluated to FALSE "

Combining AND and OR in Rules


Image file size on disk?

Question: My app only performs a certain function if an image in external memory has a file size on disk larger than 400KB, so I need to know what the size of the image is, but this
image.getByteCount() / 1024

just returns the size of the decoded Bitmap rather than the file size. I also tried using
image_file.length() / 1024

but this method just return 0 KB. Is there anyway to find the file's actual size on the disk?
Answer:
Is there anyway to find the file's actual size on the disk?

No. Mainly because of compression which may give different results depending on the bitmap content. So in fact means, you need to create the file to figure out how big it is. You can keep that file data in memory and then check disk space prior dumping (or not) that memory to a file.
Note this approach may not work if you need to work with big bitmaps or big images due to risk of running out of memory or hitting memory limits. Still, may be worth checking though.
EDIT

If the image is already a compressed file in external memory is there a way to find it?

If you have the file on disk already, just call length() on it (docs).
Comment: If the image is already a compressed file in external memory is there a way to find it?
Comment: @CalebWhittington If you know where the image actually, why don't you just `stat `? Just open path as file and `file.length()` to fetch it.

Image file size on disk?


Indexers(Smart array)

Question: Our Class Teacher had given us a Program on Indexers(),When i compiled and Execute the Program in my Computer i got error as

Error:1 Operator '<' cannot be applied to operands of type 'int' and
  'method group'

Why i am getting this error??...and Please Explain the Logic of the Program and Why Indexers are used and i am also getting
Runtime Error
        Index was out of range. Must be non-negative and less than the size of the
        collection.
        Parameter name: index
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;
    namespace ConsoleApplication2
    {
        class Program
        {
            ArrayList array = new ArrayList();
            public object this[int index]
            {
                get
                {
                    if (index < 0 || index >= array.Count)
                    {
                        return (null);
                    }
                    else
                    {
                        return (array[index]);
                    }
                }
                set
                {
                    array[index] = value;
                }
            }
        }
        class Demo
        {
            public static void Main()
            {
                Program p = new Program();
                p[0] = "123";
                p[1] = "abc";
                p[2] = "xyz";
                for (int i = 0; i <p.Count ; i++)
                {
                    Console.WriteLine(p[i]);
                }
            }
        }
    }

Comment: You shouldn't use `ArrayList` anymore these days.
Comment: Where do you expect `p.Count` to come from?
Comment: What is p.Count? a method? If so, `i < p.Count()` may help.
Comment: @Jon: Strange that the error message calls `p.Count` a _method group_. `class Program` has no method `Count`.
Comment: @Vlad: Yes, I thought that was odd too. But that's what the OP should at least look at.
Answer: It's failing because the compiler could not find a property named Count. Instead, it found a method—either one which isn't shown here, or if Program implements IEnumerable<object>, then it's likely Linq's Count extension method.
Try adding a Count property to Program
class Program
{
    ...

    public int Count
    {
        get { return this.array.Count; }
    }
}

That will solve the compiler error. Now, if you want to know why it's using indexers… well I suppose because your teacher wanted to illustrate how they can be used. Indexers are just a bit of syntactic sugar which just make writing code like p.GetItem(i) look cleaner, p[i].
Answer: I do not see a Count implementation in you Program. Add the Count implementation and try to re-compile.
    class Program
    {
        ArrayList array = new ArrayList();

        public int Count { get { return array.Count; } }

        public object this[int index]
        {
            get
            {
                if (index < 0 || index >= array.Count)
                {
                    return (null);
                }
                else
                {
                    return (array[index]);
                }
            }
            set
            {
                array[index] = value;
            }
        }
    }

Answer: You should add a Count Property and a constructor that initializes your ArrayList to the correct size, like this:
class Program
{
    ArrayList array = null;

    public Program(int size)
    {
        array = new ArrayList(size);
    }

    public object this[int index]
    {
        get
        {
            if (index < 0 || index >= array.Count)
            {
                return (null);
            }
            else
            {
                return (array[index]);
            }
        }
        set
        {
            array[index] = value;
        }
    }

    public int Count
    {
        get
        {
            return array.Count;
        }
    }
}

Comment: Whz did you tzpe all zour *Y*'s as *Z*'s?
Comment: @p.s.w.g Haha. Sorry, changed keyboard layout without noticing :-)

Indexers(Smart array)


Quadratic form as generalized distance?

Question: In the book A Linear Systems Primer (by Antsaklis and others), they first mention squared distance of a point x from the origin:

$$x^{T}x =  ||{x}||^2$$ which represents the square of the Euclidean
  distance of the state from the equilibrium $x=0$.

So far, so good this is basic linear algebra. Then they go on to say:

In the following discussion, we will employ as a "generalized distance
  function" the quadratic form given by $${x}^TPx  , P={P}^T  $$ where $P$
  is a real $n\times n$ matrix.

I am familiar with this definition of a quadratic form from linear algebra : we interpose a symmetric matrix to weight the variables in different ways.
But I am not familiar with this as a distance function. Is that mainly to say that it satisfies the requirements of a metric space? Is there a geometric (intuitive) discussion of the sense in which the quadratic form generalizes the more basic notion of a distance?
Comment: In general, it might not satisfy the requirements of a metric: unless $P$ is positive definite, distance between $x$ and $y \neq x$ may be zero or negative.
Comment: @neuronet: Thanks for that post, it helped me with a Problem I have. Would you mind taking a look at my question regarding this Topic? I cant find a way to clearify this to me... http://math.stackexchange.com/questions/1634485/is-the-squared-euclidean-norm-a-measure-for-the-distance-of-two-points/1634633#1634633
Comment: @Benvorth I still don't feel I grasped this problem yet, but see my comment to the answer below. The wikipedia page it links to I find largely impenetrable, unfortunately. I think a close study of mahalanobis distance is the way to go, as that has been addressed a lot more, at an intuitive level, and is pretty much a special case of this. I just haven't had time to undertake it yet.
Comment: On mahalanobis distance: https://stats.stackexchange.com/q/62092/17624
Answer: This determines a norm $\|\_\|_P$ iff $P$ is positive definite, then it naturally defines a metric by $d(x,y):=\|y-x\|_P$.
Else the above $d$ function would not be defined or would fail to be a metric, as e.g. there could be $x\ne 0$ with $x^TPx\le0$.
All in all, what it basically says is that the quadratic form $x\mapsto x^TPx$ can be viewed as a generalisation of $x\mapsto \|x\|^2$.
For more details and geometric insights, see for example Pseudo Euclidean spaces.
Comment: That is helpful, I wonder if there is a good discussion of this in a linear algebra context? That wikipedia page is tantalizing if a bit general, its connection to this specific measure gets lost to me fairly quickly. I am starting to think that the mahalanobis distance may be a good route to massage intuitions, as it seems to have been fairly well explored and is the same form as the quadratic form.
Comment: To add to my previous comment: the answers here would probably be really useful: https://stats.stackexchange.com/q/62092/17624
Answer: I think some examples from physics might help provide the geometric (intuitive) sense you seek, in which quadratic forms generalize distance, though I doubt whether it's useful to think of quadratic forms as providing a "more basic notion of distance" in quite the way that I think you're expecting. I see them as providing measures of distance like the usual (Pythagorean/Euclidean) notion of distance, but applied in slightly more general spaces.
A simple example of a generalisation of distance encoded by a quadratic form is given by the Minkowski metric for space-time; for the squared length of a vector from the origin:
$$d^2 = x^2 + y^2 + z^2 –(ct)^2$$
… which I'm sure you can see can be expressed as $X^TPX$ where $P$ is a $4\times 4$ matrix with all off-diagonal elements zero and the diagonal $\{1,1,1,-1\}$.  See also http://mathworld.wolfram.com/MinkowskiMetric.html where the matrix is illustrated.
And so for the slightly less-clear case of a distance between the endpoints of vectors v1 and v2, I think you will now see this also as a quadratic form (using an overly-simplistic notation):
$$d^2(v1-v2) = (x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2 –(ct1-ct2)^2$$
In General Relativity, however, the matrix $P$ is called the Metric Tensor, and can have all non-zero components. As these components can change from point to point, this metric provides for a quadratic form that can encode distances in curved space-times, which is a generalisation of the "flat" Minkowski space-time.
So, as Berci pointed out  via https://en.wikipedia.org/wiki/Pseudo-Euclidean_space , there's a clear geometric interpretation, but it's "simply" a generalisation of the familiar types of distances that apply in Pythagorean/Euclidean/pseudo-Euclidean spaces, rather than a generalisation of the more "disjointed" type that would be needed to include, say, Manhattan, Chessboard or Mahalanobis distances.
(Clearly, I'm not a mathematician, but I think the physics examples help provide the geometric insight you seek, and if I'm wrong in this, would appreciate correction from those more expert. Put into MathJax with assistance acknowledged below.)
Comment: Appreciate the formatting edit, Siong Thye Goh. .

Quadratic form as generalized distance?


Probablility of Rolling unfair dice

Question: Create a table of probabilities for two loaded six-sided dice such that the probability is approximately 0.25 that the sum of the two dice is 7.
Answer: Hint(s):
Note that there are numerous solutions. You just need to exhibit one of them.
Consider two fair dice. The proba that the sum of dice is 7 is $6/36=1/6$.
You want to increase that proba to $1/4$, so you need to get of sum of dice equal to $7$ more often. One idea could be to pick one of the favourable outcomes (say, 3+4) and make it more likely by loading the first die so that it makes 3's more often and the second die so that it makes 4's more often.
You just have to write the parameters to reach an equation...

Probablility of Rolling unfair dice


Bad parameters to mail() function issue in php email

Question: error: Warning: mail() [function.mail]: Bad parameters to mail() function, mail not sent. in /home/content/19/10977719/html/turgut/email/send.php on line 59
i'm trying to send mail with attachments. it shows error.
it works without attachment but i dont need it.
this is not working, same error: http://www.vivekmoyal.in/send-email-attachment-in-php-send-attachment-in-email-php/
this is my php code:
    $upload_name=$_FILES["upload"]["name"];
    $upload_type=$_FILES["upload"]["type"];
    $upload_size=$_FILES["upload"]["size"];
    $upload_temp=$_FILES["upload"]["tmp_name"];

    $fp = fopen($upload_temp, "rb");
    $file = fread($fp, $upload_size);

    $file = chunk_split(base64_encode($file));
    $num = md5(time());

$ad     = $_POST['ad'];
$email  = $_POST['email'];
$r_email  = $_POST['r_email'];
$msg    = $_POST['msg'];
$subject    = $_POST['konu'];

       $headers  .= "MIME-Version: 1.0\r\n";
       $headers  .= "Content-Type: multipart/mixed; ";
       $headers  .= "boundary=".$num."\r\n";
       $headers  .= "--$num\r\n";

       // spamden kaçmak için bir yöntem

       $headers .= "Message-ID: <".gettimeofday()." TheSystem@".$_SERVER['SERVER_NAME'].">\r\n";
       $headers .= "X-Mailer: PHP v".phpversion()."\r\n";

                // With message

    $headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
       $headers .= "Content-Transfer-Encoding: 8bit\r\n";
       $headers .= "".$msg."\n";
       $headers .= "--".$num."\n";

        // Attachment headers

    $headers  .= "Content-Type:".$upload_type." ";
       $headers  .= "name=\"".$upload_name."\"r\n";
       $headers  .= "Content-Transfer-Encoding: base64\r\n";
       $headers  .= "Content-Disposition: attachment; ";
       $headers  .= "filename=\"".$upload_name."\"\r\n\n";
       $headers  .= "".$file."\r\n";
       $headers  .= "--".$num."--";

$mailsonuc = mail("$r_email","$subject","$msg", $headers);

this is html:
<form id="attach" name="attach" action="gonder.php" method="post" enctype="multipart/form-data">

{TOP_MSG}

        {NAME}
        :
        <input type="text" placeholder="Adınız Soyadınız" required name="ad" />

        {SENDER}
        :
        <input type="text" placeholder="E-Posta Adresiniz" required name="email" />

        {RECEIVER}
        :
        <input type="text" placeholder="Alıcı E-Posta Adresi" required name="r_email" />

        {KONU}
        :
        <textarea name="konu"  required="" cols="46" rows="1"></textarea>

        {MESSAGE}
        :
        <textarea name="msg"  required="" cols="46" rows="7"></textarea>

        {EK}
        :
         <input type="file" name="upload" id="upload">

                <input type="submit" value="Gönder" id="send" name="send" />

        </form>

Comment: @guybennet another thing. I'm not going to continue re-checking this thread. If you're going to reply to my comments, add the **@** symbol including my name. I.e. **@Fred**.
Comment: One does not simply use `mail()` directly. You should consider a more robust/stable solution [swiftmailer](http://swiftmailer.org/).
Comment: It might help if you told us what the error you're seeing is.
Comment: Unless you're not showing us your entire code, your first `$headers` should not start with a dot. You have `$headers  .= "MIME-Version: 1.0\r\n";`. If that is in fact your first header, then remove the dot and replace with this `$headers  = "MIME-Version: 1.0\r\n";`. (for one thing). Also, show us the code that is on line 59, also the lines before, and after it.
Comment: What is the reference to `$mailsonuc`? I only see it once in your posted code. You're obviously not showing us your entire code.
Comment: yeah there is 1 line before this code.
it is: $headers  = "From: Info Mail\r\n";
and
line 59: $mailsonuc=mail($to, $subject, $message, $headers);
Comment: @guybennet You haven't defined the `$to` variable, that's probably why you're getting errors.
Comment: @guybennet You say line 59 is `$mailsonuc=mail($to, $subject, $message, $headers);` yet your code reads as `$mailsonuc = mail("$r_email","$subject","$msg", $headers);`. **Which one is it?** **Change** `$mailsonuc=mail($to, $subject, $message, $headers);` **to** `$mailsonuc = mail("$r_email","$subject","$msg", $headers);`, try it and get back to me.
Comment: @guybennet Or, add/define `$to` such as `$to = your_email@your_site.com;`
Comment: @Fred now it sends mail but you cant open file. it sends same name and size. i think its broken
Comment: @guybennet What do you mean by *"it can't open the file and it sends same name and size"*? What are you trying to achieve; what are your expected results?
Comment: @Fred The e-mail was sent with an attached ,but the attachment gets corrupted. you cant open file.
Comment: @guybennet Sorry, but that's not a topic which I know much about. I suggest you post another question about it.
Answer: I think you issues based on minor mistake only.

Check your PHP version
Mail your hosting company and report it to them.
Try removing the Bcc: Header's and see if that work's.

simply search result
Refer this link too:
This is example for fileupload
other wise, please don't build your own MIME emails. Use PHPMailer or Swiftmailer, which do almost everything for you. You can replace you entire script with about 5 or 6 lines of code.
unless you can
Refer this links also
Answer: I had the same issue and noticed that I had HTML character
 in the subject line. Once removed, it worked.


Exchange API Azure - Mailbox access ('full_access_as_app' is a major problem, how to scope to specific mailboxes)

Question: I'm currently accessing Exchange API through OAuth access token.
However I had to select
'full_access_as_app by using Exchange Web Services with full access to all mailboxes'
Is it possible to restrict the scope of mailboxes in this scenario?
Answer: You might switch to MS Graph and use Application Access Policies which allows you to limit access to a specific set of mailboxes or none.
Comment: Exchange Online does not currently support ApplicationAccessPolicies for EWS's full_access_as_app scope.
Comment: @Alfredo -  Issue we're facing is : Application Access Policies only works with 'Graph API' and not the 'Exchange API'
Comment: @Sivaprakash -MSFT:  Is there is no other way to control the specific mailboxes the app can access? Considering, 'full_access_as_app' seems to be a major issue with our client
Answer: As of 02/02/21 this is no longer a limitation of EWS. Based on this announcement, Application Access Policies can now be used in conjunction with EWS API OAuth based application access.

Using an application access policy, EWS administrators can now limit an app's access to a specific set of mailboxes by specifying an inclusion or exclusion list. Administrators who want to limit third party app access to a specific set of mailboxes can use New-ApplicationAccessPolicy PowerShell cmdlet to configure access control. For more information about application access policies, see Scoping application permissions to specific Exchange Online mailboxes.


'<' not supported between instances of 'tuple' and 'int'

Question: Python baby is stuck in the code. I know its childish thing but you know error is error I have no option instead to put it.
<code>count=0,
    while(count<5):
        count=count+1
        count
</code>
Comment: Can you show more of your code? Why do you have a comma there next to `count=0`?
Comment: `0,`  means `count=(0,)` which is a completely different thing from `count=0`.
Answer: First, you don't need comma next to count 0
Second, if you need to print count put print(count) instead of just count
Comment: "First, you ~~don't need~~ _must not put_ comma next to count 0"
Comment: Thanks for All of you. @Ash Duffy Zac


SQL - update table from another table - syntax error

Question: I have two SQL tables:
matches (columns are hometeam, awayteam, id, gameweek)
teams (columns are teamcode, teamname)

matches.hometeam and matches.awayteam consist of integers that correspond to integers in teams.teamcode. I am trying to get matches.hometeam and matches.awayteam to update to strings that are taken from corresponding strings in teams.teamname. If that is impossible, then I need to create a new table as described.
I have tried the below code, but it produces a syntax error on the penultimate two lines (error 1064 (42000)). I can't figure out why.
UPDATE matches
SET matches.hometeam = teams.teamname
FROM matches
INNER JOIN teams
ON (matches.hometeam = teams.teamcode);

Comment: _"matches.hometeam ... consist of integers"_, _"trying to get matches.hometeam ... to update to strings"_ - You can't put a string into an integer column
Comment: Do you have any foreign or primary keys? Do you care about the names of the columns at the end of the process? Are you certain that you _should_ do the thing that you're _trying_ to do?
Answer: Error 1064 is a MySQL error.  If you are using MySQL, the correct syntax is:
UPDATE matches m JOIN
       teams t
       ON m.hometeam = t.teamcode
    SET m.hometeam = t.teamname;

However, this will not really work.  What you need to do is add ids:
alter table matches add hometeamcode int;

And then do:
UPDATE matches m JOIN
       teams t
       ON m.hometeam = t.teamcode
    SET m.hometeamcode = t.teamname;

EDIT:
I think I misunderstood the whole situation.  Your data model is totally correct.  The matches table should have the integer codes, referring to the rows in teams.
You just need to write your query to get the names:
select m.*, th.teamname as hometeamname, ta.teamname as awayteamname
from matches m join
     team th
     on m.hometeam = th.teamcode join
     team ta
     on a.hometeam = ta.teamcode;

If you don't want to do the join, then encapsulate the logic in the view.
Comment: This shows the correct approach: Add a new column with the correct type, then set its value. The choice of name for the new column(s) is probably wrong; it should be `hometeam_name`, right? Rinse and repeat for the away teams.


How can I access Scala implicit functions like toInt() as function objects?

Question: I'm trying to write a general-purpose String converter function that takes a string and a conversion function and applies the function to the string:
def convertString[A](s: String, f: String => A): A = f(s)

I'm trying to pass the toInt function as f, but my IDE keeps complaining that it Cannot resolve symbol toInt.
How do I get access to toInt as a function object that I can work with like any other function?
Comment: `convertString("4", _.toInt)` is valid code, don't know what you tried.
Answer: (_: String).toInt works:
scala> val myStr = "4"
scala> convertString(myStr, (_: String).toInt)
res0: Int = 4

Basically, we need to force Scala to implicitly cast the input String object to a StringOps object, then call toInt on that StringOps object. Unpacking the magic, we can try the following:
scala> val f = (_: String).toInt
f: String => Int = <function1>

We have to specify that the input type is a String, and then Scala takes care of implicitly casting the String to StringOps when toInt is called. This is equivalent to saying
scala> def f: String => Int = _.toInt

but is more concise.


How to use a for loop to make multiple graphs of each mean of a column of data per site

Question: I have a data frame with 20 sites (i.e. levels) and ~ 60 columns of relative abundance of microbial families. I am trying to create a for loop that will find the mean of each family per site. I've been able to do it for one family (see code below) but am not sure how to make a for loop that will automate the process for the rest of the families. Thanks for any help!
data.subset = data.all %>%
  select(Site, Enterobacteriaceae) %>%
  group_by(Site) %>%
  summarise(mean(Enterobacteriaceae))

data.subset

pcm = melt(data.subset, id = c("Site"))

pcm$Site <- factor(pcm$Site,levels=unique(pcm$Site))

pcm$Site <- factor(pcm$Site,levels=c("1","2","3","4","5","6", "7","8", "9", "10","11","12","13","14","15","16","17","18","19","20","C1", "C2","C3","S1","S2","S3","OF-1","OF-2","OF-3","Effluent","Influent"))

ggplot(pcm, aes(x = Site, fill = variable, y = value)) +
    geom_bar(stat = "identity", colour = "black")

Comment: `melt` data first, aggregate by *Family* and *Site*, and then `ggplot` with `facet_wrap` by *Family*.
Answer: You can use summarize(across()) from dplyr to get the mean for each of the (60) columns of bacterial families, and then pivot this longer.  Notice that in across(), I use starts_with("F") to identify the columns, but that is because I have named the columns F1, F2, F3, ... F60... Yours might be a range of consecutive columns such as Enterobactae:Klebsiella, for example.
library(tidyverse)
data.subset = data.all %>%
  group_by(Site) %>%
  summarise(across(starts_with("F"), ~mean(.x, na.rm=T),.names = "{.col}")) %>%
  pivot_longer(-Site, names_to = "Family", values_to = "Relative Abundance")

Then, you can use facet_wrap to plot a bar plot similar to the one you showed in your original post
ggplot(data.subset, aes(x = Site, y =`Relative Abundance`, fill=Family, color=Family )) +
  geom_bar(stat = "identity") +
  facet_wrap(~Family) +
  guides(color="none", fill="none")

Input Data:
set.seed(123)
data.all = data.frame(
  Site = rep(c(1:20), times=30)
)
data.all = cbind(data.all, setNames(as.data.frame(lapply(1:60, function(x) rnorm(600))), paste0("F",str_pad(1:60, width=2,pad = "0"))))