Symmetrically clean expanded (one-item-per-line) arrays in HAML?

Question: I'm trying to figure out if there's some way to make the following code both visually "clean" and also easily sortable so each line with an array item has one array item and only one array item (plus the comma).
- conditions = [feature_on,
  job_has_started,
  user_can_request,
  no_current_request,
  job_reappointable,
  stopping_soon,]

If I want to reorder the conditions (which represent lambdas used to determine whether a form is shown or not) to put the fastest conditions to compute first (or alternately putting the conditions that are most often false) I can't necessarily simply reorder the conditions.  I have to also muck about with the opening and closing brackets and other things.  This is not my idea of elegance.  I would like something much closer to this:
- conditions = [
  feature_on,
  job_has_started,
  user_can_request,
  no_current_request,
  job_reappointable,
  stopping_soon,
  ]

But I have not found any way to get HAML to allow this.  \ at the end of the first line does not solve the problem.  Neither does HAML's own '|', which is used similarly in other situations in HAML.  I'm not 100% sure whether it is possible. But I'm sure there are others who have tried to achieve similar ends with HAML.  How can I do it?
If it's not currently possible with out-of-the-box HAML, how hard would it be to patch HAML to allow this?
Answer: Use a :ruby filter https://haml.info/docs/yardoc/file.REFERENCE.html#ruby-filter.
:ruby
  conditions = [
    feature_on,
    user_can_request,
    job_has_started,
    no_current_request,
    job_reappointable,
    stopping_soon,
  ]


Should I create two tag managers for two different websites under the same domain?

Question: I own two websites under the same domain eg. abc.com and abc.com/xyz. Both of them are hosted on different servers. So, should I create two separate tag manager accounts and thus two properties in Universal Analytics OR two tag manager accounts and one property in UA?
Answer: Yes you should.
If the two website are serving different content or you want to see the data individually. You should separate to two GTM and GA.
Comment: So should I separate the property in Universal analytics too? so far the company has been using the same property but two different tag manager accounts. This is causing some problems, like recording conversions or connecting with Google ads.
Comment: Yes you should. For both Universal Analytics or GA4. Because it is separated websites.
Comment: That's what I was thinking. I have another question related to the Search Console, we have separate properties for two websites on the google search console, but the main URL viz. abc.com also collects data for the other website viz. abc.com/xyz. Do you know the reason why?
Comment: Does the abc.com/xyz also have the same google verify code?


how to know windows driver letter change

