Melody using a different scale than the bassline - what is it called?

Question: Since I only know some very rudimentary terms in music theory, I don't know what
it's called when one does the following to create a sort-of interesting sound.
Suppose I'm playing the piano, using my left hand to repeatedly hit the note C
as a very simple bass line to give the key of my song (C major). Then I use my right hand
to play a melody that fits within the key, but instead of playing notes in the
C scale to get a 'cleanly fitting' sound I rather go for playing the melody using
the G scale, creating a slightly unusual deviation from what one would expect
from a song in the C key.
When I try this out, it creates a sound that I recognize from some songs (for instance
the intro song in Disney's Beauty and the Beast uses this kind of 'harmonization' when the villagers greet each other) and the sound feels so natural that I think that the concept of playing the melody
in a different scale than the 'expected one', given the key, should be somewhat well known/understood.
Does this kind of 'harmonization' have a name (in the case where we use the dominant (V) scale instead of the scale indicated by the key (I))? And more generally, are other scales than (V) in the melody commonly used to create a 'special feel' to a song?
Comment: The way the question is phrased, the bassline is hardly using a **scale**. One note is a drone or ostinato, and could be major or minor, so not a scale as such.
Comment: The G scale has C in it.
Comment: Shouldn't we close this question, wait for clarification fixing the discrepancy between text and title and only then answer it?
Comment: @Kaz Yes G has C in it, but if you put the C in the left hand, the overall tonality becomes C. G/C = C major 9. F/G = Gsus9, Db/G=G(b9)(#11) etc. In all these cases one note in the bass sets the overall tonality. The OP is asking about these kinds of cases, with one overall tonality, and a different one in the right hand. As many answers explain, it's called "bitonality", and extremely common in pop music.
Answer:
Suppose I'm playing the piano, using my left hand to repeatedly hit the note C as a very simple bass line to give the key of my song (C major). Then I use my right hand to ... [play] the melody using the G scale...

If you're playing notes as found in the G major scale in the right hand, but establishing C as your home note in the bass (without further establishing a different scale in the bass), you are effectively putting yourself not in C major, but in C Lydian (C D E F# G A B).
Your example there though is arguably not quite what's described in the title of the question (Melody using a different scale than the bassline) - If you genuinely and consciously use two different scales, then you are into the world of polytonality. But as per my first sentence, I think what your example describes is more simply looked at as use of a mode.

And more generally, are other scales than (V) in the melody commonly used to create a 'special feel' to a song?

Again, if we're talking about (modern) modes - there are seven of them, one of which corresponds to the major scale, one of which corresponds to the natural minor, and 5 others. Apart from perhaps the Locrian mode, there are well-known examples of all of them. If we explain your example in terms of modes, then rather than thinking of it as V in the melody, we might also think of it as the major scale but with IV as the home note.
Answer: This may not be exactly in line with your particular example, but there is a phenomenon known as the melodic-harmonic "divorce" in rock music. It basically states that the sung melodies in rock/pop music are often at odds with the tonality implied by the accompanying harmonies. One famous article explaining this concept, if you're interested, can be found here.
Answer: Kind of depends on which of your two scenarios we're supposed to answer for.
In the title, you state that two different "scales" are in use.  This makes the answer to your question Polytonality.  Exactly what it says on the box, polytonality is the use in a section or piece of music of two or more different keys.
Anyone who used the Schaum piano method when learning to play ought to remember Henry's Hennery! In this case, G-maj melody & F#-maj bass line.
In the body of your question, you're just hitting a C over and over again. This is no longer really a bass line per so, playing just one constant note makes this a drone plain and simple. Much like this musette. In this case, polytonality, modes and so forth will never even figure into the picture!
Comment: The OP's example probably cannot be considered polytonal, as the LH is only playing one note (not a full scale) and that note is part of the scale being using in the RH.
Comment: @Max - Thanks for pointing that out! Though in fairness, the title question's answer I think is polytonality.
Answer: While the Lydian mode comes immediately to mind - C Lydian varying from C major by only F♯ instead of F - as mentioned in topo's answer, another thought occurred.
That F♯ could be considered as G♭, which happens to be the flat five that dwells in a lot of blues. Thus giving a slight blues tinge to the melody. Blues will use F, G♭ and G♮ from the note pool, but that 'odd' note hints at blues.
Lydian is used a lot in Jazz, where the changed note is usually referred to technically as ♯4, whereas in blues, the very same note is usually called ♭5.
EDIT: regarding your last question - yes the idea gets used quite a bit. Imagine you use the scale notes from key C major. There are six other ways to use those notes, resulting in different flavours to pieces. Tonic C - Ionian mode/ major. Tonic D - Dorian mode, a minor feel. Tonic E - Phrygian mode - another minor feel. Tonic F - Lydian mode, where your 'playing in G' comes from. Tonic G - Mixolydian mode, with a m7 note, sounds a little bluesy. Tonic A - Aeolian mode, the natural minor. Tonic B - Locrian mode - a somewhat weird sounding key, not really stable.
Answer: Phrases or melodies in two different keys are bitonal, as in Charles Ives' Three Places in New England in which two marching bands pass each other while playing two different marches in different keys.  Some composers use an bitonal approach consistently as their style (Copeland, for example).
Answer: Actually, since you ask for a specific song (and mention that there are "many others which feel the same"), then the other answers are wrong :) There's neither lydian scale nor modal harmony, nor bitonality in the intro of "Beauty and the Beast".
What you ask for is the "pedal note" or the "pedal point", a very common device (both in archaic music, where it's known as burdon, and in modern popular music), which is all about leaving a single, strong note in bass for extended duration, while the harmony shifts and changes above it. Sometimes (not always) it's noted with slash chords (e.g. C F/C G/C F/C would make a nice pop vamp on the piano).


Join multiple tables used as Indexing - Laravel

Question: I have three tables - Chairman, Designation, Members.
MY requirement is to map the member to chairman and assign member a role.
I was able to fetch the list of members under the chairman when I had chairman_id and designation_id in the members table.
Since the chairman change, most of the members stay intact. So I came up with an idea of indexing them

Table - membermap
id | chairman_id | designation_id | member_id

So the list is preserved how many chairmans come and go. I dont need to create new profile for new chairman rather than map to it.
I am now sure how do I do it,
So far I was able to pull the ID but I am not sure how do I join the tables
Tables
Chairman
id| name

Designation
id|designation

Members
id|members

Here is my controller
$mapmember = Statechairman::findOrFail($id)->statechairmembersmap;
dd($mapmember);

In this Iam getting the statechairmembersmap but it's fetching all the result and not limiting the match.
I also tried to join the query using the DB
$mapmember = DB::table('statechairmen')
       ->join('state_chairman_members_maps', 'state_chairman_members_maps.chairman_id','statechairmen.id')
       ->join('statemembers','statemembers.id','state_chairman_members_maps.members_id')
       ->select('state_chairman_members_maps.*')->get();

   but this result show me the  Table - membermap but not the other results.

My Models:
Chairman :
public function statechairmembersmap(){

  return $this->hasMany('App\StateChairmanMembersMap','chairman_id','id');
}

public function statemembers(){
    return $this->hasMany('App\Statemembers','chairman_id', 'id');
}

public function statedesignation(){
    return $this->hasMany('App\Statedesignation','id','designation_id');
}

membermap:
protected $table = 'state_chairman_members_maps';
    protected $dates = ['deleted_at'];

    public function statechairman(){
        return $this->belongsTo('App\Statechairman','id');
    }

     public function statedesignations(){
         return $this->belongsTo('App\Statedesignation','designation_id','id');
     }

    public function statemembers(){
        return $this->belongsTo('App\Statemembers','members_id','id');
    }

Please assist me where I doing wrong.
Comment: add `, '=',` in between join queries
Comment: @ViperTecPro I added ,'=' but it not working,
$mapmember = DB::table('statechairmen')
       ->join('state_chairman_members_maps', 'state_chairman_members_maps.chairman_id','=', 'statechairmen.id')
       ->join('statemembers','statemembers.id','=', 'state_chairman_members_maps.members_id')
       ->select('state_chairman_members_maps.*')->get();

It is still showing me only StateChairmanMembersMap table result
Answer: Thanks a lot for checking the question out.
Finally after a lot of strugle, I was able to find it by myself.
 $mapmembers = DB::table('state_chairman_members_maps')
    ->join('statechairmen','statechairmen.id','=','state_chairman_members_maps.chairman_id')
    ->join('statemembers','statemembers.id','=','state_chairman_members_maps.members_id')
    ->join('statedesignations','statedesignations.id','=','state_chairman_members_maps.designation_id')
    ->where('chairman_id','=',$id)
    ->get();

Here is what I came up with.
Here I have joined 3 tables and mapped the id comming from the chairman to filter the result. I getting the results.


Como inserir um arquivo HTML com o [innerHtml] e manter os atributos do Angular

Question: Em meu Componente eu recebo um HTML em forma de String e uso o [innerHtml] para inserir esse HTML na View do Component.
Component:
test(){
    alert('Teste :D');
}

html_string = '<input type="button" (click)="test()">';

View:

O problema que estou enfrentado é que no momento em que a pagina carrega, ela ignora o (click)="teste()". No final ele acaba ficando no elemento, já outros que estão direto na View, no final somem do elemento.
E eu faço a validação com o sanitizer.
Answer: Atualização 2
Caso não queira fazer o uso de biblioteca, você pode usar a classe Compiler ( Obs.: Não confundir com $compile do AngularJS )
Arquivo app.component.ts
import { Compiler, Component, Injector, NgModule, NgModuleRef, ViewChild, ViewContainerRef } from "@angular/core";

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('testando', { read: ViewContainerRef }) _container: ViewContainerRef;
  constructor(private _compiler: Compiler, private _injector: Injector, private _m: NgModuleRef<any>) { }

  test() {
    alert('Teste :D');
  }

  ngAfterViewInit() {
    const html_string = '<input type="button" (click)="test()" value={{btnValue}}>';
    const tmpCmp = Component({ template: html_string })(class { });
    const tmpModule = NgModule({ declarations: [tmpCmp] })(class { });

    this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
      .then((factories) => {
        const f = factories.componentFactories[0];
        const cmpRef = f.create(this._injector, [], null, this._m);
        cmpRef.instance.btnValue = 'CLIQUE!';
        cmpRef.instance.test = this.test;
        this._container.insert(cmpRef.hostView);
      })
  }
}

Arquivo app.component.html

Veja funcionando em stackblitz
O exemplo acima foi adaptado do artigo: Here is what you need to know about dynamic components in Angular. ( Aqui está o que você precisa saber sobre componentes dinâmicos em Angular - Tradução livre. )

Atualização 1
Fazendo uma pesquisa no Google, encontrei a biblioteca p3x-angular-compile.
Para utilizar, basta seguir os passos:

Importar a biblioteca no arquivo app.module.ts
import { CompileModule} from 'p3x-angular-compile';

Configurar o modulo:
@NgModule({
  imports: [ ... CompileModule],
  ...
})

Código do template:

Usar seu componente normalmente assim como esta na pergunta, com a exceção que os eventos devem ser precedidos por context.:
html_string = `<input type="button" (click)="context.test('wmsouza')" value="CLIQUE AQUI!">`;

test(nome) {
  alert(`Olá, ${nome}`);
}

Podes ver funcionando em stackblitz

Isso não é possível, pois a subclasse DomSanitizer simplesmente ignora, a solução seria utilizar o método addEventListener para registrar um evento no elemento.
import { Component, ChangeDetectorRef, ElementRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  html_string;

  constructor(private sanitizer: DomSanitizer, private elRef: ElementRef, private cdRef: ChangeDetectorRef) { }

  test = (nome) => {
    alert(`Olá, ${nome}`);
  }

  ngOnInit() {
    this.html_string = this.sanitizer.bypassSecurityTrustHtml('<input type="button" value="CLIQUE AQUI!">');
    this.cdRef.detectChanges();
    this.elRef.nativeElement.querySelector('input').addEventListener('click', _ => { this.test('wmsouza') }, false);
  }
}

Veja funcionando em stackblitz
Answer: Muito simples, utilize o $compile:
Coloque ele no seu app.controller:
app.controller('MainController', function($scope, $http, $rootScope, $compile) {

...
Faça o APPEND do HTML assim:
var elementoHTML = document.getElementById("elemento");
angular.element(elementoHTML).html( $compile(response.data)($scope) );


How do I set up VSCode to put curly braces on a new line in C# and C++ while typing?

Question: I want VS Code to put curly braces on a new line in C# and C++
How it works now

How it should look

Tried C# FixFormat extension, but it works only after I push CTRL+K+F
but I want VS Code to make curly braces on new lines while I'm coding,
without additional steps like hotkeys and such
Answer: Now that C#FixFormat has been removed, try putting an omnisharp.json file in the root of your project with the following.
{
    "FormattingOptions": {
        "NewLinesForBracesInLambdaExpressionBody": false,
        "NewLinesForBracesInAnonymousMethods": false,
        "NewLinesForBracesInAnonymousTypes": false,
        "NewLinesForBracesInControlBlocks": false,
        "NewLinesForBracesInTypes": false,
        "NewLinesForBracesInMethods": false,
        "NewLinesForBracesInProperties": false,
        "NewLinesForBracesInObjectCollectionArrayInitializers": false,
        "NewLinesForBracesInAccessors": false,
        "NewLineForElse": false,
        "NewLineForCatch": false,
        "NewLineForFinally": false
    }
}

Comment: Note that as of Omnisharp 1.39.2 (in VS Code C# extension 1.25.1) an `omnisharp.json` file may not be honored unless you go to the VS Code settings and set `"omnisharp.enableEditorConfigSupport"` to false. Either that, or use a `.editorConfig` file instead. https://github.com/OmniSharp/omnisharp-vscode/issues/5446#issuecomment-1308655891
Answer: In my case, I was using the C# extension by Microsoft (3.5 stars). By default, this extension uses its default C# formatter. Disable the formatting option as shown below, and you won't get any for formatting, including the annoying NewLinesForBracesInMethods. Alternatively you can try to tweak the C# extension formatter. More info here.
So I replaced it with the C# FixFormat (5 stars) extension. This seems to work straight of the box for me.
But then I realised, I wasn't getting autocomplete, so I reinstalled the C# extension by microsoft, and kept the FixFormat extension. And it works great, no new lines for braces.
Comment: How do I do this now that C# FixFormat is gone?
Answer: Finish your code as it is, then Shift+Alt+F (or select from the menu by the right click) will auto-format everything. No need for anything else :-)
Answer: As of 2023, the C# Curly Formatter extension seems to work for me!
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/34506189)
Answer: On VSCode, Go to File\Preferences\Settings and search for 'curly'. Enable all four typescripts as given in the image.
Comment: Tried this already, seems like it doesn't affect C# and C++ formatting
Comment: I just got it to work, but not quite the way I wanted. I added the extension "c# fixformat" which doesnt change the default behavior of code completion, or at least not yet anyway, but if you say format document it will let you pick that and then it will put the { on the next line.. but what a polava
Comment: Didnt change for me either, one of the many things that annoy me about vs code is that somethings seem frustrating to get the way you want..   It could be yet another extension is interfering with it.
Comment: @BugFinder it works fine for me but you are right, it could be an interference with another extension.
Comment: I tried this settings with all extensions except C# disabled, but still braces are on the same line
Comment: I just removed it and installed visual studio community version. I hate to say that Visual studio code is not good
Answer:
From Preferences/Settings, choose c# FixFormat and uncheck the checkbox (Braces: On Same Line).
Answer: If you want to add this globally you could do the following:

open the directory: $HOME/.omnisharp (or create the directory if it does not already exist)
create a file in said directory called: omnisharp.json
paste the content from @thornebrandt's answer and save the file
go into VS Code and format the code with alt + shift + f

{
    "FormattingOptions": {
        "NewLinesForBracesInLambdaExpressionBody": false,
        "NewLinesForBracesInAnonymousMethods": false,
        "NewLinesForBracesInAnonymousTypes": false,
        "NewLinesForBracesInControlBlocks": false,
        "NewLinesForBracesInTypes": false,
        "NewLinesForBracesInMethods": false,
        "NewLinesForBracesInProperties": false,
        "NewLinesForBracesInObjectCollectionArrayInitializers": false,
        "NewLinesForBracesInAccessors": false,
        "NewLineForElse": false,
        "NewLineForCatch": false,
        "NewLineForFinally": false
    }
}

Answer: I've VSCode 1.87 & the plugins C# v2.22.3 + Prettier v10.1.0 installed.
I had to add in my VSCode settings.json this:
"[csharp]": {
  "editor.defaultFormatter": "ms-dotnettools.csharp"
},

And create the file .editorconfig in the root of my project containing the formatting options I needed:
###############################
# C# Formatting Rules         #
###############################
# New line preferences
csharp_new_line_before_open_brace = false
csharp_new_line_before_else = false
csharp_new_line_before_catch = false
csharp_new_line_before_finally = false
csharp_new_line_before_members_in_object_initializers = false
csharp_new_line_before_members_in_anonymous_types = false
csharp_new_line_between_query_expression_clauses = false

You can found more options there to config your C# project: https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/code-style-rule-options?view=vs-2022
Then, is you have format on save enabled it should update your file!
Or do Cmd+Shift+P>Format Document to manually try it.


LMM: How do I calculate a standard deviation on the variance explained by fixed effects?

Question: So, building a LMM with the lmer function in lme4, you get the variance explained by the variance component.
summary(esoph) # data on esophageal cancer from 'datasets' package

     agegp          alcgp         tobgp        ncases         ncontrols
  25-34:15   0-39g/day:23   0-9g/day:24   Min.   : 0.000   Min.   : 1.00
  35-44:15   40-79    :23   10-19   :24   1st Qu.: 0.000   1st Qu.: 3.00
  45-54:16   80-119   :21   20-29   :20   Median : 1.000   Median : 6.00
  55-64:16   120+     :21   30+     :20   Mean   : 2.273   Mean   :11.08
  65-74:15                                3rd Qu.: 4.000   3rd Qu.:14.00
  75+  :11                                Max.   :17.000   Max.   :60.00

# Just a hypothetical mixed model
m1 <- lmer(ncase~ncontrols+(1|tobgp)+(1|agegp), data=esoph, REML=F)
summary(m1)

Linear mixed model fit by maximum likelihood  ['lmerMod']
Formula: ncases ~ ncontrols + (1 | tobgp) + (1 | agegp)
   Data: esoph

     AIC      BIC   logLik deviance df.resid
   404.0    416.4   -197.0    394.0       83

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.0267 -0.4770 -0.0704  0.3030  5.8282

Random effects:
 Groups   Name        Variance Std.Dev.
 agegp    (Intercept) 2.2809   1.5103
 tobgp    (Intercept) 0.0293   0.1712
 Residual             4.4311   2.1050
Number of obs: 88, groups:  agegp, 6; tobgp, 4

Fixed effects:
            Estimate Std. Error t value
(Intercept)  1.65533    0.69209   2.392
ncontrols    0.05022    0.01882   2.668

I get the standard deviation for each of my variance components. Let's say I want to compute variance explained by my fixed effects (code from here):
(VarF <- var(as.vector(lme4::fixef(m1) %*% t(m1@pp$X))))
# 0.4082163

Great! That's useful information! How do I go about calculating the standard deviation for this variance estimate?
Comment: I believe something like `sqrt(diag(X %*% vcov(m1) %*% t(X)))` will do it (I may have the transposition in the wrong place)
Comment: One option is a parametric bootstrap (for this, and many derived quantities). You can use the `bootMer()` function in `lme4`, passing the function you give above, then calculate the standard deviation of the bootstrap replicates; this will approximate the standard error of the statistic of interest. For example, `vfix<-function(m) var(as.vector(fixef(m1) %*% t(m1@pp$X))); samples<-bootMer(m1, FUN=vfix, nsim=999); sd(samples$t)`
Comment: In a non-mixed effects model, the 'variance explained' is $R^2$. Are you asking about the analog of $R^2$ for LMMs, & how to get a standard error for $R^2$?
Comment: gung, I'm using the Marginal and Conditional R^2 from Nakagawa and Schielzeth (2013). It's a little unconventional, but I want to compare response magnitude between fixed and random effects (so show the variance explained from the fixed effects components along with variance explained by random effects, just as a bar graph instead of as a ratio).
Comment: `getME(m1,"X")` is simpler and more reliable than `m1@pp$X` ...
Answer: The std deviations given in the summary for a linear mixed model are not the std deviation for the variance estimates, they are just the estimates for the std deviation of the effects themselves, that is the square-roots of the variance estimates.
Thus, even if you calculate the std deviation of the fixed-effects variance estimate, you will not be able to compare the fixed and random variances on a graph using the random std deviations given by the summary.


How to disable geo loadbalancing in Google Cloud Load Balancer (non-Classic) HTTPS?

Question: We are using GCP load balancer non-Classic HTTPS.  We have two instance groups, one in Central and one in East.  Right now it is sending all incoming traffic to only the nearest instance group.  We actually want to turn off geo loadbalancing and just round-robbin the traffic across ALL instance groups.
How do we actually do that?  This is not obvious from UI and documentation
Comment: Is there a reason you want to do this?  While the Global LB prefers to route to the closest region to the client, it will also route to the next (nearest) region if there is no capacity in the nearest region.   Have a look at https://cloud.google.com/load-balancing/docs/backend-service#target-capacity
Comment: @GariSingh Yeah this is basic.  Azure Front Door, for example, can do this.  This is yet another example of a non-obvious limitation in GCP that matters
Comment: Could you point me to how you'd do this with Azure Front Door?  I don't see how you'd do this there either.
Answer: There is a workaround available for this issue. You need to recreate a new load balancer for your instance group and need to reconfigure it with your desired functionalities (round robin algorithm in your case). However if you are trying to edit your existing load balancer's config as of now there is no way, there is a similar issue and a feature request has been raised with google team for it for more updates.
Comment: Thanks - I am happy to create a new one.  Which screen do I select "Round Robin" in?  I tried searching around and didn't see it in the create flow but maybe I just missed it
Comment: In GCP each type of load balancer by default supports a particular algorithm for more information go through [load balancing methods](https://cloud.google.com/load-balancing/docs/features#load_balancing_methods) documentation.
Comment: Thanks - OK I am looking at the screen for a new HTTPS Load Balancer Backend Configuration.  There is a setting in Advanced called "Locality load balancing policy*".  The default choice is Round Robin.  However, there is no choice to NOT do locality load balancing at all and just do a pure Round Robin.  Am I missing something?  They all seem to be Locality Aware?  I think this just sets what to use within a locality, but I want to configure how it decides which locality.
Comment: If you are okay with using multiple load balancers, you can create an external load balancer and redirect the traffic to a regional LB for performing your round robin operations.
Comment: Thanks - wouldn't that still geo-route to the closest region though?
Comment: No you can use path based routing like for "EU" specify one path and for "US"  specify one path eg: eu.example.com and us.example.com.
Comment: But I don't want to do that.  I just want it to round robin across all regions.  Btw Azure front door can do this - it's pretty standard.


Formula for $\Phi_{3p}(x)$

Question: While I was experimenting with cyclotomic polynomials , denoted as $\Phi_n(x)$ , I came up with the following formula for $\Phi_{3p}(x)$ , where $p$ is a prime number greater than $3$ :

$$\Phi_{3p}(x)=\displaystyle\sum_{i=0}^{p-1}\left(i+1-3\left\lfloor \frac{i+2}{3} \right\rfloor\right) \cdot \left(x^i+x^{2(p-1)-i}\right)-(-1)^{\left\lfloor \frac{1}{3}\left(p-6\left\lfloor \frac{p}{6} \right\rfloor\right) \right\rfloor} \cdot x^{p-1}$$

I have verified this formula for $p \in [5,4999]$ .
Question. Is there an easy way to justify this formula?
Comment: Perhaps if you explained how you worked out the formula, it might help someone be able to explain why it holds
Comment: @P [As is stated here](https://en.wikipedia.org/wiki/Cyclotomic_polynomial#Easy_cases_for_computation), we have
$$
\Phi_{3p}(x) = \frac{\Phi_p(x^3)}{\Phi_p(x)} = \frac{\Phi_3(x^p)}{\Phi_3(x)}.
$$
I suspect that this can be used to derive your formula.
Comment: @P The summation formula is difficult to parse. Could you please write it in the form
$$
\Phi_{3p}(x) = a_0(x^0 + x^{2(p-1)}) + a_1(x^1 + x^{2(p-1)-1}) + \cdots?
$$
Comment: @Moko19 Looking at few cyclotomic polynomials of the given form with small $p$ I noticed a pattern in forming of polynomial terms.
Comment: @BenGrossmann Both $\Phi_{p}(x)$ and $\Phi_{2p}(x)$ are  expressible in the form of the single sum , that's why I wanted to express $\Phi_{3p}(x)$ in the similar form
Answer: For prime $p>3$,
$$\Phi_{3p}(x)=\frac{1+x^p+x^{2p}}{1+x+x^2}=\frac{1-x+x^p-x^{p+1}+x^{2p}-x^{2p+1}}{1-x^3}.$$If $p\equiv1\pmod 3$ then
\begin{align}
\Phi_{3p}(x)&=\frac{1-x^{2p+1}}{1-x^3}
-\frac{x-x^p}{1-x^3}-\frac{x^{p+1}-x^{2p}}{1-x^3}\\
&=(1+x^3+\cdots+x^{2p-2})-(x+x^4+\cdots+x^{p-3})-(x^{p+1}+x^{p+4}+\cdots+x^{2p-3})
\end{align}
and if $p\equiv2\pmod 3$ then
\begin{align}
\Phi_{3p}(x)&=\frac{1-x^{p+1}}{1-x^3}
-\frac{x-x^{2p}}{1-x^3}+\frac{x^p-x^{2p+1}}{1-x^3}\\
&=(1+x^3+\cdots+x^{p-2})-(x+x^4+\cdots+x^{2p-3})+(x^p+x^{p+3}+\cdots+x^{2p-2}).
\end{align}
Do these accord with your formula?
Comment: I think they do accord.

Formula for $\Phi_{3p}(x)$


Wait for pending Promises before rendering the Page

Question: I am currently working on a webproject for a Twitch-Community in node.js. I'm using the Twitch API to receive the profilepictures and adding them with other information into an array of objects, before the page will be rendered. Unfortunately I'll only get a pending promise for the profile pictures URL, when the page is rendered. nearly a millisecond after the page will be rendered, I get the console log about the PB-Links, so it goes fast, so an ajax dosen't make sense in my opinion. Is there any possibility to wait until the promises are loaded before the script goes on to render the page?
Thank you in advance
async function getStreamersPB(streamerName){
  var streamer = await twitch.getUsers(streamerName);
  var streamerPBURL = await streamer.data[0].profile_image_url;

  console.log(streamerPBURL);
}

...
router.get('/', (req, res) => {

  var streamer = [];
    con.query("SELECT * FROM xxx",  function (err, result) {
    if (err) {
      console.log(err);
    }
    if (result.length !== 0){
      for (let i = 0; i < result.length; i++) {
        let streamObj = {
          "id": result[i].id,
          "name": result[i].name,
          "website": result[i].website.toLowerCase(),
          "status": result[i].status,
          "rang": result[i].rang,
          "userPB": getStreamersPB(result[i].name)
        }
        console.log(streamObj);
        streamer.push(streamObj);
    }}});

    con.query("SELECT * FROM xxx WHERE xxx = '" + xxx + "'", function (err, result) {
    if (err) {
      console.log(err);
    } if(result.length === 1){
    res.render('home', {
      message: result[0].twitchName,
      userID: result[0].id,
      streamer: streamer
    });

...
That is my Console log:
{
  id: 1,
  name: 'xxx',
  website: 'xxx',
  status: 0,
  rang: 1,
  userPB: Promise { <pending> }
}
https://static-cdn.jtvnw.net/...xxx

Comment: You need to await `getStreamersPB`. Mark `function (err, result)` as `async` so you can await it
Comment: Hey @slebetman I changed the code to `(async function (err, result) {await getStreamersPB(result[i].name)})` now I am getting console log `userPB: [AsyncFunction: userPB]`
Answer: As slebetman mentioned, you have to await the async function call, or else you'll send a pending promise to your client. Here's your code with the modification.
router.get('/', (req, res) => {

  var streamer = [];

  // This function has been marked as async so we can use await in it.
  con.query("SELECT * FROM xxx", async function (err, result) {

    if (err) {
      console.log(err);
    }

    if (result.length !== 0) {
      for (let i = 0; i < result.length; i++) {

        let streamObj = {
          "id": result[i].id,
          "name": result[i].name,
          "website": result[i].website.toLowerCase(),
          "status": result[i].status,
          "rang": result[i].rang
        }

        // getStreamersPB is an asynchronous method which you must await.
        streamObj.userPB = await getStreamersPB(result[i].name);

        console.log(streamObj);
        streamer.push(streamObj);
      }
    }

    // I moved this query to inside the callback for the first query
    // to ensure this query happens after the first one. Originally,
    // both `con.query` calls were being invoked at the same time, so
    // there's no garuntee in what order they execute.
    con.query("SELECT * FROM xxx WHERE xxx = '" + xxx + "'", function (err, result) {
      if (err) {
        console.log(err);
      } if (result.length === 1) {
        res.render('home', {
          message: result[0].twitchName,
          userID: result[0].id,
          streamer: streamer
        });
      }
    });

  });

});

Comment: Thank you really much, but now I'm getting a SyntaxError: `SyntaxError: await is only valid in async functions and the top level bodies of modules` I also tried to set the other function on async, but then I get the result: `userPB: undefined`
Comment: @Maggimann I updated the answer. I had the wrong function marked as async. Also, your first code assumed the two `con.query` calls happened one after the other. That isn't garunteed, their callbacks can happen in any order. So I put the second `con.query` inside the callback of the first `con.query`. When dealing with asynchronous function calls (either callbacks or promises) you have to be careful about which order functions will finish. You don't want to respond to the http request before the data you are fetching has returned.
Comment: Now I'm getting a console log of `userPB: undefined`
Answer: I got it fixed! I forgot to put a return statement into my function!
Thank you very much everyone for your answers and your help!!!
Answer: You could use css to hide the page at first, then when your profile pictures have loaded, use javascript to change the css and reveal the page.
Comment: That would work if the JavaScript was client side … which it isn't.
Comment: Thank you for your answer. This is not possible in my way, because I don't want to use ajax or anything like that, because I am rendering the page with the objects. So the site will appear in different way, as more objects the array has.
Comment: Oh sorry, I missunderstood. I thought this was an issue of images loading after initial page rendering. I didn't realize it was an async/await issue. The comment from slebetman explains your issue.
Comment: Still I'm very thankful for your answer! Check my answer on slebetman's command. That isn't working either :(
Comment: @Maggimann I posted an answer with code that shows slebetman's comment.
Answer: Since you are receiving an error to Dylan's answer, add async to the first com.query function.
router.get('/', async (req, res) => {

  var streamer = [];
    con.query("SELECT * FROM xxx", async function (err, result) {
    if (err) {
      console.log(err);
    }
    if (result.length !== 0){
      for (let i = 0; i < result.length; i++) {

        let streamObj = {
          "id": result[i].id,
          "name": result[i].name,
          "website": result[i].website.toLowerCase(),
          "status": result[i].status,
          "rang": result[i].rang
        }

        // getStreamersPB is an asynchronous method which you must await.
        streamObj.userPB = await getStreamersPB(result[i].name);

        console.log(streamObj);
        streamer.push(streamObj);
    }}});

    con.query("SELECT * FROM xxx WHERE xxx = '" + xxx + "'", function (err, result) {
    if (err) {
      console.log(err);
    } if(result.length === 1){
    res.render('home', {
      message: result[0].twitchName,
      userID: result[0].id,
      streamer: streamer
    });

}

Comment: @Maggimann Did you **return** anything in `getStreamersPB()`? The code you posted does not return anything but only print the output but I assumed that was simply incomplete example. If your code REALLY did not return anything then that's why the value is `undefined`. In javascript the default return value is `undefined` so if a function returns nothing it will return undefined (or in this case a Promise of undefined)
Comment: Hi @infinite_verma thank you very much for your answer! Unfortunately I'm getting a console log of  `userPB: undefined` here :( So this isn't working either


How do I check whether and Android device supports Dolby Digital?

Question: Is there an API on android to check if a device supports DolbyDigtal(AC3)?
Is there any other way, besides using AudioManager.getReportedSurroundFormats() (which isn't listed in the official documentation?
Comment: What's the problem with `mAudioManager.getReportedSurroundFormats()`?
Comment: @Braiam it looks like [getReportedSurroundFormats()](https://developer.android.com/reference/android/media/AudioManager#public-methods) is a hidden API that isn't in the official documentation.
Comment: Thank you for answer.
Even if the audio format is none on a TV that supports dolby digital, I want to know if the TV supports dolby digital.
(If the audio format is none, AudioManager.getReportedSurroundFormats() cannot be used to check if the device supports dolby digital.)
Answer: Refer to documentation that audio format for Dolby Digital is AudioFormat.ENCODING_AC3. So you can check Dolby Digital supported from available audio output in your device like this.
val audioManager: AudioManager = /* ... */
val audioDeviceInfos = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
    .filter { it.encodings.contains(AudioFormat.ENCODING_AC3) }


How can I get MySQL 5.5 to log warnings to one of the log files?

Question: I have found various things that say that you can log warnings to the MySQL error log, but I have not been able to actually make it happen.
I do have the error log working, and MySQL prints stuff to it on startup and shutdown and occasionally at other times, but if I e.g. SELECT CAST('123' AS DATE); and then SHOW WARNINGS; I can see the warning, but it does not show up in any logs.
I've also tried enabling the general log and the slow query log, but these don't show the warnings either.
I've tried with log_warnings = 1 and log_warnings = 2, but still no warnings are logged.
What am I doing wrong?
mysql> show variables like '%error%';
+--------------------+--------------------------+
| Variable_name      | Value                    |
+--------------------+--------------------------+
| error_count        | 0                        |
| log_error          | /var/log/mysql/mysql.err |
| max_connect_errors | 10                       |
| max_error_count    | 1024                     |
| slave_skip_errors  | OFF                      |
+--------------------+--------------------------+

mysql> show variables like '%warn%';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_warnings  | 1     |
| sql_warnings  | OFF   |
| warning_count | 0     |
+---------------+-------+
3 rows in set (0.06 sec)

mysql> show variables like '%log%';
+-----------------------------------------+-------------------------------+
| Variable_name                           | Value                         |
+-----------------------------------------+-------------------------------+
...
| general_log                             | ON                            |
| general_log_file                        | /var/log/mysql/general.log    |
...
| log                                     | ON                            |
...
| log_error                               | /var/log/mysql/mysql.err      |
| log_output                              | FILE                          |
| log_queries_not_using_indexes           | ON                            |
...
| log_warnings                            | 1                             |
...
| slow_query_log                          | ON                            |
| slow_query_log_file                     | /var/log/mysql/mysql-slow.log |
...
+-----------------------------------------+-------------------------------+

Edit:
mysql> show global status like 'Aborted%';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| Aborted_clients  | 24    |
| Aborted_connects | 15    |
+------------------+-------+
2 rows in set (0.08 sec)

Edit:
Clarification:  I do get [Warning] Aborted connection 1 to db... and [Warning] Access denied for user... messages logged, but not the warnings that you can see via SHOW WARNINGS after e.g. inserting something or running LOAD DATA INFILE... which is what I'm looking for.
Answer: From : http://ushastry.blogspot.in/2011/02/mysql-bulk-import-and-logging-warnings.html
/path/to/mysql --show-warnings –uUserName –pPassword DBNAME < /path/to/dump_file.sql >> /path/to/load_warnings.log 2>&1

Answer: I've come to the conclusion that this is not possible.  MySQL does not log these warnings to the error log.  Only things like e.g. authentication failures, aborted connections, etc.


FastPass report with screenshot

Question: Is it possible to export Accessibility Insights for Android FastPass reports not only with issue description but also with screenshot?
Answer: It isn't currently possible, but we have an active feature request for this functionality in our repo. If this is something you'd like to see us add, please upvote the feature request so we know there's community interest.

FastPass report with screenshot


Access Denied when changing password in AD programmatically

Question: We have setup a small library (DLL) that we use to update passwords in AD. When testing this application in our test application, it works totally fine. But as soon as we start using the library in another application we get an Access Denied error when trying to change a password.
When we call any another function, like the one that does a simple lookup to see whether a user exists, everything works just fine.
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, TargetDomainServer, TargetDomainContainer, TargetDomainUser, TargetDomainPassword);
    UserPrincipalExt user = UserPrincipalExt.FindByIdentity(ctx, userLogonName);
    user.SetPassword(userPassword);

Any ideas on what i'm doing wrong?
Comment: Your test application might be running as an administrator. Either because it's running from your IDE or because it has a manifest with `requestedExecutionLevel`.
Comment: I'm running this solution under the same account in all situations..
Comment: On Windows Vista and 7, that doesn't mean the process isn't running as administrator. There are automatic elevations for executables marked with `requestedExecutionLevel`. Try running your test application as administrator by right clicking it and choosing that.
Answer: Your test application might be running as an administrator. Either because it's running from your IDE or because it has a manifest with requestedExecutionLevel.
On Windows Vista and 7, running the application while logged in as a normal user doesn't mean the process isn't running as administrator. There are automatic elevations for executables marked with requestedExecutionLevel. Try running your test application as administrator by right clicking it and choosing that.
There are also automatic elevations without any deliberate executable marking. Windows has an internal list for known installers. It actually recognizes some of them by version information and binary signatures and tries to run them as administrator so the installation will actually succeed. IIRC, another identification method is the filename. Executables named setup.exe are also elevated (as long as requestedExecutionLevel doesn't override it).


How choose the number of classes of a series?

Question: I am newbie in DS.
I'm doing a choropleth map with votes of a senator in several cities.
And I have two questions:
1 - How choose the correct number of classes to part the data?
At the time im using four classes, but not for a specific reason.
2 - How choose the technique to use to create these partitions? I saw there are some like natural breaks, quantiles, standart deviation etc, but I don't know how and why to use.
The data looks like this.

city
votes

city_1
1k

city_1
23k

city_1
57k

city_1
112k

.

.

.

city_n
500k

Could you point me the theory around this?
Thank you all.
Answer: It sounds like you might be interested in the literature on cartography and, more generally, data visualization.  The former explicitly addresses questions of choropleth (area-filled) maps.
Among the considerations in any such work are

Purpose: Why do you want to draw this map?  What message should it convey?

Audience: To whom do you wish to communicate?

Psychology: What are the ways in which maps and statistical graphics communicate information?

How do people derive meaning from graphics?
What methods of symbolization lend themselves to faster and more accurate understanding?

Statistics: To what extent do the data suggest forms of visualization and grouping of the values?  What are suitable ways of expressing and re-expressing data for visualization?

The classic reference is Jacques Bertin, Semiology of Graphics.  It contains extensive (thousands) of examples organized by a few basic principles.
A modern study of the psychological aspects is Allen MacEachren, How Maps Work.  It is difficult reading but provides rewarding insight.
Another classic work is William Cleveland, Visualizing Data.  Cleveland's group at Bell Labs conducted psychological studies aimed at obtaining scientific answers to these basic questions, leading to practical advice for constructing statistical graphics (and, incidentally, maps).


Multiple Futures in a Sequence in Scala

Question: I have two computations that happen in a Future as below:
val comp1 = Future { ... }
val comp2 = Future { ... }

I want this to run such that comp2 always runs after comp1 has completed! I know that using a for expression, I can compose these two Future's like.
for {
  comp1Result <- comp1
  comp2Result <- comp2
} yield { ... }

What could be the guarantee that comp1 is completed before comp2? I mean these are computations that happen in a different thread and there is no guarantee to the order in which this might be run. Is there a way to guarantee order without blocking?
Comment: Does the Scala Async solves this?
Comment: Well... if you want you can just put the other future in the onComplete of the first one, if that serves your purpose.
Comment: What if I have 4 of them in a chain with each Future in the chain needs the one before it to be completed?
Comment: `map` and flatMap are used for that. `future2 = future1.map( val => 2*val )` or `future2 = future1.flatMap( val => buildFuture( val ) )`
Answer: Scala for comprehensions are syntactic sugar for combinations of flatMap and map calls on the 'container type' (Futures, in this case), so your code above equates to:
comp1.flatMap{ comp1Result => comp2 }

the computation inside the curly braces here occurs only after comp1 completes and returns a successful result (in the case of failure, the internal computation doesn't get executed).
If you define comp2 outside of the for comprehension as shown in the question, you are kicking off that computation then (you just ignore the outcome until you're inside the for comprehension), but if you define it only inside the for comprehension, then it won't be kicked off unless and until comp1 completes successfully. So, try rejigging the code as follows:
val comp1 = Future { ... } // or you could put this construction inside the for as well
for {
  comp1Result <- comp1
  comp2Result <- Future { ... } // Only start the computation here
  comp3Result <- Future { ... } // etc. for as many such computations as you need
} yield { ... }

Other alternatives are to declare comp2 as a lazy val (so it isn't actually evaluated - kicking off the computation - until it is referenced), or as a lambda (eg val comp2 = () => Future { ... }) and call it with the line
  comp2Result <- comp2()

inside the for comprehension.
Comment: Does the Scala Async offer me the same behavior that I need in my case?
Comment: It is possible that it might in this particular case, but I would strongly recommend avoiding use of Async (at least outside of tests) if at all possible, and becoming familiar with the above "monadic" style of computation, where you keep propagating the 'context' (here, the Future monad) as long as possible. Think of it as structuring your code like you are writing a prescription for what you want done, with the actual chain of computations only carried out at the last possible moment.
Comment: Why would you recommend against using Async other than the fact with getting familiar with monadic computation style?
Comment: Perhaps "strongly" recommend was overstating things :)  Mostly I feel it can easily lead to confusion over what code fragments are being executed when (and where) and what results are available to other bits of code. In simple cases I'm sure you can manage it well enough and it seems straight-forward, but production code rarely remains that simple in my experience. I admit I haven't worked with Async, though, so someone with greater experience working with it might be able to provide better guidance. To me, the for comprehension feels cleaner and easier to reason about.

Multiple Futures in a Sequence in Scala


Equation with complex numbers

Question: Solve the following equation in $ \mathbb{C} $:
$ |z - |z + 1|| = |z + |z - 1|| $
I started it but I don't know how to finish it. Here is what I did so far:
$ |z - |z + 1||^2 = (z - |z + 1|)(\bar{z} - \overline{|z + 1|}) = |z|^2 - z \cdot \overline{|z + 1|} - \bar{z} \cdot |z + 1| + |z + 1|^2 $
$ |z + |z - 1||^2 = (z + |z - 1|)(\bar{z} + \overline{|z - 1|}) = |z|^2 + z \cdot \overline{|z - 1|} + \bar{z} \cdot |z - 1| + |z - 1|^2 $
Now, $ |z - |z + 1|| = |z + |z - 1|| \Rightarrow |z - |z + 1||^2 = |z + |z - 1||^2 $
So we have: $ |z|^2 - z \cdot \overline{|z + 1|} - \bar{z} \cdot |z + 1| + |z + 1|^2 = |z|^2 + z \cdot \overline{|z - 1|} + \bar{z} \cdot |z - 1| + |z - 1|^2 $
$ z(\overline{|z + 1| + |z - 1|}) + \bar{z}(|z + 1| + |z - 1|) = (|z + 1| + |z - 1|)(|z + 1| - |z - 1|) $
We divide all by |z + 1| + |z - 1| and we get:
$ z + \frac{||z + 1| + |z - 1||^2}{(|z + 1| + |z - 1|)^2} + \bar{z} = |z + 1| - |z - 1|$
But $ |z + 1| + |z - 1| $ is a positive number so $ ||z + 1| + |z - 1|| = |z + 1| + |z - 1| $
So $ z + \bar{z} = |z + 1| - |z - 1| $.
And now I don't know what to do with this equation.
Answer: The division actually obscured the result. If you undo it by multiplying your final result by $|z+1|+|z-1|$ you get with $\Re(z)=x$
$$2x(|z+1|+|z-1|)=|z+1|^2-|z-1|^2\tag{1}$$
The term on the right hand side of (1) can be simplified:
$$|z+1|^2-|z-1|^2=|z|^2+2x+1-|z|^2+2x-1=4x\tag{2}$$
Combining (1) and (2) and dividing by $2x$ gives
$$|z+1|+|z-1|=2\tag{3}$$
which is the equation of a degenerate ellipse in the complex plane. Note that the eccentricity equals $1$, so you end up with a line segment on the real axis in the range $x\in[-1,1]$. Note that because we divided by $x$, Eq. (3) disregards the solution $x=0$, i.e. the whole imaginary axis. So, in sum, the regions satisfying your original equation are
$$x\in[-1,1],\;y=0\quad\text{and}\quad x=0,\;y\in\mathbf{R}$$
i.e. a line segment on the real axis, and the whole imaginary axis.
Comment: And the imaginary axis.
Comment: @Michael: What do you mean?
Comment: You cancelled $x$ from both sides.  Check that $z=iy$ satisfies the equation.
Comment: But the ellipse is just the real axis between $\pm1$.
Comment: @Michael: Yes, you're right, it's a degenerate ellipse with eccentricity=1. Thanks for pointing that out! I've edited my answer.
Answer: $z+\overline{z}=|z+1|-|z-1|$
You might square twice
$$(z+\overline{z})^2=2z\overline{z}+2-2|z+1||z-1|\\
4(z+1)(\overline{z}+1)(z-1)(\overline{z}-1)=(2-z^2-\overline{z}^2)^2\\
4(z^2-1)(\overline{z}^2-1)=4-4z^2-4\overline{z}^2+z^4+2z^2\overline{z}^2+\overline{z}^4\\
0=(z^2-\overline{z}^2)^2$$
so $z^2$ is real, so $z=x$ or $z=iy$.
If $z=iy$, then $z+\overline{z}=0=|iy+1|-|iy-1|$, so the whole imaginary axis is included.
If $z=x$, then just the interval $[-1,1]$ is included.
Answer: Here is a much simpler geometric proof:

In the diagram, $z_1=z_0+1$ and $z_2=z_0-1$. Then arcs are drawn with centre at A and tip at $z_1$ and $z_2$ to meet real axis at D and C respectively. Clearly, point D will represent $|z_0+1|$ and point C will represent $-|z_0-1|.$
The length of the line segment joining $z_0$ to D will represent $|z_0 - |z_0 + 1||$ and the one joining $z_0$ to C will represent $|z_0 + |z_0 - 1||$ .
The original equation requires both these line segments to be equal, and this implies that $z_0$ must lie on the perpendicular bisector of D and C. Algebraically, this is equivalent to:
$$Re(z_0)={|z_0+1|-|z_0-1|\over 2}$$
Multiplying both sides by $|z_0+1|+|z_0-1|$, you will get the the following equation after simplification:
$$Re(z_0)(|z_0+1|+|z_0-1|)=2Re(z_0)$$
Which is representing either the imaginary axis or the points lying between -1 and 1

Equation with complex numbers


How to use CoreText to replace UILabel in Swift?

Question: Currently I am using UILabel to put texts on the screen:
var label = UILabel()
view.addSubView(label)
label.backgroundColor = UIColor.whiteColor()
label.numberOfLines = 2
label.font = UIFont.systemFontOfSize(20, weight: UIFontWeightMedium)
label.frame = CGRectMake(0, 0, 100, 50)
label.text = "Hi, this is some text..."

How to use CoreText to replace the above in Swift?
Answer: Following code solved my question:
override func drawRect(rect: CGRect) {
    super.drawRect(rect)

    let  context  = UIGraphicsGetCurrentContext()

    // Flip the coordinate system
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    let path = CGPathCreateMutable()
    CGPathAddRect(path, nil, self.bounds)

    let str = NSMutableAttributedString(string: "some text goes here...")

    // set font color
    str.addAttribute(kCTForegroundColorAttributeName as String, value:UIColor.blackColor() , range: NSMakeRange(0,str.length))
    // set font name & size
    let fontRef = UIFont.systemFontOfSize(20, weight: UIFontWeightMedium)
    str.addAttribute(kCTFontAttributeName as String, value: fontRef, range:NSMakeRange(0, str.length))

    let frameSetter = CTFramesetterCreateWithAttributedString(str)
    let ctFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0,str.length), path, nil)

    CTFrameDraw(ctFrame, context!)
}

Answer: Update for Swift 4.0:
override func draw(_ rect: CGRect) {
     super.draw(rect)

    // context allows you to manipulate the drawing context (i'm setup to draw or bail out)
    guard let context: CGContext = UIGraphicsGetCurrentContext() else {
        return
    }

    // Flip the coordinate system
    context.textMatrix = CGAffineTransform.identity;
    context.translateBy(x: 0, y: self.bounds.size.height);
    context.scaleBy(x: 1.0, y: -1.0);

    let path = CGMutablePath()
    path.addRect(self.bounds)

    let str = NSMutableAttributedString(string: "00:00:00")

    // set font color
    str.addAttribute(NSAttributedStringKey(rawValue: kCTForegroundColorAttributeName as String), value:UIColor.purple , range: NSMakeRange(0,str.length))
    // set font name & size
    let fontRef = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.bold)
    str.addAttribute(NSAttributedStringKey(rawValue: kCTFontAttributeName as String), value: fontRef, range:NSMakeRange(0, str.length))

    let frameSetter = CTFramesetterCreateWithAttributedString(str)
    let ctFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0,str.length), path, nil)

    CTFrameDraw(ctFrame, context)
}

Answer: Try this:
func drawText(context: CGContextRef, text: NSString, attributes: [String: AnyObject], x: CGFloat, y: CGFloat) -> CGSize {
    let font = attributes[NSFontAttributeName] as UIFont
    let attributedString = NSAttributedString(string: text, attributes: attributes)

    let textSize = text.sizeWithAttributes(attributes)

    // y: Add font.descender (its a negative value) to align the text at the baseline
    let textPath    = CGPathCreateWithRect(CGRect(x: x, y: y + font.descender, width: ceil(textSize.width), height: ceil(textSize.height)), nil)
    let frameSetter = CTFramesetterCreateWithAttributedString(attributedString)
    let frame       = CTFramesetterCreateFrame(frameSetter, CFRange(location: 0, length: attributedString.length), textPath, nil)

    CTFrameDraw(frame, context)

    return textSize
    }

And call like this:
var textAttributes: [String: AnyObject] = [
    NSForegroundColorAttributeName : UIColor(white: 1.0, alpha: 1.0).CGColor,
    NSFontAttributeName : UIFont.systemFontOfSize(17)
]

drawText(ctx, text: "Hello, World!", attributes: textAttributes, x: 50, y: 50)

Hope this works!
Comment: Is it possible to achieve what the `numberOfLines` property does?
Comment: What is `ctx` passed into `drawText`? The code seems not complete. Do you mind sharing the reference? Thanks.
Comment: pls try this. this should work CGContextRef ctx = UIGraphicsGetCurrentContext(); let me know if not working.
Comment: not working... or maybe I don't know how to use it in the proper place.
Answer: Updated for swift 3.0:
if let context  = UIGraphicsGetCurrentContext(){

            // Flip the coordinate system
            context.textMatrix = CGAffineTransform.identity;
            context.translateBy(x: 0, y: self.bounds.size.height);
            context.scaleBy(x: 1.0, y: -1.0);

            let path = CGMutablePath()
            path.addRect(self.bounds)

            let str = NSMutableAttributedString(string: "some text goes here...")

            // set font color
            str.addAttribute(kCTForegroundColorAttributeName as String, value:UIColor.black , range: NSMakeRange(0,str.length))
            // set font name & size
            let fontRef = UIFont.systemFont(ofSize: 20, weight: UIFontWeightMedium)
            str.addAttribute(kCTFontAttributeName as String, value: fontRef, range:NSMakeRange(0, str.length))

            let frameSetter = CTFramesetterCreateWithAttributedString(str)
            let ctFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0,str.length), path, nil)

            CTFrameDraw(ctFrame, context)
        }


Select no mysql agrupando resultado por mês

Question: Bom tenho a seguinte estrutura de tabela:
Categoria  |  DataOp        |  Tipo    | ValorOp
--------------------------------------------------
Carro      |  2012-01-14  |   1        | 10
Moto       |  2012-01-17  |   1        | 200
Venda      |  2012-03-15  |   2        | 500
Carro      |  2012-04-24  |   1        | 10
Moto       |  2012-04-10  |   1        | 35
Internet   |  2012-01-11  |   1        | 98

Bom quero fazer um select que me retorne a soma dos totais de cada mês do tipo 1:
O resultado teria que ser esse:
 Mes    | Total
----------------------------
 01     | 308
 04     | 45

Acho que o select ficaria mais ou menos assim:
SELECT
    DataOp,
    SUM(ValorOp)
FROM
    ResumoReceitaDespesas
GROUP BY DataOp

Porém aqui ele agrupa por por mês.
--------------- Solução --------------
SELECT
    MONTH(DataOp),
    SUM(ValorOp)
FROM
    ResumoReceitaDespesas
WHERE Tipo = '1'
GROUP BY DataOp

Comment: Não entendi o agrupar por cidade. Utilize a função `MONTH()` ou talvez seja melhor `YEAR()` e `MONTH()`.
Comment: Eu me atrapalhei no final da pergunta. De qualquer forma sua solução deu certo.
Answer: Tu pode fazer de duas formas,
SELECT
    MONTH(DataOp) as Mes,
    Tipo,
    SUM(ValorOp) as TotalOp
FROM
    ResumoReceitaDespesas
GROUP BY Mes, Tipo

SELECT
    MONTH(DataOp) as Mes,
    Tipo,
    SUM(ValorOp) as TotalOp
FROM
    ResumoReceitaDespesas
WHERE Tipo = '1'
GROUP BY Mes, Tipo

A primeira vai trazer todos os tipos agrupados por mês e a segunda somente o primeiro tipo.


SED returning error 2 when launched by Wpkg

Question: Case
I am deploying a software product using Wpkg over Windows workstations. I need to disable product's faulty automatic update and the best solution in this case is to modify one configuration file with a following regular expression: s/<value>.*<\/value>/<value>file:\\\\<\/value>/g
Problem
To perform the described task, I use SED:
%BASH%\sed "s/<value>.*<\/value>/<value>file:\\\\<\/value>/g" "MyApp.config" > "MyApp.config.tmp"`

Whenever I do it from commandline, it works.
But once I paste it into Wpkg (<> escaped due to XML constraints):
<install cmd='%BASH%\sed "s/<value>.*<\/value>/<value>file:\\\\<\/value>/g" "%PKG_DESTINATION%\MyApp.config" > "%PKG_DESTINATION%\MyApp.config.tmp"' />

...it fails, creating no new files and... returning mysterious error code 2:
Exit code returned non-successful value (2) on command '%BASH%\sed "s/<value>.*<
\/value>/<value>file:\\\\<\/value>/g" "%PKG_DESTINATION%\MyApp.config" > "%PKG_D
ESTINATION%\MyApp.config.tmp"'.

Question
After a pointless hour and half of searching for that mysterious error code 2 I begin to believe that there is either something wrong in me vs. Google relationship, or there really is no documentation for that error. Official manual also left me blind.
I've tried to dump stderr of that Wpkg command to text file, but the file ain't being created, which suggests no stderr to dump.
Perhaps a second or third pair of eyes would help me find the source of the problem?
Comment: Could you indicate if this is still an issue? Have you considered to use PowerShell?
Answer: Apparently, the error 2 was returned not by the sed command, but by the Wpkg being unable to find the %BASH%\sed.exe file :)


Requisição get Falhando

Question: Olá, estou com um problema que está afetando meu desenvolvimento. Estou desenvolvendo uma aplicação que utilizo Axios e Vue.js e Desejo fazer um primeiro get em um dado que irá para uma props e nisso ele apresenta o seguinte erro:

Eu tentei fazer várias outras formas e todas cai neste mesmo erro.

Aqui está a imagem do código.
Como faço para solucionar esse problema?
Answer: Você precisa resolver a promise antes de poder utilizar o valor. Segue um exemplo:
 async asyncData (context) {
    try {
        const { data } = await context.$axios.$get('/vagas')
        return { vagas: data, errorMessage: '' }
    } catch (e) {
        if (e.response.status === 404 || e.response.status === 400 || e.response.status === 500) {
            const { data } = e.response;
            return { vagas: [], errorMessage: data.errors[0].msg }
        } else if (e.request) {
            return { vagas: [], errorMessage: e.request }
        }
        return { vagas: [], errorMessage: e.message }
    }
}

Caso seja necessário posso adicionar mais trechos do código.
Caso não seja possível utilizar o padrão async/await. Pode-se utilizar o .then e .catch. Segue um exemplo.
axios.post('/formulas/create', {
    name: "",
    parts: ""
})
.then(response => {
    console.log(response)
})
.catch(error => {
    console.log(error)
});

Comment: Muito obrigado, eu já consegui resolver de outra forma.
```
async created() {
    await this.axios("http://localhost:8000/items")
      .then((response) => (this.items = response.data))
      .catch((err) => console.log(err));
  },
```

Requisição get Falhando


SQL Server parallel inserts with Azure Eventhub + Logic app

Question: I'm using Azure Event Hub to stream Azure diagnostics data to a Logic app to save it into an Azure SQL table for monitoring purposes. This works great. However, it sometimes occurs that EventHub sends duplicates. To avoid duplicate inserts I'm using a INSERT INTO statement with a  WHERE NOT EXISTS clause. However, very infrequently I am still getting double rows. The Logic app runs parallel so I guess this is causing the issue. I think sometimes it does the same insert on exactly the same time, which causes the WHERE NOT EXISTS clause not to work.
Does anyone know a workaround? i'd rather not do a DELETE from and remove duplicate rows afterwards as I want to put a unique key constraint on the table.
Answer: You have to have some idempotency checking in you function. When scaling happens the new scale unit will take over processing a partition and thus reprocess the same messages.
I don't know if Service Bus can queue those messages.
I advise you to report to the Event Hubs team.


Simple coin flip probability

Question: There's are many people saying either one of two answers for this:
<code>If you flip a coin twice, what's the chance that both will be heads given
that at least one will be heads?
</code>
The more "educated" answer is that the three possible outcomes are H/H, H/T, T/H so the chance is 33.33% The more obvious answer is that since one is heads, you should only count it as a 1 coin toss so it's a 50% chance.
I think 50% is correct even though the above explanation is wrong.
So, one of the coin flips is a guaranteed heads flip..
Case 1: The first flip is is the guaranteed heads: Outcomes: H/T, H/H
Case 2: The second flip is the guaranteed heads: Outcomes: T/H, H/H
H/H should be counted as 2 outcomes, like T/H and H/T are. They're both the same in quantity (i.e T/H, H/T is 1 heads 1 tails, H/H, H/H is 2 heads)
The thing that differs is the ORDER, in which case (guaranteed)H/H and H/(guaranteed)H should be counted as two different outcomes, therefore making it 50%. Am I wrong here?
Comment: The argument is not right. It is certainly true, however, that  **given** the first is (guaranteed to be) head then the probability of $2$ heads is $1/2$, and the same holds if the roles of first and second are interchanged. If you doubt the $1/3$, toss a coin twice $10000$ times. Let $A$ be the number of situations where we got at least one head, and $T$ be the number where we got two. Calculate $A/T$. The experiment is not much fun to do by hand, but we can do a computer simulation.
Comment: Nevermind, deleted
Answer: Let $E_{HH}$ be the event that both coin tosses are heads, $E_{HT}$ (resp. $E_{TH}$) resp. that the first is Heads and the second Tails (resp. the converse). Letting $E$ be the event that at least one coin flip is Heads, you get exactly $$E=E_{HH}\cup E_{HT}\cup E_{TH}$$ and this is a disjoint union.
You want to compute $\Pr[E_{HH}\mid E]$, which can be written
$$
\Pr[E_{HH}\mid E] = \frac{\Pr[E_{HH}\cap E]}{\Pr[E]} = \frac{\Pr[E_{HH}]}{\Pr[E_{HH}]+\Pr[E_{HT}]+\Pr[E_{TH}]}
$$
as $E_{HH}\cap E = E_{HH}$. As the coins are fair and independent, this is
$\Pr[E_{HH}\mid E] = \frac{\frac{1}{4}}{\frac{1}{4}+\frac{1}{4}+\frac{1}{4}} = \frac{1}{3}.$
Comment: I know why people people say 1/3, I know your reasoning. But I'm saying why use this equation on an answer that says "at least one will be heads" which gives us 2 cases (either first flip is heads, or the second flip is heads). Where each case has two outcomes. There are 4 outcomes, not 3
Comment: But if you do that, you are double-counting one event -- the one where both are Heads. I.e., your two events are not disjoint.
Comment: But it's not the same event,  because a guaranteed heads is different from heads that you acquire from a 50/50 chance. The quantity of heads in each is the same, like T/H and H/T but the order of where the guaranteed heads is is different (in both)
Comment: It's not quite true, although it may seem intuitive. Try to write down fully and rigorously your argument using e.g. conditional probabilities, and you will see something does not go through (basically, again, it boils down to counting separately the probabilities of events that are not disjoint), (As a followup comment: either you think something is wrong with your argument, or that something is wrong with mine, as both cannot be correct at the same time. I'm pointing out a flaw in your reasoning -- if you discard this, then it's your turn to explain what is wrong in the argument above.)
Answer: Your analysis is correct, but for a different question: Suppose you flip two coins.  You pick one of the coins at random, and examine it.  It proves to be heads.  The probability that the other coin is heads also is $1/2$, for the reasons you provide.
If you represent the two coin flips as binary variables $A$ and $B$, with heads being $1$ and tails being $0$, then the difference between the original question, and the question you really answered, is that the original question is asking for the probability
$$
P(A \land B \mid A \lor B) = \frac{1}{3}
$$
where $\land$ and $\lor$ are logical AND and OR, respectively, while the question you actually answered asks for the expression
$$
P(B \mid A) \cdot P(A) + P(A \mid B) \cdot P(B) = \frac{1}{2}
$$
Answer: I think, in your case, order counts: $H, T \ne T,H$ since they are two different events, and they have their own possibilities. Task only says that one $H$ is guaranteed, but doesn't say anything about, when is it guaranteed, therefore the answer is indeed $33,3$%.
Comment: That's what I said in my last sentence. (guaranteed)H/H and H/(guaranteed)H are two different H/H outcomes and therefore should be counted as 2 just like T/H and H/T. Making it 50%
Comment: But you can't differ $H,H$ and $H,H$, since you can't decide which is the guaranteed one.
Comment: One of them has the first heads as guaranteed, the other has the second heads as guaranteed. Regardless of which is which. We can't see it with our eyes obviously, but I'm talking about logically
Answer: The point is that there are more ways to get exactly one head if you have two coins and don't assume anything, compared to the number of ways to get exactly one head if you assume that the first coin (or second coin) is heads or tails. This is in essence why the probability is indeed $1/3$ and not $1/2$.
If you want a rigorous argument, just take the 4 equally likely and disjoint possibilities $TT, HT, TH, HH$. The law of conditional probability says that the probability of getting $HH$, assuming you have at least 1 head, is $P(HH)/(P(TH) + P(HT) + P(HH))$. So it's 1/3.
Comment: My argument is that there's more than one way to get heads / heads. Whether the first or the second is the guaranteed heads means that there are TWO orders of H/H.
Comment: @JoeDefill See update giving conditional probability analysis. You can look up the event-based law of conditional probability to verify this.
Comment: I know, I gave the same simplified explanation in my post. My point is why is H/H not two different events? It has the guaranteed heads in a different position in both.

Simple coin flip probability


Google Home Assistant

Question: Hey I'm a student and for a project we have to do a agent for google via API.ai (now named dialogflow.com). Creating the agent isn´t that hard, but is it possible to interrogate the network of the user in a certain intent, to find out which printers he is using?
I think you can handle this with fulfillments, but i dont really understand how i can do this with a snmp trap. Is it possible to catch the data of the google assitant users network? Or is it google who says no we dont want you to scan our users network?
Answer: There are a number of things that made this impossible.
First - the Google Home device itself doesn't allow for local monitoring or control of anything. Although it does have "Smart Home" voice actions, these commands are all sent to a cloud server, and the local devices are responsible for getting their commands from the manufacturer's cloud server.
Second - Actions on Google primarily treats a device (the speaker or your phone) as a user interface device. With a few exceptions, it does not allow access to the hardware itself, so it can't access the networking stack directly, and can't access any SNMP operations.
Third - While commands with Dialogflow are sent to a fulfillment server, that server must be at a publicly accessible HTTPS server address, and everyone using your action will be hitting the same server. So you can't just access a service running on the user's local network. You could create a public service that identifies each user accessing it and forwards the command to something registered on their network, but you still need a way to establish that connection.
One possible workaround would be to have a local server collect SNMP information and save them to a cloud-based database, and then have your fulfillment service access the database to provide information you're querying. There are a lot of pitfalls in this scheme, however, and you'll need to make sure you take appropriate data security measures.

Google Home Assistant


Order of elements is lcm-closed in abelian groups

Question: How can I prove that if $G$ is an Abelian group with elements $a$ and $b$ with orders $m$ and $n$, respectively, then $G$ contains an element whose order is the least common multiple of $m$ and $n$?
It's an exercise from Hungerford's book, but it's not homework. I could not solve it when I take the course on groups and I think it should be easy. There is a hint that says to first prove when $m$ and $n$ are coprimes. I did this part. But I have no idea how to solve the general case.
Thanks.
Comment: Yes, this is a great exercise in Hungerfold's book.
Comment: This is also exercise 10.E.1 in Pinter.
Comment: The dihedral group of order 6: take the rotation $a$ of order $3$ and a reflection $b$ of order $2$, but the dihedral group has no element of order $6$.
Comment: this was a neat problem. can anyone think of a counterexample for nonabelian groups?
Answer: Let $n = \prod_i p_i^{n_i}$ and $m = \prod_i p_i^{m_i}$, where the $p_i$s are the same. Thus $\mathrm{lcm}(n,m) = \prod_i p_i^{\max(n_i,m_i)}$. Let $N = \{ i : n_i \geq m_i \}$ and $M = \{ i : n_i < m_i \}$. Define $n' = \prod_{i \in N} p_i^{n_i}$ and $m' = \prod_{i \in M} p_i^{m_i}$. Now $a' = a^{n/n'}$ is of order $n'$, and $b' = b^{m/m'}$ is of order $m'$. Since $n',m'$ are coprime, we know that there is an element of order $n'm' = \mathrm{lcm}(n,m)$.

You can also prove it using the structure theorem for abelian groups, but that's an overkill.
Comment: Instead of "we know that there is an element of order $n'm'= \mathrm{lcm}(n,m)$" I'd say "the order of $a'b'$ is $n'm'= \mathrm{lcm}(n,m)$".
Comment: @AnalyticHarmony Use $(a'b')^t=1$ and $(a')^t=(b')^{-t}$. Then take $m'$-th powers, then $1=(a')^{tm'}=(b')^{-tm'}$. We have $n'|tm'$, giving $n'|t$. Similarly, we have $m'|tn'$ giving $m'|t$. Therefore, $m'n'|t$.
Comment: Indeed, you can take the subgroup generated by $a,b$, which is going to contain the element you're looking for anyhow.
Comment: Thanks Yuval. That's a nice proof. But how would you do this using the structure theorem? Here the abelian group isn't necessarily finitely generated. So would you pick a finitely generated subgroup containing a and b?
Comment: $a'b'$ have order $m'n'$? Certainly $(a'b')^{m'n'} = e$, but I'm struggling to prove that.
Comment: I have this same problem but instead of having $G$ abelian as hypothesis, I just have $a,b\in G/ab=ba$. How would you face this problem? I ask because at your last sentence you use (if I interpret it right) that if two elements commute and they orders are coprime then the order of the product is the product of the orders. How could I know that $a'$ and $b'$ commute?
Answer: Below is a simple  inductive proof excerpted from my post in a prior thread.
Lemma $\ $ A finite abelian group $\rm\,G\,$ has lcm-closed  order set, i.e. with $\rm\, o(X) := $ order of $\rm\: X$
$$\rm X,Y \in G\ \ \Rightarrow\ \ \exists\ Z \in G\!:\  o(Z) = lcm(o(X),o(Y))\qquad\ \ \ \ \ $$
Proof $\ \ $  We induct on  $\rm\, o(X)\, o(Y).\, $ If it's $\,1\,$ let $\rm\:Z = 1.\:$  Else split off $\rm\,p's$ in $\rm\,o(X),\,o(Y),\,$ i.e.
write  $\rm\ \ o(X)\, =\, AP,\: \ \ o(Y) = B\bar P,\, $  prime $\rm\: p\nmid A,B,\, $  wlog $\rm\,p\,$ $\rm\color{#0a0}{highest}$ in $\,\rm P\,$ so $\,\rm\color{#0a0}{\bar P\!\mid P}\! =\! p^{\large k} > 1 $
Then $\rm\: o(X^{\large P}) = A,\ \ o(Y^{\large \bar P}) = B.\ $  By induction  $\rm\, \exists\, Z\!:\ o(Z) = lcm(A,B)$
so  $\rm\,\ \ o(X^{\large A}\,\!Z) =\, P\, lcm(A,B) = lcm(AP,B\bar P) = lcm(o(X),o(Y))\,\ $ by here.
Note $  $ This is an element-wise form of what's known as "Herstein's hardest problem": $2.5.11$, p. $41$ in the first edition of Herstein's popular textbook Topics in Algebra. In the 2nd edition Herstein added  the following note (problem $2.5.26$, p. $48$)

Don't be discouraged if you don't get this problem with what you know of group theory up to this stage. I don't know anybody, including myself, who has done it subject to the restriction of using material developed so far in the text.  But it is fun to try. I've had more correspondence about this problem than about any other point in the whole book."
Comment: @Arturo: Indeed, but essentially the same proof works for the subgroup case.
Comment: Thanks Bill. I think that's a very elegant proof and probably was the one Hungerford had in mind when gave that hint. Also I wasn't aware of the repercussion of the original problem involving subgroups in the first edition of Hernstein's book.
Comment: @dharmatech I misread your comment. We are pulling out all factors of the  *same* prime  $p$ from both (not different primes). So in your example for $\,p=3\,$ it should be $P = 3^{\large 2},\ \bar P = 3^{\large 0} = 1\ \ $
Comment: @dharmatech We must split out *all* of the $p's$ so what remains $= A$ (or $B)$ is not divisible by $p.\,$   The name is "prime factorization" (but we only care about one prime $p$ so we collect the product of all the other prime factors into $A$ (or $B).\,$ It is indeed a common technique: reducing to prime powers then combining appropriately, e.g. it is used in CRT, [multiplicative functions,](https://en.wikipedia.org/wiki/Multiplicative_function) etc.
Comment: @dharmatech This is a widely used technique for symmetric problems. Here the statement $\rm P(X,Y)\, :=\, \exists\ Z \in G\!:\  o(Z) = lcm(o(X),o(Y))\,$ is *symmetric* in $\rm X,Y$ i.e. $\rm\,P(X,Y)\!\iff\! P(Y,X),\,$ i.e. swapping the arguments yields an equivalent statement, so it suffices to prove either.
Comment: @Bill: I believe the (in)famous problem was about *subgroups*, not elements; that is, if $G$ is abelian and $H$ and $K$ are finite *subgroups*, then $G$ has a subgroup of order $\mathrm{lcm}(|H|,|K|)$. In my Spanish translation of the first edition, this is problem 2.5.11.
Comment: @Bill: if you know that if $X$ has order $ab$ and $\gcd(a,b)=1$, then $X^a$ has order $b$; that would require at least a lemma or two with the material known up to that point... But in any case, your text does not make clear what "Herstein's hardest problem" was, just that it is something of which this is the "element-wise form"
Comment: @Arturo: No, it's trivial and gcd(a,b)=1 isn't needed: if o(X) = ab then o(X^a) = b (it can't be c < b else X^(ac) = 1 for ac < ab, contra to o(X) = ab). The above proof is for the OP, not for Herstein's exercise (I don't recall the constraints imposed by order of presentation of material in Herstein's textbook).
Comment: @Bill: Sorry! I was commenting on the subgroup version, sorry I did not make that clear; should have used "H" instead of "X"; my apologies about the confusion. I guess I think you just may want to mention in the body what Herstein's problem is.
Comment: Let's say $o(X) = AP = 9 = 1*3^2$. $o(Y) =  BP' = 4 = 1*2^2$. In this case, $P = 3^2$ and $P' = 2^2$. However, then $P'|P$ is clearly false. What am I missing here? :-)
Comment: Is it incorrect to assume that hypothetically, $o(X) = AP = 9 = 1*3^2$ and $o(Y) =  BP' = 4 = 1*2^2$? Because with $o(X) = 9$ and $o(Y) = 4$, it isn't clear to me how things can be arranged such that $P' | P$.
Comment: Ah, thank you for that reminder and example. I've been trying a few other examples. $o(X) = AP = 9 = 1*3^2$ and $o(Y) = BP' = 27 = 3*3^2$ doesn't work since $p\nmid B$, i.e. $3\nmid 3$ is false. So I have to switch them around: $o(X) = AP = 27 = 1*3^3$ and $o(Y) = BP' = 9 = 1*3^2$ and this seems to check out OK.
Comment: Is this approach of "splitting off primes" of two numbers in this way a standard or well known technique? Just wondering if it's something I might run into again. It's certainly interesting!
Comment: Thanks Bill. Yes, I see that when I wrote $o(Y) = 3*3^2$, the issue there is that I did not factor out all the $p$'s. OK then. Let's say $o(X) = 9 = AP = 1*3^2$ and $o(Y) = BP' = 27 = 1*3^3$. Now of course,  the issue is that `P'|P` is false. As I mentioned in the last comment, if we switch them around so that $o(X) = 27$ and $o(Y) = 9$ things work. But that need to switch them seems odd. The proof is supposed to be "for any X and any Y". But I run into the above issue with when X and Y are such that $o(X) = 9$ and $o(Y) = 27$. Is there something in the proof wording that accounts for this?
Comment: Thanks for confirming and for the explanation Bill. Always much appreciated!
Answer: Both responses you have received provide correct answers. In fact, you don't need to go so far as to obtain elements of relatively prime orders; all you need to worry about are primes with the property that they divide $nm$, and the largest power of $p$ that divides $n$ is equal to the largest power of $p$ that divides $m$.
Lemma. Let $x$ and $y$ be commuting elements of a group $G$, and assume $x$ and $y$ are of finite orders $n$ and $m$, respectively. Suppose that for every prime $p$ that divides $nm$, the largest power of $p$ that divides $n$ is different from the largest power of $p$ that divides $m$. Then the order of $xy$ in $G$ is $\mathrm{lcm}(n,m)$.
Proof. Let $\ell=\mathrm{lcm}(n,m)$. It is easy to verify that $(xy)^{\ell}=1$, so we just need to show that $\ell$ is the smallest positive integer $k$ such that $(xy)^k=1$. Suppose that $(xy)^k = 1$, with $0\lt k\leq \ell$.
Since $(xy)^k = x^ky^k = 1$, then $x^k = y^{-k}$, and in particular $x^k$ has the same order as $y^k$. The order of $x^k$ is $n/\gcd(n,k)$, and the order of $y^k$ is $m/\gcd(m,k)$. Let $p$ be a prime that divides $\ell$, and let $a=\mathrm{ord}_p(n)$, $b=\mathrm{ord}_p(m)$, and $c=\mathrm{ord}_p(k)$. Assume $b\lt a$. If $c\lt a$, then $\mathrm{ord}_p(n/\gcd(n,k)) = a-c$, and $\mathrm{ord}_p(m/\gcd(m,k))=\max(0,b-c)\lt a-c$, which is impossible. Thus, $c=a$. A symmetric argument shows that if $a\lt b$, then $c=b$. That is, for all primes $p$ that divide $\ell$, we have $\mathrm{ord}_p(k) = \max(\mathrm{ord}_p(n),\mathrm{ord}_p(n)) = \mathrm{ord}_p(\ell)$. Hence $k=\ell$. QED
So now assume that $a$ is an element of order $n$ in an abelian group, and let $b$ be an element of order $m$. Let $p_1,\ldots,p_k$ be the primes that divide $nm$ and for which the $p$-order of $p_i$ in $m$ and in $n$ are equal. Then
$$\mathrm{lcm}(n,m) = \mathrm{lcm}\left(n, \frac{m}{p_1\cdots p_k}\right).$$
Since $m/(p_1\cdots p_k)$ is the order of $b^{p_1\cdots p_k}$, then it follows from the lemma that $ab^{p_1\cdots p_k}$ has order $\mathrm{lcm}(n,m)$, as desired.
Comment: Very nice Arturo. It's good to know that we can do this assuming only that the elements commute.
Comment: @Álvaro Garcia: Well, that much is really a very simple observation: just work inside $\langle x,y\rangle$. Of course, the result is horribly false if $x$ and $y$ don't commute. All sorts of weird things can happen then.
Comment: Why isn't the mysterious notation ord$_p(n)$ defined anywhere?
Comment: @DaveS.: $k$ must divide $\ell$, because $(xy)^{\ell}=1$ and $k$ is the order of $xy$. So the order of $p$ that divides $k$ is *at most* the order of $p$ that divides $\ell$, which is $a$.
Comment: @Phil: I'm not aware of it appearing as-is in any source, but I submitted it as a problem to the Monthly at one point, so you could cite the solution given there. [Here's a link to it on JSTOR](https://www.jstor.org/stable/27641940)
Comment: @Junglemath: Because it isn't mysterious in general (though of course it is if you haven't seen it before; but it is quite common); it's the $p$-order of $n$, which is the largest power of $p$ that divides $n$. $\mathrm{ord}_p(n)=k$ if and only if $p^k|n$ but $p^{k+1}$ does not divide $n$.
Comment: @ArturoMagidin Thank you for the definition. I don't think that notation is nearly common enough to warrant the omission of its definition as part of an answer. I imagine I would have come across it in one of the many algebra books I've browsed through. Moreover I find it hard to believe that all of the millions of people who've read this answer knew what it was without looking it up.
Comment: @Junglemath: Given that the answer was written almost 10 years ago and you are the first person to ask, perhaps you may want to consider the possibility that your perspective may not be as common as you may believe. There's nothing wrong about not knowing a piece of notation (there's a lot of notation around). It also does not mean it's the fault of the writer for using notation you haven't encountered before.
Comment: @Junglemath: By the way: of course [you aren't the first one not to know](https://math.stackexchange.com/questions/116356/what-is-the-meaning-of-operatornameord-pn). It's a little more common in number theory, as it is related to the $p$-adic norm in $\mathbb{Q}$. It may take more than browsing through a book to find it, though.
Comment: Searching for `ord_p` in this site yields [over 180 hits](https://math.stackexchange.com/search?q=ord_p).
Comment: @ArturoMagidin My point is simply that it's _uncommon enough_ to have included its definition in your answer.
Comment: @Junglemath: And clearly I disagree with that estimation. Cheers.
Comment: @DaveS.: $c$ is the order of $p$ that divides $\ell=\mathrm{lcm}(n,m)$; $a$ is the order of $p$ that divides $n$, and $b$ is the order of $p$ that divides $m$. Therefore, $c\leq\max(a,b)$. Since we are assuming $b\lt a$, we have $c\leq a$. There is no gap.
Comment: Sorry, my comment got deleted.  But I disagree.  $c$ is the order of $p$ that divides $k$, not $l$.  Again, I see no reason why we can't have $c>a$.
Comment: @ArturoMagidin , is your Lemma in some source, which I can cite? Thank you!
Answer: This is also one of the starred problems in Herstein's: Topics in Algebra book. Take a look into page 3 of this file:

http://www.csie.ntu.edu.tw/~b89053/herstein.pdf

In case you aren't able to view the solution i type it down as i am not able to download this file, but able to view it in Google Docs.
Solution: Let $a$ and $b$ be elements of order $m$ and $n$ respectively.  Write $\text{lcm} (m,n)= \prod\limits_{i=1}^{t}p_{i}^{\alpha_{i}}$, where the $p_{i}$'s are distinct primes, and $\alpha_{i} > 0$ for each $i$. For any $i \in [1,2, \cdots,t ]$, $p_{i}^{\alpha_{i}}$ divides, either $m$ or $n$. If say, $p_{i}^{\alpha_{i}} \mid  m$, then, $a^{m/p_{i}^{\alpha_{i}}}$ is of order $p_{i}^{\alpha_{i}}$. In this way we obtain elements $x_{1},\cdots,x_{t}$ of orders $p_{1}^{\alpha_{1}}, \cdots, p_{t}^{\alpha_{t}}$ respectively. Now consider elements in $G$ of the form $$x_{1}^{\beta_{1}}, \cdots, x_{t}^{\beta_{t}} \quad \cdots (3)$$ where $\beta_{i} \in \mathbb{N}$, and $i \in [1,2,\cdots,t]$.
Our next goal, is to show that, the single elements, $(x_{1},\cdots,x_{t})$ generates all elements of the form $(3)$. For this purpose, we prove that for all $\beta_{i} \in \mathbb{N}$,  $i \in [1,2,\cdots t]$, the system $$ k = \beta_{1} \ (\text{mod} \ p_{1}^{\alpha_{1}})$$ $$ \cdot $$ $$\cdot $$ $$\cdot $$ $$k = \beta_{t} \ (\text{mod} \ p_{t}^{\alpha_{t}}$$ has a solution in $k$. This follows by setting $$ k =\sum\limits_{i=1}^{t} \beta_{i}c_{i} p_{1}^{\alpha_{1}} \cdots p_{i-1}^{\alpha_{i-1}}p_{i+1}^{\alpha_{i+1}} \cdots p_{t}^{\alpha_{t}}$$ where $c_{i}$ satisfies $$ c_{i} p_{1}^{\alpha_{1}} \cdots p_{i-1}^{\alpha_{i-1}}p_{i+1}^{\alpha_{i+1}} \cdots p_{t}^{\alpha_{t}} \equiv 1 \ (\text{mod} \ p_{i}^{\alpha_{i}})$$
It's not hard to see that the elements of the form in Eq.(3) form a subgroup $H$ of $G$. Hence for each $i$ the order $p_{i}^{\alpha_{i}}$ of the subgroup generated by $x_{i}$ divides $|H|$ by Lagrange's theorem.  This gives $|H| \geq \prod\limits_{i=1}^{t} p_{i}^{\alpha_{i}}$. Clearly $|H| \leq \prod\limits_{i=1}^{t} p_{i}^{\alpha_{i}}$ also holds. Since the element, $(x_{1}, \cdots, x_{t})$ generates exactly $H$ it has order $|H|$
Answer: This becomes quite easy once you know the following structural
Theorem. Any Abelian torsion group is canonically isomorphic to the direct sum of its $p$-torsion subgroups for all prime numbers$~p$.
Here the $p$-torsion subgroup is the subgroup of elements of order some power of$~p$. Note that this is not the structure theorem for finitely generated Abelian groups, as here (1) the decomposition is canonical, (2) there is no finiteness requirement for the group, and (3) the theorem deals only with torsion elements.
To see why the theorem implies the requested result, $a$ and $b$ surely live in the torsion subgroups of $G$, and viewing that as the indicated direct sum, it suffices to prove the result in each $p$-torsion subgroup separately (applying it to the components of $a$ and $b$ in that summand, and combining the new $p$-torsion elements so found as components of a torsion element of$~G$). But in a $p$-torsion group the result is trivial: as $\operatorname{lcm}(p^i,p^j)\in\{p^i,p^j\}$, one can simply choose the element with the larger order as the new element.
The proof of the theorem is based on the property: for every prime $p$, each torsion element $x$ can uniquely be written as product of a $p$-torsion element $g$ and a co-$p$-torsion element $h$ (an element with order relatively prime to$~p$). This follows from the Chinese remainder theorem for cyclic groups, which gives that (1) if $x=gh$ is any such product, then necessarily $g$ and $h$ both lie in the cyclic group generated by $x$, and (2) within that cyclic group there is a unique such pair $g,h$. Then $g$ is the component of $x$ on the $p$-torsion subgroup. Combining these components for all $p$ provides an inverse to the obvious embedding of the direct sum of the $p$-torsion subgroups into the torsion subgroup of$~G$. The proof that it does is easy.

What happens in each $p$-torsion component is trivial, but quite unrelated to what happens at other primes. This explains why the result requires breaking up of the problem across different primes. As far as I can tell all the proofs given for this question do this in some way or another.
Answer: Let $G$ be an abelian group. Let $a$ and $b$ belong to $G$ with order $m$ and $n$ respectively.
Three cases arise:
Case 1: If $m\mid n$ or $n\mid m$ then $\mathrm{lcm}(m,n)=m$ or $n$ in the two cases respectively. Hence our condition holds trivially.
Case 2: Suppose $m$ and $n$ are co-primes. Hence $\mathrm{lcm}(m,n) = mn$.
By abelian property of $G$ $(ab)^{mn} = a^{mn}b^{mn} =ee=e$.
If $o(ab)<mn$ then let $k$ be smallest value for which it holds.
Now $a^k$ and $b^k$ must not be $= e$ as if even one of them equals $e$ then $a^k=e$ implies $m\mid k$ as $m$ is the order of $a$.
Also then $b^k=e$ implies $n\mid k$ as $n$ is the order of $b$.
Hence $k$ is a multiple of $m$ and $n$ and is less than $mn$. Contradiction. Hence not possible.
Now if $a^k$ and $b^k$ are not equal to $e$ and $a^kb^k=e$
Then $a^k=(b^k)^{-1}$.
Hence $b^k$ belongs to $\langle a\rangle$.
Hence $o(b^k) \mid o(a)=m$,
but $o(b^k)\mid o(b)=n$,
hence $m$ and $n$ have a common factor.
Contradiction.
Hence $o(ab)=mn$
Case 3:
Let $m$ and $n$ not be coprime.
Let $d= \gcd(m,n)$.
Hence $n/d$ is coprime with $m$,
so $o(a)=m$ and $o(b^d)=n/d$.
But as $m$ and $n/d$ are coprimes, by Case 2 we get $o(a(b^d))=(mn)/d=mn/\gcd(m,n)=\mathrm{lcm}(m,n)$.
Hence we have an element which has order $\mathrm{lcm}(m,n)$.
Hence proved.
Comment: **Case 3 is wrong**: for $m=24$, $n=36$ we have $d=12$, and $(n/d,m)=(3,24)=3$, $(m/d,n)=(2,36)=2$.


How to SAVE a webform in Simpletest?

Question: I am able to save a sample webform in Simpletest if I only use title and body:
<code>  $edit = array();
  $edit['title'] = 'Sample webform';
  $edit["body[$langcode][0][value]"] = $this->randomName();
  $this->drupalPost('node/add/webform', $edit, t('Save'));
</code>
But when it comes to add the additional fields,
<code>$edit['customfield_xxx'] = '0053416';
</code>
the test fails:
<code>Failed to set field customfield_xxx to 0053416
</code>
Is any nesting necessary to make it work?
UPDATE
It seems like after submitting the form as describe above I need to access the components page:
$this->drupalGet('node/1/webform/components');
where I build an array with all components. However I have been able to fill in the specific component form with 1 single field.
Answer: You need to mimics the user's behaviour.
You need to submit individually each form in multiple steps.
You must write correctly the field names (look for input names in the DOM with Firebug or Developer Tools)
<code>  $edit = array();
  $edit['title'] = 'Sample webform';
  $edit["body[$langcode][0][value]"] = $this->randomName();
  $this->drupalPost('node/add/webform', $edit, t('Save'));
</code>
then submit the fields individually:
<code>  $edit = array();
  $edit['add[name]'] = 'Sample webform';
  $edit['add[type]'] = 'textfield';//or whatever, optional
  $this->drupalPost('node/webforms/components', $edit, t('Add'));
</code>
Rinse and repeat.
You can create a custom function to perform that.

How to SAVE a webform in Simpletest?


PHP command-line: How do I read in a typed-in password without displaying the typed chars on the console?

Question: I want to read in a password as part of a command-line script, but do not what the typed password to appear on the screen. This seems to be a fairly common feature in command-line apps, but my Google-fu has failed in identifying how this works. Is it a feature of the OS? Do you have to intercept the input stream somehow so it doesn't write out to the console? I would like to use this in a php command line script, but I cannot use what I cannot understand.
Some independent searching yielded this link, where way down at the bottom they mention that mysqladmin does not use STDIN to read in the password. How do they do it then, and how could I implement this functionality?
Comment: To answer the question about `mysqladmin`, you can always open your own TTY which will allow input.
Answer: Answering in case someone finds this googling.
It isn't possible in pure PHP.  The solution is to execute a small shell script for Linux or a small program for Windows.
The shell script would look like this for the zsh shell:
<code>/usr/bin/env zsh -c 'stty -echo; read -r mypassword; stty echo; echo $mypassword'
</code>
A full working implementation was written by Seldaek from Composer, which you can find at https://github.com/Seldaek/cli-prompt


Fourier transform of $\frac{2\sin(x)}{1+x^2}$

Question: I'm trying to calculate FT of $$f(x)=\frac{2\sin(x)}{1+x^2}$$
First of all we have
$$
\int_{-\infty}^{+\infty}\left|\frac{2\sin(x)}{1+x^2}\right| \, dx\leq 2\int_{-\infty}^{+\infty}\frac{1}{1+x^2} \, dx=2\pi
$$
thus $\mathcal{F}(f)$ is well defined. Now let's compute $\mathcal{F}(f)(\xi)$:
$$\mathcal{F}(f)(\xi)=2\int_{-\infty}^{+\infty}\frac{\sin(x)e^{-2\pi i x\xi}}{1+x^2} \, dx = \left[\sin(x)=\frac{e^{ix}-e^{-ix}}{2i}\right]=\\=-i\int_{-\infty}^{+\infty} \frac{e^{-2\pi ix\xi + ix}-e^{-2\pi ix\xi -ix}}{1+x^2}\, dx$$
Now I'm not sure how to proceed further. Any help?
Comment: I think you can use the Residue's theorem.
Answer: This can be solved using the convolution theorem.
You should first verify for yourself that
$$\mathcal{F}^{-1}\left\{2\pi e^{-|2\pi\xi|}\right\} = \dfrac{2}{1+x^2}$$
and that
$$\mathcal{F}\left\{\sin(x)\right\} = \dfrac{i}{2}\delta\left(\xi + \dfrac1{2\pi}\right)-\dfrac{i}{2}\delta\left(\xi - \dfrac1{2\pi}\right)$$
By the convolution theorem
$$\begin{align}\mathcal{F}\left\{\dfrac{2}{1+x^2} \cdot \sin(x)\right\} &= \mathcal{F}\left\{\dfrac{2}{1+x^2} \right\} * \mathcal{F}\left\{\sin(x)\right\} \\
\\
&= 2\pi e^{-|2\pi\xi|} \space * \space \left[\dfrac{i}{2}\delta\left(\xi + \dfrac1{2\pi}\right)-\dfrac{i}{2}\delta\left(\xi - \dfrac1{2\pi}\right)\right]\\
\\
&= i\pi \left( e^{-\left| 2\pi\left(\xi + \frac1{2\pi}\right)\right|}-e^{-\left| 2\pi\left(\xi - \frac1{2\pi}\right)\right|}\right)\\
\\
&= i\pi \left( e^{-\left| 2\pi\xi +1 \right|}-e^{-\left| 2\pi\xi-1\right|}\right)\\
\end{align}$$
Answer: Hint: Define the upper semi-circle with center in origin and redius $R$ as the contour and when $z=i$ is a pole of
$$\int_{C}\frac{e^{-2\pi ix\xi + ix}-e^{-2\pi ix\xi -ix}}{1+x^2}dx$$
in $C$, find the residue, then you can simplify the integral.


Prove/Disprove: Find $a\in S_4$ that is not a power of $b$ such that $ab=ba$ while $b=(123)$

Question:
Prove/Disprove: Find $a\in S_4$ that is not a power of $b$ such that $ab=ba$ while $b=(123)$

What I did:
I think this statement is false.
So we need to find $aba^{-1}=b$, we know that $id\in S_4$ will surely $id*b*id^{-1}=b$ but we get $id^k=b$, I wonder if there are more elements such that $ab=ba$, how to find them?
Any help will be appreciated.
Comment: @pjs36 I think you're right, I deleted my comment.
Answer: If $a$ commutes with $b$, let's look where $ab=ba$ sends 4. We see that $ba(4)=ab(4)=a(4)$, thus $a(4)$ is a stable point of $b$, thus $a(4)=4$. So we reduced the problem to the case of $S_3$, but for $S_3$ it is straitforward to check that any transposition does not commute with $(123)$, and all others are powers of $b$.
Comment: Nope, in $S_3$ you have 6 elements: powers of $b$: $id,b,b^2$ and three transpositions. Powers of $b$ obviously commute with $b$, so nothing to check for them. But if you checked that (123) and (12) do not commute, then obviously (123)=(231) and (23) do not commute, because we just renamed elements, similarly, (312) and (31) do not commute.
Comment: So I need to check for all possible elements in $S_3$? Meaning to check for 6 different elements to check commute and if so to check for each element if it a power of $b$


Changing order of derivation and integration for infinitely continuous function

Question: $$\frac d{dt}\int_0^t f(t,\tau)d\tau=f(t,t)+\int_0^t\frac\partial{\partial t}f(t,\tau)d\tau$$
How would you prove that? Thank you very much
Comment: Possible duplicate of [when can we interchange integration and differentiation](https://math.stackexchange.com/questions/2530213/when-can-we-interchange-integration-and-differentiation)
Comment: You would replace $\tau$ with $t$ and then bring the derivative inside the integral (so that it becomes a partial derivative) per the Newton-Leibniz integral rule.
Answer: Use the Leibniz integral rule.
Or use any of the other answers to this and variants of this question on this site.
Comment: I am not really sure what to ....
Answer: By the Newton-Leibniz Integral rule
$$\frac{d}{dt}\int_a^{s(t)}f(t,\tau)d\tau=s'(t)\, f(s(t),t)+\int_a^{s(t)}\frac{\partial f(t,\tau)} {\partial t }  \, d\tau$$
in your case $s(t)=t$ and $a=0$. Therefore, $s'(t)=1$ and the above expression becomes
$$\frac{d}{dt}\int_0^{t}f(t,\tau)d\tau=\, f(t,t)+\int_0^{t}\frac{\partial f(t,\tau)} {\partial t }  \, d\tau$$
Comment: Thank you very much, do you think is possible to show that by the definition of derivative ? I am afraid we are not allowed to use NL rule.