Question: I write a program to get disk SerialNumber and driver letter relationship, it works well. But user can change drive letter in disk management, I want to get the relationship realtime. Does windows has change event or notification send when driver letter change?
I have  tried WM_DEVICECHANGE event and ReadDirectoryChangesW function, but it not works.
Can somebody tell me how to know windows driver letter in a pragrom, Thanks!
Comment: Have a look at [`VDS_DRIVE_LETTER_NOTIFICATION`](https://learn.microsoft.com/en-us/windows/win32/api/vds/ns-vds-vds_drive_letter_notification).
Answer: After ask many peoples and searched long time. I found that no windows api notifcation or send an event to track windows drive letter. But I found windows drive letter is record in registry HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices. We can use RegNotifyChangeKeyValue function to listen this registry value change to know windows drive letter change.


Is conditional probability always equal to the probability of the predicted event? P(A|B) = P(A)

Question: I'm currently trying to better understand the fundamental notions of statistics.
Navigating through multiple sites, I've found this formula for joint probability.
P(A ∩ B) = P(A)*P(B)
Namely, if we want to know what is the probability of A and B to co-occur, we just multiply their individual (marginal) probabilities.
As for the conditional probability, the formula stands like this:
P(A | B) = P(A∩B) / P(B)
So, if we want to know the probability of A when we already know B, we divide the joint probability of A and B by the probability of B.
If we develop this formula, we will get:
P(A | B) = P(A)*P(B)/P(B)
Further, we can simplify the fraction by dividing it by P(B), and we are left with
P(A | B) = P(A)
Suppose we want to estimate the probability of drawing from a deck of cards a red colored card of 4 (hearts or diamonds), while already knowing it's colored red.
Individual (marginal) probabilities
P(red) = 1/2 = 0.5
P(4) = 4/52 = 1/13
Joint Probability (to draw a red 4)
P(4 ∩ red) = P(A)*P(B) = 1/2 * 1/13 = 1/26
Conditional probability (prob to draw a 4 already knowing it is red)
P(4 | red) = P(4 ∩ red) / P(red) = P(4)*P(red)/P(red)
P(4 | red) = 1/13*0.5/0.5 = 1/13
If we know that the card we are about to draw is red, the probability of it being a red 4 is 1/13 (or 7.6%), which is just the probability of drawing a 4 from the deck. This makes sense because we have eliminated half of the possibilities (black cards), and we are actually drawing from a set of 26 cards that has 2 fours in it. So, 2 out of 26 (or 1 of 13) of the drawn cards will be a red 4.
The results look fine, but it really seems that I am missing something, because in the relationship P(A | B) = P(A) doesn't take into account the probability of B.
I will be highly grateful is someone could look into my question and give a response.
Thanks in advance!
Comment: All clear, thank you all for the explanations.
Comment: Check out this [question](https://stats.stackexchange.com/questions/238230/is-the-joint-probability-of-two-sets-equal-to-their-intersection). Your probability for the intersection isn't always right.
Answer: $P(A\cap B)=P(A)P(B)$ is true if and only if $A$ and $B$ are independent. So, $P(A|B)\neq P(A)$ in general. In your example, it holds because the events are fortunately independent. You already informally found it in your reasoning paragraph, by thinking about the sample space.
For a simple counter example, consider the case where $A=B$. $P(A|B)=1$ clearly, because if you know that $B=A$ happened, the probability of $A$ happening is $1$.
Comment: Typo in the last sentence: *because if you know that **A** happened*. It's B, obviously.
Comment: @RuiBarradas It wasn't meant to be a typo, but maybe this is more clear. In the reason part, I was just using the fact that $B=A$ to make sense.
Comment: Yes, it is, thanks.
Answer: P(A ∩ B) = P(A)*P(B)
this expression is true only when events A and B are independent. It is not true in general.
Answer: It might help to think of P(A|B) as meaning "What percentage of B is A", and to think of all probabilities as conditional; if a probability is not given explicitly as conditional, there's an implicit universal condition; P(A) can be taken as P(A|S) where S is the entire set you're considering. In this case, S is just "any card". So if A is "card is red" and B is "card is a 4", then P(A|S) is "probability that what we draw is red, given that it's from a standard deck" or "percentage of all the cards that are red". P(A|B) is "percentage of all the 4s that are red". P(A ∩ B) = P(A ∩ B|S) = percentage of cards that are red and 4s.
So when you ask "Is P(A) = P(A|B)", you're asking "Is there percentage of all cards that are red equal to the percentage of 4s that are red?" In this case, the answer is "yes". However, this is not in general the case. The property of these percentages being equal is known as "independence".
It's easy to come up with examples of variables that are dependent. For instance, P(Diamond|Red) != P(Diamond). Any time a subpopulation has a property at a rate different from the general population, the conditional probability is different. E.g. P(child goes to a private school|parents make more than $100k) != P(child goes to private school).


Technique for Gretchen am Spinnrade - Schubert/Liszt

Question: I'm having a fair crack at learning "Gretchen am Spinnrade" which is the Lizst arrangement of the famous Schubert Lieder work.
I would ask advice of any accomplished pianist that knows either the work, or any of Liszt's other arrangements of Schubert lieder - what's the trick to pulling off the melody? The ostinato semiquavers are not really a problem, but pulling off the melody in the same hand whilst keeping the running semiquavers going is proving to be a challenge. I am no Kissin or Yuja Wang, just a dude who enjoys tinkling the ivories.
Any technique suggestions or studies/exercises that might help would be much appreciated.
Comment: Maybe we think it's a problem of the hand and fingers. I think it is a problem of  the brain hemispheres. I don't know the piece and without looking at it I understand that the right hand has to play the tune and semiquavers at once. I would try to practice only  one of them (r.h.) and the other  by the left hand - ignoring the job the l.h. would have  - and then exchange them in purpose the synapses are prepared and laid in your brain ...
Comment: Apparently you have not yet seen one of Liszt's arrangement, where he uses a third system, just to find a place for all notes. My uninformed guess, that this intended to be played with a third hand or the nose, clearly outs me as non-pianist.
Comment: Yes, I have seen this - Ave Maria is one such transcription. I took a quick look at that and put it right back where I found it.
Comment: I have tried various appendages in my vain attempts to play ave maria. I had most success with my nose, limited success elsewhere....
Answer: This is just a question of technique really.
I assume that you have listened to the piece being played by an accomplished pianist so you know what it is supposed to sound like, yes?  If not then do that (you'll find many on YouTube), so at least you know what to aim for and also the fact that it can be done.
So what is the issue:  some notes (the melody) are being emphasised over the other notes in the same hand.  And that is done by giving those notes more weight when playing them.  Or in other words, and I'll say this quietly, they are being played louder.
As with so many things of this nature it comes down to practise.  Start slowly, making sure you not only get the notes right but also that you are weighting the strikes differently to make the melody stand out.
It sounds difficult I know but this happens all over the place in the piano repertoire;
Chopin's Fantaisie Impromtu (at the end, in the recapitulation) and Berceuse both require something similar as does Debussy's Ballade and they are just three that come straight to my mind.  The Debussy in particular is much easier than the Liszt so it might something to look at.
But, as ever, it all comes down to practise.  Good luck.


Change name of updated_at column in ActiveRecord / Rails

Question: I'm building a JRuby on Rails app for a legacy database. None of the tables have a 'created_at' column (so I can just go ahead and add that), but all of them have a 'modtime' column instead of an 'updated_at' column. I can't change all of the column names from 'modtime' to 'updated_at' in the db since much of the java code and sql functions use this column name. It would be possible to simply add an 'updated_at' column to all the tables, but this would be confusing and less than ideal.
How I can get ActiveRecord to use 'modtime' as a column name instead of 'updated_at'?
Comment: Check out this answer: http://stackoverflow.com/a/3981571/2622934
Comment: Thanks guys, I read that answer but I don't really understand it: Where does this active_record.rb file go? What is the meaning of "create a file called that in the initializers"? I assume that I put :modtime in the array I pass to the timestamp_attributes_for_update method?
Answer: Here's what you need to do for ActiveRecord to use modtime as its update column:
Create a file in the config/initializers directory named active_record_patch.rb
# config/initializers/active_record_patch.rb
module ActiveRecord
  module Timestamp

    private

      def timestamp_attributes_for_update #:nodoc:
        [:modtime, :updated_on, :modified_at]
      end
  end
end

What you are doing here is overriding ActiveRecord::Timestamp's timestamp_attributes_for_update method which it uses to identify the names of its update attributes. The file needs to be put in config/initializers since all files in initializers get run once your Rails app loads.
This is a monkey patch and overrides the normal behavior of ActiveRecord::Timestamp which may break when you use a different version of ActiveRecord.
Hope it helps.
Comment: This monkey patch quietly breaks a normal behavior of Timestamp because original column names are [:updated_on, :updated_at](https://github.com/rails/rails/blob/3-2-stable/activerecord/lib/active_record/timestamp.rb#L91). `updated_at` column that was generated by default rails generator for other AR models wouldn't be updated. Please clarify your answer.
Comment: Thank you! This is a clear and concise answer and works for me on Rails 4.0.2.


fields.title.content in views-view-fields--n--block.html.twig won't display

Question: This is what I wrote into views-view-fields--n--block.html.twig.
The second and third fields are displayed properly (here I used the machine name). But how do I get the title which is automatically there with every content type?

 {{ fields.title.content}}

{{ fields.field_news_bild.content }}

{{ fields.body.content}}

please help!
Comment: Your code looks correct to me, did you add the Title as a field in your view?
Answer: Just found out that my title fields' name is title_1.
this is what brought the solution:

    {% for key, field in fields %}

key: {{ key }}

    {% endfor %}

This shows all fields from the view in the template file.


mpdf cropmarks and bleed margins

Question: I've just started looking in to mPDF today (so it's all new too me). I'm a little stuck on as to how I can get the crop marks and bleed margins working. I can't see  them on the output PDF. Usually when I make files for printers (i.e. not an actual printer, but a print shop) I have to include bleed and crop marks since images for covers need it.
This is what I have now
require_once __DIR__ . '/../../vendor/autoload.php';
$pdfOptions = array(
    'mode'                  => 'utf-8',
    'format'                => 'A4',
    'orientation'           => 'P',
    'printers_info'         => true,
    'mirrorMargins'         => true,
    'bleedMargin'           => 3,
$pdf = new \Mpdf\Mpdf( $pdfOptions );
$styles = file_get_contents( __DIR__ . '/css/print.css');
$content = '
Some content
';
$pdf->SetDisplayMode( 'fullpage','continuous' );
$pdf->img_dpi = 300;
$pdf->WriteHTML( $styles, 1 );
$pdf->WriteHTML( $content, 2 );
$pdf->Output( 'test.pdf', "I" );

Answer: The easiest way to enable crop marks and control the document bleed in mPDF is via the CSS parameter @page. mPDF supports the marks and size CSS properties which will make it easy for you to enable the crop marks and control the bleed.
The following sample code will add a 3mm bleed around the document:
$mpdf = new \Mpdf\Mpdf([
    'mode' => 'utf-8',
    'format' => 'A4',
    'orientation' => 'P',
    'img_dpi' => 300,
]);

$mpdf->SetDisplayMode('fullpage');

$mpdf->WriteHTML('

Content
');

$mpdf->Output();

If you want to add a larger bleed, reduce the values in the size parameter. Also, add a margin property to @page to control the margins around the print area.
Comment: Thanks for the reply! I've been playing around with these settings for a while now. Still trying to get a real handle on everything : )  But at least now I understand that the bleed settings don't automatically add the needed space, but rather you have to increase the size (since I want the final result to fit A4 (210x297)). So In my case I added space to make it work. Thanks again! Very helpful in getting me in the right direction  ; )
Answer: For anyone else running into this - remember that crop marks/bleed needs to be at the page size that the printing company will be using. So if you are trying to print an A4 pdf (which is 210mm x 297mm), the size attribute shown in Jake's answer will need to be 210 x 297 and the actual document size will need to be increased. The usual standard is about 5mm space added to all side of the document, which means that your document should be 10mm higher and 10mm wider.
As an example:
<?php
function generate_pdf($content, $pdf_width, $pdf_height, $bleed = false) {
    $bleed_size = 10; //5mm either side of the doc
    $width      = ($bleed ? $pdf_width + $bleed_size : $pdf_width); //if bleed - increase by 10mm
    $height     = ($bleed ? $pdf_height + $bleed_size : $pdf_height); //if bleed - increase by 10mm

    $mpdf       = new \Mpdf\Mpdf([
        'mode'          => 'utf-8',
        'format'        => [$width, $height],
        'img_dpi'       => 300,

    ]);

    $mpdf->SetDisplayMode('fullpage');

    if($bleed) {
        $content = add_bleed($content, $pdf_width, $pdf_height);
    }

    $mpdf->WriteHTML($content);
    $mpdf->Output();
}

function add_bleed($content, $width, $height) {
    $bleed = '

';
    return $bleed.$content;
}

Once the above functions are saved, you can simple use the following function to generate your pdf with crop marks.
<?php
generate_pdf('
test
', 210, 297, $bleed); //a4 == 210x297

mpdf cropmarks and bleed margins


Denominator in Bayes - in the continuous case, why isn't it zero?

Question: For a continuous random variable, the probability of any particular value is zero. Only by integrating over some range is a non-zero probability obtained.
The components of the Bayes theorem are random variables.
Thus, in the case of Bayes written for continuous data,
say D is the height mass of something, why isn't the dedenominator $P(D)$ zero?  The probability density of any particular value is zero (yes)?
$$
  P(M|D) = \frac{ P(D|M) P(M) }{ P(D) }
$$
I believe that in the Bayes formula we can assign D as the value of a single observation OR as a collection of observations (yes?).  If so, in the case where the collection is a continuous interval, then $P(D)$ would be non-zero.
I am also aware that $P(D) = \int P(D|M) P(M) \, dM$.  However this does not answer the question for me. Again consider the case where the data is the mass (or height).  You can measure a particular mass, but the probability of that exact mass is zero.
Answer: In the case where $D$ is a continuous random variable, the expression $P(D)$ refers to the probability density of $D$, instead of the probability mass.
Comment: @basicidea "The probability density for a single value from a continuous distribution is $0$." No, that's not correct. The key word here is *density*. For example, if $X$ is uniformly distributed on $[0,1]$, the probability density of $X$ at $1/3$ is equal to $1$.
Comment: Right, but that is the source of the problejm (I believe). The probability density for a single value from a continuous distribution is zero.

Am I wrong?
Comment: please distinguish probability mass from "mass" in the question. I am using mass (related to weight) as an example of a continuous quantity.


quadratic Sum of N nummbers: implementation in C

Question: As you can read in the header it is about a rather simple topic. But I encountered something very odd while implementing possible different ways to get a quadratic sum of N numbers.
I implemented three different versions:

Quadratic Gauß sum (func: quadratGauss(int n) )
Iterative (func: quadratIterativeClassic(int n) )
Iterative via Bitoperation (func: quadratIterativeBitoperation(int n) )

All three functions have returned the same result as expected from the given Input. The Big question now is. How was it possible for the third function to work proper? The Code looks like this:
void quadratGauss(int n){

    printf("+quadratGauss: \n");
    int result = ((n*(n+1))*(2*n+1))/2;
    printf("Result: %d\n----------------\n",result);

}

void quadratIterativClassic(int n){

    int result;
    printf("+quadratIterativClassic: \n");
    for(int i;i<=n;i++)
        result += i * i;
    printf("Result: %d\n----------------\n",result);

}

void quadratIterativeBitOperation(int n){

    int result;
    printf("+quadratIterativeBitOperation: \n");

    for(int i;i<=n;i++)
        result += i^2;

    printf("Result: %d\n----------------\n",result);

}

As you see I use the XOR operator. I originally wanted to use the shift-operator "<<" but i tried others as well. what where stunning when i tried the XOR operator: the result was still the same as before and the same as the other two functions. I thought this was not possible because the XOR is not an operator for the power-operation because C does not contain such an operator but still i got eventually the right result.
I tested the functions with different numbers of different "sizes". Nothing odd in the result of each function.
I've got no clue why. But there must be an explanation, doesn't it?
If you have one, I would appreciate alot the effort of writing down a possible reason, why you can implement this with the XOR operator.
here the whole main file:
#include <stdlib.h>
#include <stdio.h>

#include <iostream>

#define N 5000

void sumGauss(int n)
{
printf("+sumGauss: \n");
int result = (n*(n+1)/2);
printf("Result: %d\n----------------\n",result);
}

void sumClassic(int n)
{
printf("+sumClassic: \n");
int result = 0;
for(int i = 0; i <= n; i++)
    result += i;
printf("Result: %d\n----------------\n",result);
}

void quadratGauss(int n){

printf("+quadratGauss: \n");
int result = ((n*(n+1))*(2*n+1))/2;
printf("Result: %d\n----------------\n",result);

}

void quadratIterativeBitOperation(int n){

int result;
printf("+quadratIterativeBitOperation: \n");
for(int i;i<=n;i++)
    result += i^2;
printf("Result: %d\n----------------\n",result);

}

void quadratIterativClassic(int n){

int result;
printf("+quadratIterativClassic: \n");
for(int i;i<=n;i++)
    result += i * i;
printf("Result: %d\n----------------\n",result);

}

void unevenSum(int n)
{
printf("+unevenSum: \n");
int uneven = 0;
int i=0;
for(i=1;i<= n;i+=2) {
    uneven += i;
}

printf("Result: %d\n----------------\n",uneven*2);

}

void unevenSumModulo(int n)
{
printf("+unevenSumModulo: \n");
int result=0;
for(int i=0;i<=n;i++)
{
    if( (i%1) == 0)
        result += i;
}

printf("Result: %d\n----------------\n",result);

}

void unevenSumNico(int n)
{
printf("+unevenSumNico: \n");
int odd = 0;
int i=0;
for(i=1;i<= n;i++) {
    odd += ((2*i)-1)/2;
}

printf("Result: %d\n----------------\n",odd);

}

void evenSum(int n)
{
printf("+evenSum: \n");
int result=0;
for(int i=0;i<=n;i++)
{
    if( (i%2) == 0)
        result += i;
}

printf("Result: %d\n----------------\n",result);

}

void Zins(float Kapital,int years)
{
printf("Zinstabelle fuer Grundkaptial %.2f Euro\n",Kapital);
printf("Kapitalstand zum Jahresende\n");
int i=0;
float K = Kapital;
for(int i =1;i<years+1;i++)
{

    K = K *(1.f + 0.05f);
    printf("Jahr: %2d         Kapital: %.2f Euro\n",i,K);

}
}

int main(int argc, char** argv) {

sumGauss(N);
sumClassic(N);

quadratGauss(N);
quadratIterativeBitOperation(N);
quadratIterativClassic(N);

unevenSum(N);
unevenSumNico(N);
unevenSumModulo(N);

evenSum(N);
Zins(N);

return 0;
}

Comment: You didn't initialize `i` or `result` in either iterative function, so I assume that the initial value of `i` is greater than `n`, the loop doesn't run, and the result is unchanged from the first call to `quadratGauss`. In other words, your program has undefined behavior.
Comment: The stack is "freed" meaning the stack pointer is set to the value before the function was executed. The next function is "overwriting" the old stack values when it is called. Or, when you are not initializing variables, it might just take whatever is written in that specific address of the stack (which in your case could be the values from the previous function)
Comment: @ExOfDe To understand exactly what your code is doing, you need to take a look at the assembly code. You can do that by compiling with `-S`. Or compile normally and look at the assembly with the debugger. There are a lot of factors that determine what the code will do in these cases (e.g. processor type, [ABI](https://en.wikipedia.org/wiki/Application_binary_interface), optimization level, etc.) so trying to explain undefined behavior is generally a wasted effort.
Comment: okay that is definitly something i did wrong, but how is it possible to get still the same values? i thought as soon i leave a function the stack of that function disappears into the nirvana?
Comment: This apparently was what happened. thanks alot for the explanation :D
Answer: This would only be true for n = 0. Rest assured that you cannot implement squaring using just the XOR operator, even for integral types.
The behaviour of your code is currently undefined, as you don't initialise either i, or result. I suspect that your loop does not run at all and by the most amazing coincidence, result occupies the same memory in the subsequent functions as it does in the Guassian function. But don't ever rely on that behaviour. Other compilers might simply attempt to eat your cat.
Comment: Analysing undefined behaviour is rather like trying to nail jelly to the wall. What JonnyMopp is saying is *probably* what is happening, but don't ever rely on that. Note that a *stack* is an *implementation* concept, not a *language* concept.
Comment: Okay that's true. Thanks a lot. But one question then remains: why got i still the same result? And why did this most amazing coincidence happend frequently?
Comment: crazy.... and i could not get my head around why that happend XD. just for got to initialise...
Comment: Similarly in `quadratIterativClassic` the local variable `int result;` is uninitialised therefore UB. Please turn on compiler warnings - it should have told you!
Comment: @Bathsheba I am aware of that fact that the stack is not a language concept, but thanks for pointing out it :D
Answer: #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
   int main(int argc, char const *argv[]){
    int i=0,n1;
     scanf("%d",&n1);

void quadratGauss(int n){
 printf("+quadratGauss: \n");
  int result = ((n*(n+1))*(2*n+1))/6;   // you made here mistake take 2 insted of 6.
  printf("Result: %d\n----------------\n",result);
 }

void quadratIterativClassic(int n){

  int result=0;
   printf("+quadratIterativClassic: \n");
     for(i=1;i<=n;i++)
       result += i * i;
  printf("Result: %d\n----------------\n",result);
 }

void quadratIterativeBitOperation(int n){
   int result=0;
   printf("+quadratIterativeBitOperation: \n");
    for(i=1;i<=n;i++)

    result += pow(i,2);  //This is power fun to add series of quadrat

    printf("Result: %d\n----------------\n",result);

  }
   //call the fun.
  quadratGauss(n1);
  quadratIterativClassic(n1);
  quadratIterativeBitOperation(n1);

  return 0;
 }

:) Want to more about http://www.trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm
https://en.wikipedia.org/wiki/Quadratic_Gauss_sum
Comment: yeah, that was a typo, but after getting so amazed that XOR would produce the same result i just didn't check the correctness of my math formular. but thanks pointing it out. and yeah there is an function  math.h. but the task was not to use it... to simple
Answer: First, its /6, not /2. See that quadratGauss is always 3 times the quadratIterativClassic. And I got completely different results for quadratIterativeBitOperation
n = 4
+quadratGauss:
Result: 90
----------------
+quadratIterativClassic:
Result: 30
----------------
+quadratIterativeBitOperation:
Result: 12
----------------
n = 5
+quadratGauss:
Result: 165
----------------
+quadratIterativClassic:
Result: 55
----------------
+quadratIterativeBitOperation:
Result: 19
----------------
n = 6
+quadratGauss:
Result: 273
----------------
+quadratIterativClassic:
Result: 91
----------------
+quadratIterativeBitOperation:
Result: 23

I think it your compiler must have ^ set as exponent instead of XOR
Comment: I do not think there is such an option for GCC neither for C or C++ or any other language. Except for languages who could overwrite operators which i did not


Probability of tic tac toe winning based on coin flips

Question: I was looking around this problem:
If two people randomly move in tic - tac - toe with random turns according to coin flips, what is the probability each wins (or that there is a draw)? In other words we fill an entire 3*3 matrix only according to coin toss. Intuitively it should be 50% for each player, but why?
SO we made 9 coin flips and we have for ex.(H,T,H,T,T,T,T,H,T)
According to this values we fill a game board with XorO rispectivelly.
Comment: How are you populating the squares?  "Heads is $X$" or something?  If so then you have to compute the probability of a stalemate, call that $\psi$, in which case the answer is $\frac 12\times (1-\psi)$.
Comment: No, it should be less than $50\%$ because of draws.
Comment: I don't see how this game is well-defined. Do we just proceed one square at a time, filling in $X$ or $O$ according to a coin flip, and continue until one side has three-in-a-row, or the board is full?
Comment: It seems to me that $X$ should have an advantage.
Comment: SO we made 9 coin flips and we have for ex.(H,T,H,T,T,T,T,H,T)
According to this values we fill a game board with XorO rispectivelly.
Comment: Ok, but what if 9 flips give you a board in which $X$ and $O$ *both* have three-in-a-row? Who wins then?
Comment: if nX=nO it will be a tie, if nX>nO X win
Answer: A tie can occur in the following ways.
First, we could get a board where nobody has 3-in-a-row. In that case, up to symmetry, the board must look one of the three tied positions you can achieve in tic-tac-toe:
X X O    X X O    X X O
O X X    O O X    O O X
X O O    X X O    X O X

There are $32$ boards in this category. For the first board, we can rotate it in $4$ ways, reflect it or not, and swap X with O or not, giving $16$ variations; for the second and third, reflections don't help (since they're symmetric) so we get $8$ variations of each.
Second, we could get a board where both players have one 3-in-a-row. No player can claim a diagonal: if that happens, there is no other 3-in-a-row for the other player to claim. Similarly, no player can claim both a vertical and a horizontal 3-in-a-row. So we are left with boards like this one:
X X X
O O O
X O O

There are $72$ boards in this category. We can choose in $2$ ways whether the 3-in-a-rows are vertical or horizontal. Once we do, we can permute the "win for X" line, the "win for O" line, and the third line in $3! = 6$ ways, and specify the outcomes along the third line in $2^3 - 2 = 6$ ways (it cannot be X X X or O O O, but any of the other outcomes are valid).
So the probability of a tie is $\frac{32 + 72}{2^9} = \frac{104}{512} = \frac{13}{64}$, leaving a probability of $\frac{51}{128}$ that X wins and a probability of $\frac{51}{128}$ that O wins. (Each of these is just over $39.8\%$.)


Json deserialization using java enums

Question: I'm trying to deserialize the following JSON to a java object.
"distance":[
  {
    "weight": 60,
    "unit": "km"
  },
  {
    "weight": 100,
    "unit": "m"
  }
]

The java object should look like:
[

  {
    "km": 60
  },
  {
    "m": 100
  }
]

Comment: Could you show us what you have tried?
Answer: The problem can be solved using JSONObject and HashMap

Use JSONObject to convert json string into java class object.
Loop items inside JSONObject to get distance and unit data.
Create HashMap object and put it inside ArrayList.

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class Main {
    public static void main(String args[]) throws JSONException {
        ArrayList<HashMap<String, Double>> result = new ArrayList<HashMap<String,Double>>();

        String jsonStr = "{\n" +
                "    \"distance\": [\n" +
                "        { \n" +
                "            \"weight\": 60, \n" +
                "            \"unit\": \"km\" \n" +
                "        }, \n" +
                "        { \n" +
                "            \"weight\": 100, \n" +
                "            \"unit\": \"m\" \n" +
                "        } \n" +
                "    ]\n" +
                "}";

        JSONObject json = new JSONObject(jsonStr);
        JSONArray distanceArray = json.getJSONArray("distance");

        for(int i = 0; i < distanceArray.length(); i++) {
            JSONObject distanceItems = distanceArray.getJSONObject(i);
            final String unit = distanceItems.getString("unit");
            final double weight = distanceItems.getDouble("weight");

            result.add(new HashMap<String, Double>() {{
                put(unit, weight);
            }});
        }

        System.out.println(result.toString()); // output [{km=60.0}, {m=100.0}]
    }
}

Answer: Here I have found two issues, One, it is not well formed JSON. It should be:
{
 "distance":[
   {
     "weight": 60,
     "unit": "km"
   },
   {
     "weight": 100,
     "unit": "m"
   }
 ]
}

OR
[
  {
    "weight": 60,
    "unit": "km"
  },
  {
    "weight": 100,
    "unit": "m"
  }
]

Another is, you did not mention your POJO clearly. You can achieve this response several ways. For simplicity I am assuming simple Map for it.
However, we need to make this string well formed at first.
String jsonStr = "\"distance\":[\n" +
                "  {\n" +
                "    \"weight\": 60,\n" +
                "    \"unit\": \"km\"\n" +
                "  },\n" +
                "  {\n" +
                "    \"weight\": 100,\n" +
                "    \"unit\": \"m\"\n" +
                "  }\n" +
                "]";
jsonStr = jsonStr.substring(jsonStr.indexOf(":") + 1);

Create a class:
@Data
public class Distance {
    private Double weight;
    private String unit;
}

Here I have used lombok for getter and setter.
Parse JSON string to list of Distance:
ObjectMapper objectMapper = new ObjectMapper();
List<Distance> distances = objectMapper.readValue(jsonStr, new TypeReference<List<Distance>>(){});

Now you can convert this list to your desired response. For converting this response to Map:
Map<String, Double> response = distances.stream().collect(Collectors.toMap(Distance::getUnit, Distance::getWeight));

OR, you can convert it to List<Pair<String, Double>> as well:
List<Pair<String, Double>> response = new ArrayList<>();
distances.forEach(distance -> {
    response.add(new Pair(distance.getUnit(), distance.getWeight()));
});

Happy coding...

Json deserialization using java enums


How to calculate homography matrix of plane using the homography of its orthogonal plane?

Question: I have an image of a 3D object cast on two orthogonal planes. I have a homography matrix of one of these planes. I want get the homography for the other plane.
my question explicitly is:
1- Can I compute or convert the homography of one plane  directly as homography to the other plane?
2- If not, what other data do I need to add to the current homography in one plane  to compute the other one? And, what is the algorithm to use?
Thanks.
Comment: What do you mean by "I have an image in of 2 orthogonal planes"? What kind of image? A planar projection of the 3d scene? What do you mean by having the homography matrix of one of these planes? The matrix which maps one of these planes from 3d space into your 2d image space?
Answer: I found the answer.
Mathematically there is no way to do what I asked for. but by adding some other information it is reachable.
in this context: (I assumed a projective transformation as I was working with camera modeling and 3D image processing)
either of following can give us enough information to compute other H matrix:
C :camera position
Vz : vanishing point in Z direction
etc... (there are other measurable parameters that also work)


Pool data from two different points of time with different attendants

Question: I have two samples (each nurses) one from 2008 and the other drawn 2013. Both got the same questionaire to fill out. Now I would like to pool the data but do not know if I just can do it. My idea was to check if demographics of the attandents have the same distribution using a two sample KS. I also would perfom a t-test on the item I would like to pool and use for my analysis or maybe test if the standard deviations but do not differ but I do not know if this is enough. It would be great if I could get some advice here.
Comment: Of course you can pool the data. Are you planning to use a particular software? This can be easily implemented in Stata. I can provide an answer for it.
Comment: I am using R or SPSS unfortunately I do not use Stata.
Comment: They are beyond my knowledge. But just google two sample KS R or SPSS. I'm sure there are plenty of examples.
Answer: Whether or not it makes sense to pool your data is as much a question for an expert in your field as it is a statistics question. There are a few questions that you can ask yourself to decide if it makes sense:

Is there any reason for you to believe that the two populations are different? For example, were the respondents from very different hospitals (large institutions in the first one, small ones in the second); or from different countries? If the answer is yes, you will need to find ways to account for this difference in your analysis.
What type of analysis are you planning to do? If you are doing some regression, controlling for which survey the respondent answered might be enough.

The fact that there are several years between the two survey might need to be accounted for in your analysis. It is possible that between 2008 and 2013, the nurse population has changed a lot. This would lead to differences in the correlation between your survey items between the two groups that are real differences rather than random variation. If this is the case, you need to account for the difference between the group but also ask yourself if it makes sense to treat those two samples as representative of the same population.
Even if you decide pooling the data makes sense, it will probably be necessary to account for which survey a respondent answered (in a regression context, that would be a control variable). Gelman and Hill (2007) have a good discussion of pooling in the context of multilevel models (chapter 12, p.252-259), which I think explain neatly the difference in results you can expect from pooling your data with and without a control variable for which group a respondent belongs to.


Chord Theory Basics

Question: I really do not understand piano chord theory and how to do inversions (are first and second the only ones?),and the numbers on chords (i.e. Cm13; C Sharp 7 etc.) how can I make myself understand this better?  Are there better books on this?
All the books presume knowledge but I want something very basic or a basic web site or video somewhere.
Comment: Questions seeking external resources are off-topic here, but there are already lots of questions and answers about chords and inversions on the site. Try looking at questions under the [tag:chords] tag for starters: there are 1089 questions there at the moment.
Comment: See also [tag:chord-theory]!
Answer: There are as many inversions as there notes in the chord.  A triad (3 notes) has three inversions - called root position, first inversion and second inversion - any of the three notes may be at the bottom.   A seventh chord (4 notes) has four inversions.    We don't normally go beyond this point - a C9 chord voiced as D, E, G, Bb, C COULD be called 'C9, fourth inversion' but generally isn't!
On piano, distinguish between 'voicings' and 'inversions'.   Voicing is about texture, how notes are spaced. Inversion is about harmony, which note is the lowest.  There's no point in talking about the 'inversion' of a RH chord on piano when there's a LH note as well.  That's the one that defines the inversion.
Comment: I see your point about a triad having three inversions, but we normally call them root position, first inversion, and second inversion, no? Saying "three inversions" may be a bit confusing; a beginner may conflate "root position" with "first inversion" and get in a whole mess of trouble.
Comment: Nice, clean, to the point.
Comment: An inversion is a change from an original. So with three notes to play with, so to speak, there's an original (root) and only *two* inversions. Yes, it's slightly pedantic, but what you state may confuse someone at the stage  the OP is, at the moment.
Answer: Using a triad as a start point. Three notes which make up a standard chord. It's 1,3 and 5. Let's take G major. That's G B D. With the G (chord note name) at the bottom, it's called root position. Put the B as the bottom note, it's now 1st inversion. Now put D underneath, it's 2nd inversion.
With either of the other two notes either way round, those names still stand. It could be a closed chord, with the 3 notes as close as possible to each other, or a open chord, where there's a missing note, which could be played but isn't, in between a couple of notes that are played.
That's simple chords. Major and minor. The numbers game is next. Generally, after 1,3,5, comes 7. The 7th note in the scale is added to the original triad. C maj 7 adds the maj.7th note. Cm7 adds the minor 7th note. When we see C7, it's short for C dominant 7, and uses the maj. triad, but adds a m7.
That's it for now, as you can probably guess what 9, 11, 13 might entail. Suffice to say that numbers larger than 7 will often also contain the 7th note  as well. There's more later, maybe.

Chord Theory Basics


Divide a dict by a number (int)

Question: i have a problem, i have to create a fuction that divide my dict by a int.
This is my dict:
Counter({1: [9, 10, 1], 2: [5, 1, 1, 2, 1, 1, 9, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1], 0: [1, 5, 1, 1, 2, 10, 1, 2, 1, 2, 2, 1, 1]})

And this is my function:
def probabilitacondizionata(lista, sommafreq):
    lista= {k: v / sommafreq for k, v in lista.items()}
    return lista

And this is the function, which sum the value(int) sommafreq:
def sommafrequenze(lista):
    sommafreq= sum(lista.values())
    return sommafreq

This instruction gives me this error: unsupported operand type(s) for /: 'dict_values' and 'int' ..
The output i would is like:
Counter({1: [9/sommafreq, 10/sommafreq, 1/sommafreq], 2: [5/sommafreq, 1sommafreq, 1/sommafreq, 2/sommafreq, 1/sommafreq, 1/sommafreq, 9, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1], 0: [1, 5, 1, 1, 2, 10, 1, 2, 1, 2, 2, 1, 1]})

and keep on going to divide all.. Sorry for my bad english and thanks in advance!
Edit: My previous functions:
def ricercafrequenze(trainspam, testspam):
    filtratespam=Counter()
    filtratespam ={k:v for (k,v) in trainspam.items() if k in testspam}

    return filtratespam
    #main
def ricerchefrequenzeinlista(lista1,lista2):
    lista=Counter()
    i=0
    while i < len(lista2):
       lista[i]=(ricercafrequenze(lista1, lista2[i]))
       i+=1
    return lista

Counter({0: {'offer': 1, 'time': 5, 'discount': 1, 'one': 1, 'th': 2, 'subject': 10, 'special': 1, 'need': 2, 'price': 1, 'order': 2, 'product': 2, 'per': 1, 'today': 1}, 1: {'us': 9, 'subject': 10, 'buy': 1}, 2: {'time': 5, 'realist': 1, 'quickli': 1, 'give': 2, 'go': 1, 'thoma': 1, 'us': 9, 'let': 1, 'aruba': 1, 'natur': 1, 'b': 3, 'length': 1, 'ca': 1, 'one': 1, 'know': 2, 'life': 1, 'think': 1, 'girlfriend': 1, 'use': 2, 'stronger': 1, 'press': 1, 'longer': 1, 'fl': 1, 'po': 1, 'partner': 1, 'subject': 10, 'presid': 1, 'save': 1, 'nearli': 1, 'stud': 1, 'short': 1, 'everi': 3, 'gain': 1, 'citi': 1, 'product': 2, 'said': 1, 'increas': 1, 'month': 1, 'unit': 3, 'want': 4, 'must': 1, 'sex': 1, 'pleasur': 1, 'result': 3, 'matt': 1, 'name': 4, 'love': 1, 'bigger': 1, 'visitor': 1, 'oranjestad': 1}})

Comment: Why don't you just divide the sum instead? You need to divide each item within the list: `{k: [x / sommafreq for x in v] for ... }`, but your current code shouldn't give the error you claim. Can you provide a [mcve] with full traceback?
Comment: That's not a problem with my suggestion,;`lista` is apparently the values of the dictionary, not the dictionary itself.
Comment: thanks but, i gives me this error: AttributeError: 'dict_values' object has no attribute 'items'
Answer: If sommafrequenze function is dedicated to sum up the values of the initial list - use the following simplified approach:
def probabilitacondizionata(lista, sommafreq):
    lista = {k: [v / sommafreq for v in v] for k, v in lista.items()}
    return lista

l = {1: [9, 10, 1], 2: [5, 1, 1, 2, 1, 1, 9, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1], 0: [1, 5, 1, 1, 2, 10, 1, 2, 1, 2, 2, 1, 1]}
l_sum = sum(v for sublist in l.values() for v in sublist)

print(probabilitacondizionata(l, l_sum))

The output:
{0: [0.007194244604316547, 0.03597122302158273, 0.007194244604316547, 0.007194244604316547, 0.014388489208633094, 0.07194244604316546, 0.007194244604316547, 0.014388489208633094, 0.007194244604316547, 0.014388489208633094, 0.014388489208633094, 0.007194244604316547, 0.007194244604316547], 1: [0.06474820143884892, 0.07194244604316546, 0.007194244604316547], 2: [0.03597122302158273, 0.007194244604316547, 0.007194244604316547, 0.014388489208633094, 0.007194244604316547, 0.007194244604316547, 0.06474820143884892, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.02158273381294964, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.014388489208633094, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.014388489208633094, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.07194244604316546, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.02158273381294964, 0.007194244604316547, 0.007194244604316547, 0.014388489208633094, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.02158273381294964, 0.02877697841726619, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.02158273381294964, 0.007194244604316547, 0.02877697841726619, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547, 0.007194244604316547]}

Comment: thanks but always the same problem,  File "C:/Users/david/prova.py", line 141, in probabilitacondizionata
    {k: [v / sommafreq for v in v] for k, v in lista.items()}

AttributeError: 'dict_values' object has no attribute 'items'
Comment: you have shown your dict as `Counter` argument, can you show the initial dict in its actual form ? Compare your dict with that one in my answer
Answer: You have two possibilities:
1. Use numpy (as you have dicts as lista values, this is not applicable):
    import numpy as np
    def probabilitacondizionata(lista, sommafreq):
        lista= {k: np.array(list(v)) / sommafreq for k, v in lista.items()}
        return lista

2. Use dict comprehension:
    def probabilitacondizionata(lista, sommafreq):
        lista= {k: {k_i: v_i / sommafreq for k_i, v_i in v.items()} for k, v in lista.items()}
        return lista

Comment: Thanks for the two solutions , i tried the first: TypeError: unsupported operand type(s) for /: 'dict_values' and 'int'   and the second but,
it gives me this error: AttributeError: 'dict_values' object has no attribute 'items' –
Comment: That's due to usi.ng Python 3. Try to wrap `v` in a list, as in the edit
Comment: It gives me the same error, AttributeError: 'dict_values' object has no attribute 'items'.. But is a counter not a dict.. can be this the problem?
Comment: The error says that `lista` is of type `dict_values` (and hence is not a dict). The error you are getting is because you are calling `probabilitacondizionata` having not a dict, but its values as a parameter
Comment: i discovered that is a  my lista
Comment: Ok, then your `lista` has dicts as values, and not lists as you wrote originally. Then it explains everything, and you need not a list, but a dict comprehension.
Comment: how can i do it? the previous wasn't? was a list comprehension?
Comment: Where? But below they post me a dict comprehension but it doesn't work.. Can i convert this dict a list?
Comment: thanks, but always the same error 'dict_values' object has no attribute 'items'
Answer: As mentioned in the comment, you can just evaluate the sum and then divide by a value to achieve the same thing. Anyways, you can divide every element like this:
Counter({k:[i/sommafreq for i in v] for k,v in lista.items()})

Comment: thanks but, i gives me this error: AttributeError: 'dict_values' object has no attribute 'items' –
Comment: @ErikGodard, no python 2 also has items(), so this is not a python 2/3 issue. May be OP is applying `.items()` on a list.
Comment: No i use python version 3.5 :(
Comment: Can be the problem the type of sommafreq? it is a int
Comment: @DavideDiMenna, No I have tested it with int value, and this is fine. Problem is in your side. Could you show us the output of `print type(lista)`?
Answer: I often wanted to do this type of thing without using dict comprehensions. BetterDict is a little project of mine that extends Python dicts/Counters/defaultdicts/OrderedDicts, allowing them to be merged, or used in arithmetic with scalars or other dicts.
eg
>>> raw_counts = BetterDict({'the': 1432, 'she': 600, 'wookie': 25})
>>> total = 10000.
>>> relative_freqs = raw_counts / total
>>> print(relative_freqs)
{'she': 0.06, 'the': 0.1432, 'wookie': 0.0025}

Divide a dict by a number (int)


Locally closed subset of an l-space is also an l-space.

Question: I am trying to prove that a locally closed subset of an l-space is also an l-space.
An l-space is defined as a Hausdorff, locally compact, zero-dimensional topological space.
I am having difficulty in proving the locally compact part. I know it is true that a closed subset of a locally compact space is locally compact. Is it also true for a locally closed subset? Thanks!
Answer: As we are working in Hausdorff spaces, all usual definitions of local compactness are equivalent. (i.e. each point having a compact neighbourhood, or having a base of compact neighbourhoods, or having a local base with compact closures etc.).
All subspaces of a zero-dimensional (in the sense of having a clopen base) spaces are trivially zero-dimensional again, so we need not bother about that aspect of what the OP calls $l$-spaces. Likewise for Hausdorffness.
A locally closed subset $A$ of $X$ is by definition a subset of the form $A = O \cap C$ where $O$ is open in $X$ and $C$ is closed in $X$.
$C$ in the subspace topology is locally compact (as a closed subspace) and $A = O \cap C$ is thus an open subspace of a locally compact subspace $C$) and thus in turn locally compact in its subspace topology too.


A question about the minimal polynomial of a transformation.

Question: My Linear Algebra textbook states:

Say the minimal polynomial of the transformation $T$ is $m(x)=p_1(x)^{e_1}p_2(x)^{e_2}\cdots p_s(x)^{e_s}$. Then $$n(p_i(T))^{e_1}$$, which is the null space associated with the transformation $n(p_i(T))^{e_1}$, is $T$-invariant.

Shouldn't $n(p_i(T))^{y}$ be $T$-invariant for all $1\leq y\leq e_i$, where $y\in\Bbb{N}$?
Reason: Take $v\in n(p_1(T))$. The minimial polynomial $m(x)$ can be written as $p_1(x)^{e_1-1}p_2(x)^{e_2}\cdots p_s(x)^{e_s}p_1(x)$. For any vector $v\in n(p_1(T))$, we can see that $m(T) (v)=0$. This is true for all powers of $p_i(T)^{e_1}$
Thanks.
Comment: Could someone help please?
Answer: Your reasoning is correct. Note that your textbook does not state that the null spaces of the other powers are not invariant. Also note that the following more general statement holds.  Let $f\in K[X]$ be any polynomial over the field $K$, which should be the same field as the one over which you're considering $V$. I claim that the null space of $f(T)$, $T$ being a linear map $V\to V$, is $T$-invariant.
To see this, write $f=\sum_{k=0}^n a_k X^k$ and let $v \in \ker(f(T))$. Then we have
$$f(T)(Tv)=\sum_{k=0}^n a_k T^k (Tv) = T \sum_{k=0}^n a_k T^k v = T (0) = 0.$$
So the null space (or "kernel", $\ker$ for short) of any polynomial in $T$ is an invariant subspace (if you are unsure that this is really a subspace, you should go ahead and try to prove this yourself).


Zero divisors and units for the ring $\mathbb{Z}/n\mathbb{Z}$ with integer $n$

Question: Given the ring $ \mathbb{Z}/n\mathbb{Z} $ is always true that $ \mathbb{Z}/n\mathbb{Z}=[\text{zero divisors}]\cup[\text{units}] $

How can evaluate the zero divisors and units ?

I believe that $ a x=0 \pmod n $ for zero divisor
and $ ax=1 \pmod n $ for units
I know how to solve a congruence but what is $a$ ?? thanks.
What are the generators of the group $ \mathbb{Z}/n\mathbb{Z} $ under the addition '+' and product '$\times$'?
Answer: Hint $ $ If $\rm\,a\in\rm\color{#c00}{finite}$ ring $\rm\,R\,$ then $\,\rm x\to ax\,$ is onto $\rm\color{#c00}{iff}\ 1$-$1,\,$ so $\rm\,a\,$ is a unit iff $\rm\,a\,$ is not a zero-divisor.
Answer: After reading the question , I wondered which rings $A$ have the property that every element in $A$ is a unit or is a zero-divisor.
1) If the zero ideal has a primary decomposition (which is always the case for a noetherian ring), then the set of  zero divisors is the union  of the associated primes of the ring: $zdiv(A)=\bigcup _{{\mathfrak p}\in Ass(A)}\mathfrak p$ so that the condition for the property is that every maximal ideal of $A$ be an assassin.
This holds for all artinian rings (e.g. the ring $\mathbb Z/n\mathbb Z$ of the question ), but also for higher dimensional rings, like   the one-dimensional localization $A=R_{\mathfrak m}$ of the notorious ring $R=k[X,Y]/(X^2, XY)=k[x,y]\quad (k \text { a field})$ at the maximal ideal $\mathfrak m=(x,y)$.
Notice that a primary decomposition of $(0)$ is $(0)=(x)\cap {\mathfrak m}^2$ and that  $Spec (A)=Ass(A)=\lbrace\mathfrak m,(x)\rbrace$, so that $zdiv(A)=\mathfrak m$ .
2) Some non-noetherian rings also have the property that every non-unit is a zero-divisor.
Class of examples: rings with only one prime ideal, like the non-noetherian $$A=k[X_1, X_2,...,X_n,...]/(X_1^2,..., X_n^2,...) $$
WARNING Needless to say, this post is absurdly highbrow with respect to the actual question.
As Gadi remarks,  the answer to  Jose's question is to be found in fairly elementary algebra or number theory books.
I just wanted to address a more general question which might (or might not!) be of interest to more advanced users of our site.
Comment: Such rings are sometimes called *quasi-regular*, as I mention in my [post here](http://math.stackexchange.com/a/95248/242) on embedding  rings into quasi-regular rings.
Comment: Ah, that's very interesting: thanks a lot for the word and the link, @Bill . I was a 100% sure that such an elementary property must have been investigated, but I had no idea what keyword to use to search the literature.
Comment: I've asked the exact same question in MO:  http://mathoverflow.net/questions/42647/rings-in-which-every-non-unit-is-a-zero-divisor
Comment: Thanks a lot to you too, @lhf: the link is very rich and interesting. It is a little ironic that I thought I was explaining results to  others  and it turns out that I'm the one who is learning from users! Ironic but very pleasant!
Comment: @GeorgesElencwajg, yes, I've experienced the same surprise. I've learned a lot from all those generous and knowledgeable people here.
Answer: The general rule is that $a$ is a unit modulo $n$ is and only if it is prime to $n$, i.e. $\gcd(a,n)=1$. This is proven in every basic algebra/number theory textbook (for example, Dummit and Foot's "Abstract Algebra") but is so easy you can prove it on your own (use the fact that if $\gcd(a,b)=d$ then there exists integers $x,y$ such that $ax+by=d$).
As for the other question - $\mathbb{Z}/n\mathbb{Z}$ is not a "group" if you talk about two operations, but a ring, and "generators" is not very clear. Still, if I understand your basic question, there's a nice discussion of the structure of  $\mathbb{Z}/n\mathbb{Z}$ for all values of $n$ in (for example) Ireland and Rosen's "Classical introduction to modern number theory" (and I think Dummit and Foote cover it as well). As before, this is a very standard result, given almost in every book on the subject.


unexpected behavior when reading a text file into array using javascript

Question: I am writing a emulator and I am trying to compare opcode logs from another working emulator. I have a log of executed opcodes ready to be compared it looks something like this
//log.txt (10000 lines long)
0
195
33
195
18...

I am reading this text file into a array using this code that looks kinda like this
//CPU.js
let log  = fs.readFileSync("./log.txt").toString().split("\n"); // read file
let logCount = 0;
function executeOP(){
let opcode = memoryRead(PC.inc()); // get opcode
  if(opcode != parseInt(log[logCount])){ // convert string to number and compare opcodes
    console.log("failed opcode " + log[logCount]); // print out failed opcode
    console.log("failed at line " + logCount); // print out failed opcode position
  }
  logCount++ // index of next opcode to compare
....
}

The problem is that parse in evaluates to NaN randomly on certain places in the test log array. It seems that extra invisible character example
console.log(log[2]) // 33
console.log(log[2][0]) // invisible
console.log(log[2].length) // 3? should be 2

I have tried correcting the array with (didn't work for me)
for(let i = 0; i < log.length; i++){
 log[i] = log[i].trim();
}
// also
for(let i = 0; i < log.length; i++){
 log[i] = log[i].replace(/(\r\n|\n|\r)/gm,"");
}

similar issue thread Loading text file in Javascript adds unexpected extra hidden characters
Thank you
Answer: I've tried simple solution on replicated textfile and I don't really see any issue.
const fs = reqiure('fs-extra')
const text = fs.readFileSync("./data.txt").toString().split("\r\n")

console.log(text[2][1]) // 3

Potential problem is with \n in your split function, in this code there is used \r\n to split these lines at glance, optionally you're able to use library dedicated for working on massive text-data, I've used that library for larger linear progression in node.js so maybe it will be useful for you, it's called skale.
Answer: turn out it was a few zero width spaces very frustrating but a simple fix
    for(let i = 0; i < log.length; i++){
        log[i] = log[i].replace(/\u200B/g,"");
    }


Show that if $a, b$, and $c$ are integers with $(a,b)=(a,c)=1$, then $(a,bc)=1$

Question:
Show that if $a, b$, and $c$ are integers with $(a,b)=(a,c)=1$, then
  $(a,bc)=1$

I don't know exactly that I should use the division algorithm
or $(a,b)=d$, $(a/d,b/d)=1$.
This is my first time to study number theory...
it's very hard...T^T I can't understand basic thms in this study...
Answer: Assume $(a,bc)=d>1$. Then $d$ divides $a$ and $bc$. If $p$ is a prime divisor of $d$ then $p$ divides $a$ and $bc$, hence it divides $b$ or $c$ (definition of being prime). This is absurd because $p$ would divide either $(a,b)$ or $(a,c)$.
Answer: Suppose $p$ is a prime number such that $p|(a,bc)$. Then
$$p|a\text{ and }p|bc$$
Since $p$ is a prime number, by Euclid's Lemma $p|b$ or $p|c$ (or both). But if $p|b$, then $(a,b)\geq p$, contradiction. The same applies for $c$. Thus, $(a,bc)=1$.


Deny delete permission when saving file from IE

Question: I am trying to setup an networkshare in which users can add/write files but are not able to delete them. So I tried this with special permissions:
Domain\Usergroup - Special Permissions Allow Special Permission except 2 options: Delete subfolders and files and Delete
Domain\Usergroup - Special Permissions Deny Delete subfolders and files and Delete
This works right as long as I work from Word/Excel etc. The problem is that when I try to save a file from Internet Explorer an error occurs:
You are not able to change files in this networklocation. Please contact your system manager....
If I check the destination folder I can see the file but it's only 0 kb...
Comment: IE 9 and + got builtin a download manager that create amd erase .partial file, check with process monitor if its not that feature that stop you.
Answer: Can you download the file to your C-drive and then manually copy the file to the network share?
When you download something in Internet Explorer, it is firstly saved to a temp location on your local drive, and will then be copied to the network location
Comment: Yes if I download it to my harddrive I can than afterwards copy it to the networkshare. Because it is a webapplication I need to be able to directly save tot the share


If I have the expected value of the logarithm of a RV, can I obtain the expected value of the RV itself?

Question: Assume that $\text{E}[\log(X)] $ is given, can I derive $\text{E}[X]$ in a closed form format?
Comment: Pretty much all you can say is that $\mathrm{E}[\log(x)] \leq \log \left( \mathrm{E}[x] \right)$ due to [Jensen's inequality](https://en.wikipedia.org/wiki/Jensen%27s_inequality).
Comment: Do you know the *distribution* of log x or x? Eg. is is $x$ normally distributed? In the most general case with $x$ following some arbitrary distribution, you won't be able to say much.
Comment: No. Only the mean value of the log(x) is given.
Answer: No.
For example, if $X$ follows a log normal distribution, where $\log(X) \sim N(\mu,\sigma)$, then $E[\log(x)] = \mu$ and is independent of $\sigma$. However, its mean is $E[X] = \exp \left(\mu + \frac{\sigma^2}{2} \right)$. Clearly, you cannot derive a $\sigma$ dependent number from a $\sigma$ independent number.
Comment: Or for a super-simple example, consider discrete random variables X (taking value 1 with probability 1/3 and 10 with probability 2/3), and Y (taking value 1 with probability 2/3 and 100 with probability 1/3). Then E[log X] = E[log Y] = 1/3 (or some other number if you prefer your logarithms taken to a more sensible base than 10, but still equal since in any base log 100 = 2 log 10). However E[X] != E[Y].


UPPER_CASE naming style in __init__.py in Python Flask

Question: I am wondering what the proper convention is for the init file in Python Flask.
Is there a way to format an init file in such a way in Flask that all the variables are not interpreted as constants? Currently my Pylint is saying that all the variables such as 'app' need to be renamed to be compliant with the UPPER_CASE naming style.
import logging
from logging.handlers import RotatingFileHandler, SMTPHandler
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_mail import Mail
from config import Config

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
mail = Mail(app)

from app import routes, models, errors

if not app.debug:
    if app.config['MAIL_SERVER']:
        auth = None
        if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
            auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
        secure = None
        if app.config['MAIL_USE_TLS']:
            secure = ()
        mail_handler = SMTPHandler(
            mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
            fromaddr='no-reply@' + app.config['MAIL_SERVER'],
            toaddrs=app.config['ADMINS'], subject='Microblog Failure',
            credentials=auth, secure=secure)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
    if not os.path.exists('logs'):
        os.mkdir('logs')
    file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240,
                                       backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)

    app.logger.setLevel(logging.INFO)
    app.logger.info('Microblog startup')

Comment: pylint requires all variables in the outermost scopes to be constants. Could you try putting your main code in an `if __name__ == '__main__':`?
Answer: As per pylint's definition, any variable at the module level is a constant.
as @adrianp suggested in the comment move the entire code into a
method (say run_stuff) and invoke it by
if __name__ == '__main__':
    run_stuff()


Java binary literals - Value -128 for byte

Question: Since SE 7 Java allows to specify values as binary literal. The documentation tells me 'byte' is a type that can hold 8 Bit of information, the values -128 to 127.
Now i dont know why but i cannot define 8 bits but only 7 if i try to assign a binary literal to a byte in Java as follows:
byte b = 0b000_0000;    //solves to the value 0
byte b1 = 0b000_0001;   //solves to the value 1
byte b3 = 0b000_0010;   //solves to the value 2
byte b4 = 0b000_0011;   //solves to the value 3

And so on till we get to the last few possibilitys using those 7 bits:
byte b5 = 0b011_1111;   //solves to the value 63
byte b6 = 0b111_1111;   //solves to the value 127

If i want to make it negative numbers i have to add a leading - in front like this:
byte b7 = -0b111_1111;   //solves to the value -127

Now half of the problem i have is that i use just 7 bits to describe what they tell me is a 8 bit data type. Second half is that they dont seem to be threaded as twos complement unless using a 32bit int type where i can define all of the 32 bits ("sign indicator bit" included).
Now when i search on how to display the in-range number -128 i was told to do it this way without any further explanation:
byte b8 = 0b1111_1111_1111_1111_1111_1111_1000_0000;

I can clearly see that the last 8 Bit (1000 0000) do represent -128 in twos compelment using 8 Bit, still i never was confused more and try to ask my questions:

Isnt the above 32 bit long nr a 32 Bit (java-) int value?
Why can i assign a 32 bit value to a 8 bit (java-) byte type?

Or in general: Why do i have to assign it this way?
Any links/ informations about this would be great!
Thank you for the time you took to read this as well as any further information in advance.
Regards
Jan
Comment: does `byte b8 = 0b1000_0000` work, also look up 2's complement binary representation
Comment: No    byte b8 = 0b1000_0000  does not work, unfortunately i lost the scientific focus on this question but i think that this is expected to not work.

Interesting however that there never was a full answer on this question, need to check how to set a reward on it.
Answer: According to the Java Specification,
http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1
all your declarations (b, b1,..., and b8) use int literals, even when they would fit in a byte. There's no byte literal in Java, you can only use an int to initialize a byte.
I did some tests and byte neg128 = -0b1000_0000; works fine. 0b1000_0000 is 128, so you just need to put a - sign before it. Notice that that 1 is not a sign bit at all (don't think about 8-bit bytes, think about 32-bit ints converted to bytes). So if you want to specify the sign bit you need to write all 32 bits, as you have demonstrated.
So byte b8 = 0b1000_0000; is an error just like byte b8 = 128; is an error (+128 does not fit in a byte). You can also force the conversion with a cast:
byte b = (byte) 0b1000_0000;
or
byte b = (byte) 128;
The cast tells the compiler that you know 128 does not fit in a byte and the bit-pattern will be reinterpreted as -128.
Comment: Oh, I too was somewhat surprised that 0b1000_0000 is not sign-extended automatically in this case. :-)


Adding relationships in NSManagedObjectModel to programmatically created NSEntityDescription

Question: When you write a static library which uses CoreData there's a big mess including a normal .xdatamodeld file into the project because you simply cannot just link its compiled version (.momd) into your binary, so it's better to create the whole NSManagedObjectModel in the code like this:
NSAttributeDescription *dateAttribute = NSAttributeDescription.new;

dateAttribute.name = @"timestamp";
dateAttribute.attributeType = NSDoubleAttributeType;
dateAttribute.optional = NO;
dateAttribute.indexed = YES;

NSAttributeDescription *payloadAttribute = NSAttributeDescription.new;

payloadAttribute.name = @"payload";
payloadAttribute.attributeType = NSBinaryDataAttributeType;
payloadAttribute.optional = NO;
payloadAttribute.indexed = NO;

NSEntityDescription *entry = NSEntityDescription.new;

entry.name = entry.managedObjectClassName = NSStringFromClass(MyCustomEntry.class);
entry.properties = @[dateAttribute, payloadAttribute];

NSManagedObjectModel *mom = NSManagedObjectModel.new;

mom.entities = @[entry];

And everything is just perfect....
But! Wait, if I have more than one entity in my NSManagedObjectModel and they are related (to-many, inversed, and so on), how in the world I gonna connect them in the code, like in example above, without that nice Xcode editor, where you make relationships with several mouse clicks?
Example
Imagine, we have a class MyCustomElement, which is almost the same as in MyCustomEntry from the code above. Now, here're their interfaces how they would appear if I used Xcode generation for entities:
@interface MyCustomEntry : NSManagedObject

@property (nonatomic, retain) NSNumber *timestamp;
@property (nonatomic, retain) NSData *payload;
@property (nonatomic, retain) MyCustomElement *element;

@end

@interface MyCustomElement : NSManagedObject

@property (nonatomic, retain) NSNumber * timestamp;
@property (nonatomic, retain) NSString * identifier;
@property (nonatomic, retain) NSSet *entries;

@end

@interface MyCustomElement (CoreDataGeneratedAccessors)

- (void)addEntriesObject:(MyCustomEntry *)value;
- (void)removeEntriesObject:(MyCustomEntry *)value;
- (void)addEntries:(NSSet *)values;
- (void)removeEntries:(NSSet *)values;

@end

What NSRelationshipDescription I need to create for them and how to init it?
Answer: Relationships are described by NSRelationshipDescription objects. The following code creates two entity descriptions for "MyCustomEntry", "MyCustomElement" with relationships

entries (MyCustomElement --> MyCustomEntry, to-many),
element (MyCustomEntry --> MyCustomElement, to-one), inverse of entries.

Both entities have only a string attribute "identifier" (to save some lines of code).
Objective-c:
NSEntityDescription *entry = [[NSEntityDescription alloc] init];
[entry setName:@"MyCustomEntry"];
[entry setManagedObjectClassName:@"MyCustomEntry"];

NSAttributeDescription *entryIdAttribute = [[NSAttributeDescription alloc] init];
entryIdAttribute.name = @"identifier";
entryIdAttribute.attributeType = NSStringAttributeType;

NSEntityDescription *element = [[NSEntityDescription alloc] init];
[element setName:@"MyCustomElement"];
[element setManagedObjectClassName:@"MyCustomElement"];

NSAttributeDescription *elementIdAttribute = [[NSAttributeDescription alloc] init];
elementIdAttribute.name = @"identifier";
elementIdAttribute.attributeType = NSStringAttributeType;

// To-many relationship from "Element" to "Entry":
NSRelationshipDescription *entriesRelation = [[NSRelationshipDescription alloc] init];

// To-one relationship from "Entry" to "Element":
NSRelationshipDescription *elementRelation = [[NSRelationshipDescription alloc] init];

[entriesRelation setName:@"entries"];
[entriesRelation setDestinationEntity:entry];
[entriesRelation setMinCount:0];
[entriesRelation setMaxCount:0]; // max = 0 for to-many relationship
[entriesRelation setDeleteRule:NSCascadeDeleteRule];
[entriesRelation setInverseRelationship:elementRelation];

[elementRelation setName:@"element"];
[elementRelation setDestinationEntity:element];
[elementRelation setMinCount:0];
[elementRelation setMaxCount:1]; // max = 1 for to-one relationship
[elementRelation setDeleteRule:NSNullifyDeleteRule];
[elementRelation setInverseRelationship:entriesRelation];

[entry setProperties:@[entryIdAttribute, elementRelation]];
[element setProperties:@[elementIdAttribute, entriesRelation]];

NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] init];
[mom setEntities:@[entry, element]];

Swift (now updated for Swift 3/4):
let entry = NSEntityDescription ()
entry.name = "MyCustomEntry"
entry.managedObjectClassName = "MyCustomEntry"

let entryIdAttribute = NSAttributeDescription()
entryIdAttribute.name = "identifier";
entryIdAttribute.attributeType = .stringAttributeType;

let element = NSEntityDescription()
element.name = "MyCustomElement"
element.managedObjectClassName = "MyCustomElement"

let elementIdAttribute =  NSAttributeDescription()
elementIdAttribute.name = "identifier"
elementIdAttribute.attributeType = .stringAttributeType

// To-many relationship from "Element" to "Entry":
let entriesRelation = NSRelationshipDescription()

// To-one relationship from "Entry" to "Element":
let elementRelation = NSRelationshipDescription ()

entriesRelation.name = "entries"
entriesRelation.destinationEntity = entry
entriesRelation.minCount = 0
entriesRelation.maxCount = 0  // max = 0 for to-many relationship
entriesRelation.deleteRule = .cascadeDeleteRule
entriesRelation.inverseRelationship = elementRelation

elementRelation.name = "element"
elementRelation.destinationEntity = element
elementRelation.minCount = 0
elementRelation.maxCount = 1 // max = 1 for to-one relationship
elementRelation.deleteRule = .nullifyDeleteRule
elementRelation.inverseRelationship = entriesRelation

entry.properties = [entryIdAttribute, elementRelation]
element.properties = [elementIdAttribute, entriesRelation]

let mom = NSManagedObjectModel()
mom.entities = [entry, element]

I have tested this code and it seems to work, so I hope that it will be useful to you.
Comment: Kudos to @idanuda for adding a Swift version!


Sending piped commands via python3 subprocess

Question: I am trying to execute the following subprocess command via python3.4
cd /home/mailer-domains/domain | rndc loadkeys domain

I have tried numerous methods using .call and .Popen but it either doesn't like my pipe or it doesn't like my switch
>>> subprocess.call(['cd /home/mailer-domains/'+domain, '|', 'rndc', 'loadkeys', domain])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/subprocess.py", line 537, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/usr/local/lib/python3.4/subprocess.py", line 859, in __init__
    restore_signals, start_new_session)
  File "/usr/local/lib/python3.4/subprocess.py", line 1457, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'cd /home/mailer-domains/lecomm.com'

>>> subprocess.call(['cd /home/ex-mailer-domains/'+domain, '&&', 'rndc', 'loadkeys', domain])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/subprocess.py", line 537, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/usr/local/lib/python3.4/subprocess.py", line 859, in __init__
    restore_signals, start_new_session)
  File "/usr/local/lib/python3.4/subprocess.py", line 1457, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'cd /home/mailer-domains/lecomm.com'

>>> subprocess.call(['cd', '/home/mailer-domains/'+domain, '&&', 'rndc', 'loadkeys', domain])
cd: too many arguments
2

>>> subprocess.Popen(['cd', '/home/mailer-domains/'+domain, '&&', 'rndc', 'loadkeys', domain])
<subprocess.Popen object at 0x805aa5860>
cd: too many arguments

>>> subprocess.call(['cd', '/home/mailer-domains/'+domain] '&&' ['rndc', 'loadkeys', domain])
  File "<stdin>", line 1
    subprocess.call(['cd', '/home/mailer-domains/'+domain] '&&' ['rndc', 'loadkeys', domain])
                                                                 ^
SyntaxError: invalid syntax

>>> subprocess.call(['cd', '/home/mailer-domains/'+domain], '&&' ['rndc', 'loadkeys', domain])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

>>> subprocess.call(['cd', '/home/mailer-domains/'+domain], ['rndc', 'loadkeys', domain])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/subprocess.py", line 537, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/usr/local/lib/python3.4/subprocess.py", line 767, in __init__
    raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer

>>> subprocess.call(['cd', '/home/mailer-domains/'+domain] ['rndc', 'loadkeys', domain])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple

>>> subprocess.call(['cd', '/home/mailer-domains/'+domain] +['rndc', 'loadkeys', domain])
cd: too many arguments
2

>>> ps = subprocess.Popen((['cd', '/home/mailer-domains/'+domain]), stdout = subprocess.PIPE)
>>> output = subprocess.check_output((['rndc', 'loadkeys', domain]), stdin=ps.stdout)
rndc: 'loadkeys' failed: not found
no matching zone 'lecomm.com' in any view
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/subprocess.py", line 620, in check_output
    raise CalledProcessError(retcode, process.args, output=output)
subprocess.CalledProcessError: Command '['rndc', 'loadkeys', 'lecomm.com']' returned non-zero exit status 1

>>> output = subprocess.check_output((['rndc', 'loadkeys', domain]), stdin=ps.stdout, stdout=PIPE)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'PIPE' is not defined

How do I properly send 2 piped commands via Python3 subprocess?
Comment: What are you trying to achieve by piping the output of `cd` (which is normally empty) into the `rndc` process? Do you really just want to run `rndc` in the new directory?
Comment: @TomDalton  I am assuming the loadkey switch looks in the current directory.  I saw some odd behavior that indicated this. I have numerous zone directories each with their own keys.
Comment: though, I am pondering to myself, that sounds silly.
Answer: The answer can be found in the subprocess documentation.
The functions from the subprocess module normally do not call a shell to interpret the commands, but rather invoke them directly with the given arguments! This behaviour can be overidden by using the argument shell=True (example from the Python documentation):
output = check_output("dmesg | grep hda", shell=True)

However, this is not advisable if the command and arguments are not fix but depends on user input. Then, the correct way to do this is to use two Popen calls and construct the pipeline by hand (code example again from the Python documentation):
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

Comment: @PadraicCunningham Agreed in this case. However, someone searching for the title of this question will almost certainly be interested in this answer.
Comment: There is no need for a pipe at all. the cwd can be passed to subprocess
Comment: @PadraicCunningham: 1001... :D
Comment: There are 1000 dupes of how to pipe, this is not the approach to take for the OP, piping when you can pass the directory makes no sense
Comment: Well it sure helped me out! Thanks @Sebastian Riese
Answer: You don't need pipes at all, just pass the cwd to to subprocess:
subprocess.call(['rndc', 'loadkeys', domain],cwd='/home/mailer-domains/'+domain)

If you did wanted to  change directory for more than just the subprocess, you should use os.chdir.


How to connect a guitar mono TS output to smartphone TRSS input without an interface?

Question: Is it possible to connect a guitar directly to a smartphone, without any interface in between?
A guitar output is an unbalance mono TS, and a smartphone input is a balance TRSS.
I already have a TRSS to TRS adapter. With it, I can successfully connect TRS microphones to my smartphone.
But when I connect my guitar directly to that TRS input adapter, I cannot get any sound recorded. Tried different guitars, and also tried all cables on different setups. So I could verify all my cables work in general.
What am I missing to let the audio signal pass through from a mono guitar output into a TRS input?
Answer: It's not possible, you need some kind of signal amplifier between the guitar and the phone.
The guitar has huge internal impedance, so the input impedance must be around a megaohm to sound right. The headset jack has impedance of few hundred ohms, so it would need much more current than the guitar pickup can provide. Or less technically, the signal from the guitar is too weak for the phone without amplification.
Comment: FTR, many amp- or pedal inputs only have an impedance around or below 200 kΩ. True is: even this already colours the sound, while still being much more than a phone's. You don't _need_ 1 MΩ, but it will give the clearest possible sound, and you certainly don't want much less than 100 kΩ.
Comment: That's by the way why some people like to but a buffer before effect pedals.


If two sets are countable and infinite show the Cartesian product is countable.

Question: If I have two sets say A and B which are countable and infinite then how would I show that the Cartesian product is countable.
Comment: Do you have any thoughts?
Comment: Have you seen proof that $\mathbb N\times\mathbb N$ is countable?
Comment: The easiest way to show something is countable is to create a bijection between the two sets.
Comment: How would I create this bijection. Would I need to show its both surjective and injective.
Comment: You could have a look at the related questions on the right. Like this one: http://math.stackexchange.com/questions/71850/cartesian-product-of-two-countable-sets-is-countable.
Comment: This is an extremely famous problem and given that you have not explained anything about how you have worked on it, we can't do anything that a Google search can't.
Answer: The set  of natural numbers is the prototype for countable sets; anything in bijective correspondence with this set, by definition, is a countable set.
Let us see the natural numbers in their physical/visual form. We write them out in base 10. Then we get all possible finite sequences formed by the symbols $0,1,2,\ldots,9$ (avoiding 0 at the starting position).
As numbers can be written uniquely in any basis (binary system, decimal system) it follows that given a finite set of symbols, the collection of strings of all possible finite length composed of these symbols is a countable set.
Now let us take a visual description of the cartesian product: a typical element looks like $(13374,26905)$. We can see that physically these are subset of all possible strings of finite length composed of the thirteen symbols: the decimal digits, opening and closing parentheses, the comma.
So this is a subset of the  countable set of all strings of finite length formed with 13 symbols, hence countable.
Note that this actually  proves  that product of three (or any finite number of) countable sets is  also countable.
BONUS: To prove countability of rationals look at their physical forms, other than the minus sign, the slash sign for division should be enlisted, and same argument will work.


How to use polymer-redux with polymer-build?

Question: I've currently started a new project based on Polymer Custom Build. I've modified the project in order to add usage of polymer-redux. Since then, when trying to build a bundled project using the command gulp build, I have the following problem

[unknown-polymer-behavior] - Unable to resolve behavior ReduxBehavior. Did you import it? Is it annotated with @polymerBehavior?

Declaring the ReduxBehavior is done using ReduxBehavior = PolymerRedux(store); which is not very usual.
Anybody succeeded to make both of polymer-build and polymer-redux work together ?
Comment: Have you resolved this issue yet?
Answer: You can check the sample repo for Polymer 2 with Redux Application.
https://github.com/kumarargutech/polymer-redux
I hope it's helpful to you!
Answer: You can check out this Polycast edition.
Here is the code
You can also check the Simpla repo
Basically you create a polymer-redux-store-html:

        <link rel="import" href="../bower_components/polymer-redux/polymer-redux.html">

and include it in any element where you need the ReduxBehavior
Comment: Thanks Umit. This is precisely what I did. The website works well if I don't try to create a bundled version using `gulp build`. My question is about the creation of the bundled version, which doesn't seem to support the usage of redux.
Comment: that's weird, maybe there is an issue with ordering of the bundled imports. Can you check in the bundled output if the `polymer-redux-store` is included ?


How can I set an alias in the .bashrc of my Docker image

Question: For example:
'alias python=/home/user/python3.6'
Is something I might want to put into my bashrc
How do I set this in a Dockerfile
I know of the ENV command which sets path variable, is it possible to do similar for setting an alias?
Comment: just put that line into your .bashrc file and ADD it to your Dockerfile
Answer: simply use RUN to add an alias to bash_profile.
FROM ubuntu
MAINTAINER Mojtaba Yeganeh

RUN echo "alias python=/home/user/python3.6" >> ~/.bash_profile

Comment: shouldn't this be simply `RUN echo "alias python=..." >> ~/.bash_profile`? https://stackoverflow.com/a/36388856/5339857
Comment: i meant you have double `alias alias` there
Answer: For me it worked in .bashrc file.
I've put this in Dockerfile:
RUN echo "alias ll='ls -alF'" >> ~/.bashrc


Submit button doenst work with script asp.net mvc5

Question: I have a maybe simple problem but I don`t have that much experience with scripts:
I have this Skript in my _Layout.cshtml:

and one of my views:
@using (Html.BeginForm("Create", "Home", FormMethod.Post, null))
{
    @Html.AntiForgeryToken()

        <textarea class="form-control" name="TextArea"></textarea>

        <button class="btn btn-secondary btn-block mt-2 post-btn" type="submit" id="PostButton">Post</button>

}

This form works great without the script, but for any reason with the script it doesn`t work.
I placed the script in the _layout.cshtml because I want to have it for all buttons in my asp.net page.
After click on the button the button is disabled - as I wish - but the action result "Create" in the HomeController will not called.
I think I need to extend the script but can someone help me how to do it?
Thanks all
Answer: If I'm getting your question correctly, you are messing up with the submit form and making the button disable. Without the script, the form works correctly as the button is submitted type and not disabled. But with the script, as soon as you click the button it becomes disabled, and the form can't be posted. So use this script instead of yours;
    $('#mainForm').submit(function (e) {
        $('#PostButton').prop('disabled', true);
    });

And also make a little bit of change in your form declaration;
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { @id = "mainForm"}))
{
@Html.AntiForgeryToken()

    <textarea class="form-control" name="TextArea"></textarea>
    <button class="btn btn-secondary btn-block mt-2 post-btn" type="submit" id="PostButton">Post</button>

}


Fill an array with fread()

Question: I've just started programming in C.
I'm trying to write a code able to analyse the values from a wav audio file and write them into the array buf[num_samples]; num_samples is defined by reading the info contained in the header of the audio file (it is defined as a uint32_t variable because the audio file can consist of a huge amount of samples). I found this piece of code:
uint16_t buf[num_samples];

// Open WAV file with FFmpeg and read raw samples via the pipe.
FILE *pipe = popen("ffmpeg -i 45s.wav -f s16le -ac 1 -", "r");

// check on the pipe work
if ((pipe = popen("ffmpeg -i 45s.wav -f s16le -ac 1 -", "r"))==NULL) {
    perror("ERROR\n");
}

fread(buf, 2, num_samples, pipe);
pclose(pipe);

Where the second argument of fread() is 2 (referring to bytes) because I'm using a recorder which works with the parameter Bit_per_sample = 16.
However there are problems, in fact the array is filled with "illogical values": I expect values representing a waveform (more or less they should belong to the interval [-20,000; 32,767]).
In order to verify the correct filling of the array I have added a printf with %d of buf[i] in a cicle from i=0 to i=num_samples-1. Below some of the values I got from the output:

64947    65002    65046    65080    65110    65150    65188    65236
65264    65306    65338    65378    65434    65472    65517    8
81       128      168      206      241      268      306      322
424      458      497      520      543      566      586      622
676      699      728      745      765      796      825      840
917      950      970      996      1018     1040     1064     1072
1106     1128

Can anybody help me or give me some useful advises?
Thank you in advance, hoping I didn't waste your time.
Comment: Furthermore, despite us helping you ages ago, you seem to be not reading *any* comments left to your questions, including the ones asking why the `popen` is being called twice in a question [that has now been deleted](https://stackoverflow.com/questions/45775690/segmentation-fault-caused-by-popen), so you indeed **are** wasting our time.
Comment: **You're reading signed 2's complement numbers as unsigned numbers. The waveform is there, you're just not seeing it, because the signed to unsigned conversion.**, thus -1 becomes 65535, -10 => 65525.Change the type to **`int16_t`** as suggested by Paul originally! Notice the lack of `u` in there. It is `int16_t`.
Comment: Do you understand what `u` in `uint16_t` means? It means unsigned. It means that you will not ever see a negative value in such a variable!
Comment: Could be a byte order issue. Btw you are calling `popen()` twice. Also a 16bit signed integer cannot reach 35,000...
Comment: Could also be a wrong format specifier problem. What is the exact array declaration and how do you print?
Comment: You can find the exact array declaration in the question, it is an int array, containing num_samples positions. I print it with the following code: uint32_t i;

           for (i=0; i<numcampioni; i++) {
            printf("%d    ", buf[i]);
           }
Comment: Try declaring the `buf` array to be `int16_t`.
Comment: Why you are using `popen()` 2 times? Also you have to read starting at the right position.
Comment: Did you read the specs? http://soundfile.sapp.org/doc/WaveFormat/
Comment: Very sorry, I made a mistake when I wrote the code in the question: the array buf[num_samples] is already declared as a uint16_t, but the problem, stays. Now I'm going to correct the question. Anyway could you explain me why I'm using popen() twice? Do you mean in the check I wrote in the 'if'?
Comment: @NiccolòCirone: Yes you use it before the check and in the check. Because you are doing it before the if statement you just need `if (pipe == NULL)` or doing the assignment inside of the if and not before. Further to print your values the right way cast them in your printf:  `printf("%d ", (int)buf[i]);`
Comment: @AnttiHaapala thank you a lot for your answer, it was not clear to me. Anyway can you explain me the reason why these values have totally no relation with a waveform? Even without a sign I expect to see a local wave behaviour of data, isn't it?
Comment: Also reading this: [Signed to unsigned conversion in C](https://stackoverflow.com/a/50632/8051589) would help because that's what happens! Don't ignore what was said here. The answer is already here, read carefully.
Comment: Finally of the various answers to the question that I linked, please read [this one especially carefully](https://stackoverflow.com/a/5789914/918959)
Comment: NiccolòCirone, "more or less they should belong to the interval [-20000; 35000]" is a problem for 2-byte values,  how about a more limited range, only up to 32,767?
Comment: @chux Yes, of course the maximum value is 32767, I've been inaccurate! Thank you for the correction
Comment: You can use sizeof() function to compute the amount of bytes that the function fread will read.
Answer: Your type is wrong, You're using uint16_t as unsigned type and expect signed values between [-20,000; 32,767].
Declare buf as int16_t buf[num_samples]; so the buffer is declared as elements of 2 (signed) bytes.
Also, to open and check the pipe use
FILE *pipe;
if ((pipe = popen("ffmpeg -i 45s.wav -f s16le -ac 1 -", "r"))==NULL) {
    perror("ERROR\n");
    exit(1);
}

Comment: `perror` doesn't exit, so one needs to add exit too :)

Fill an array with fread()


AWS-CLI - Can't find my config even through it exists

Question: I installed Amazon Command Line Tools (AWS-CLI) using:
pip install awscli

It installed successfully. I then created a file in this location: /opt/aws/aws_cred.txt
[default]
aws_access_key_id = XYZ
aws_secret_access_key = XYZ
region = XYZ

Then I ran this command:
export AWS_CONFIG_FILE="/opt/aws/aws_cred.txt"

Then I get this when I try to run this command: aws ec2 describe-regions

botocore.exceptions.ConfigNotFound:
  The specified config file ("/opt/aws/aws_cred.txt")
  could not be found.

What else could I do? Does it need to be executable, owned by a certain user, what? The file is definitely there but it can't find it.
Comment: See also: http://stackoverflow.com/questions/34134879/aws-the-config-profile-myname-could-not-be-found
Comment: You don't need quotes at all actually
Answer: Compare
export AWS_CONFIG_FILE="/opt/aws/aws_cred.txt"

and
export AWS_CONFIG_FILE="/opt/aws/aws_cred.txt"

(Hint: one uses "smart" quotes.)
Edit: to be less oblique, your use of smart quotes is causing the problem.
Answer: Have you tried searching for it?
find / -name aws_cred