&& operator behaves like || operator

Question: I am a beginner and I've been trying to run a program that prints all the numbers from 1 to N (user input) except for those that are divisible by 3 and 7 at the same time. What my code does instead, however, is that it prints the numbers from 1 to N except for those that are divisible by 3 or 7. I examined it for a while and I have no idea why it does that. Please explain to me where I'm going wrong.
static void Main(string[] args)
{
    int n = 0;
    int a = 0;
    n = Convert.ToInt32(Console.ReadLine());
    while (a <= n)
    {
        a++;
        if (a % 3 != 0 && a % 7 != 0)
        {
            Console.WriteLine(a);
        }
    }
    Console.ReadKey();
}

When I reverse the signs of the if statement to == the && operator works properly, but if the sign is != it simply acts like an || operator, so that confuses me even more. The issue is most likely in the condition, but I can't see what is wrong with it.
Comment: As a side note, a number is divisible by both 3 and 7 if, and only if, it is divisible by 21.
Comment: `!(a%3==0 && a%7==0)`
Comment: @AndreyChernyakhovskiy: Better generalization is - a number is divisible by both *a* and *b*, if it is divisible by *LCM of a and b*.
Comment: @displayName: http://meta.stackexchange.com/a/19479/135695  Also, freehand drawn Venn diagrams are preferred: http://meta.stackexchange.com/a/19775/135695
Comment: `x` = `a%3 == 0` (divisible by three), `y` = `a%7 == 0` (divisible by 7). You want `!(x&&y)` = `!x || !y`, instead of `!x && !y` which you have in code. You just need to study some mathematical logic.
Answer: "Except numbers that are divisible by 3 and 7 at the same time" can be broken down as follows:
"divisible by 3 and 7 at the same time" can be expressed as:
"(divisible by 3 and divisible by 7)"
"Except" can be expressed as "Not".
So you get:
Not (divisible by 3 and divisible by 7)
"divisible by 3" is (a % 3) == 0
"divisible by 7" is (a % 7) == 0
Giving:
Not ( (a % 3) == 0 and (a % 7) == 0)
In C# Not becomes ! and and becomes &&, so you can write the whole thing in C# as:
if (!((a % 3) == 0 && (a % 7) == 0))

Compare with your incorrect:
if (a % 3 != 0 && a % 7 != 0)
This latter is incorrect because it means:
if (the number is not divisible by 3) and (the number is not divisible by 7).
i.e. it means "Print the number if it is neither divisible by 3 nor divisible by 7", which means "don't print the number if it's divisible by 3 or 7".
To see why, first consider the number 6:
6 is not divisible by 3? = false (because 6 *is* divisible by 3)
6 is not divisible by 7? = true (because 6 is *not* divisible by 7)

So this resolves to if false and true which is, of course, false.
This result also applies to any other number divisible by 3, so no numbers divisible by 3 will be printed.
Now consider the number 14:
14 is not divisible by 3? = true (because 14 is *not* divisible by 3)
14 is not divisible by 7? = false (because 14 *is* divisible by 7)

So this resolves to if true and false which is, of course, false.
This result also applies to any other number divisible by 7, so no numbers divisible by 7 will be printed.
Hopefully you can see why it's wrong now. If not, consider this equivalent example:

Suppose we have four people, Tom the Carpenter, Dick the Carpenter, Harry the Butcher and Tom the Butcher.
This question is equivalent to the one you're asking:
 Name every person who is (not called Tom and is not a Butcher)

And you should be able to see that this the same as asking:
Name every person except (anyone called Tom or anyone who is a Butcher)

In both cases, the answer is Dick the Carpenter.
The question you should have asked is:
Name every person except (anyone called Tom who is also a butcher)

To which the answer is Tom the Carpenter, Dick the Carpenter and Harry the Butcher.

Footnote: De Morgan's laws
The second law states that:
"not (A or B)" is the same as "(not A) and (not B)"

This is the equivalent of my example above where:
Name every person except (anyone called Tom or anyone who is a Butcher)

is the equivalent to:
Name every person who is (not called Tom and is not a Butcher)

where A is anyone called Tom and B is anyone who is a butcher and not is written as except.
Comment: Though the thorough explanation is appreciated, I believe the answer would benefit from explaining the theory that's going on under the hood with the logical statements i.e. De Morgan's Law.
Comment: @Leon7C I think such an explanation  would be beyond the scope of an answer here. Someone already linked the Wiki article on De Morgan's laws (although I fear it would possibly be too complicated for the OP, at least at this stage). My example with Tom, Dick and Harry was intended to provide a basic introduction to the logic for the OP's specific issue. However, I will add a footnote.
Comment: Almost thought you wouldn't mention De Morgan in this long answer at all. :)
Comment: An excellent response. However, in theory, shouldn't " if (a % 3 != 0 && a % 7 != 0) " also be correct? My logical not is just 2 "!=" signs instead of a single "!" sign so I find this to be pretty confusing.
Comment: @Ornstein I have added more information to explain why that's wrong.
Comment: Thank you very much, I think that I pretty much understand it know. Thank you for the time you spent helping me!
Comment: Holy cow, what an answer. Posts like these need like a +100 button.
Comment: You're missing a closing parenthesis in `if (!((a % 3) == 0 && (a % 7) == 0)`
Comment: @Leon7C I am aware of De Morgan's laws, I knew them for a while now, although I am not sure I fully understood them until I read 2-3 of the answers here.
Answer: You should read De Morgan's laws

"not (A and B)" is the same as "(not A) or (not B)"
also,
"not (A or B)" is the same as "(not A) and (not B)".

a % 3 != 0 && a % 7 != 0 is true when a is not divisible by 3 (a % 3 != 0) and not divisible by 7 (a % 7 != 0). So all as which are divisible by 3 or 7 (3,6,7,9,12,14,...) makes the whole expression false. You can rephrase it like !(a % 3 == 0 || a % 7 == 0)
Comment: this should be the accepted answer - it's really not about the operator, it's the concept of boolean logic in general that OP wasn't getting.
Comment: There is a simple fix to avoid such awkward situations, use more parenthesis than strictly necessary.
Comment: What I want is for the condition to be true when a is not divisible by 3 and 7, but it still behaves as if it's either 3 or 7. I replaced the condition with "if (!(a % 3 == 0 && a % 7 == 0))" and it worked, but I am still not quite sure why my initial condition didn't do the same.
Comment: @Ornstein Try reading your initial condition out loud; you should end up with something like : Print a as long as a does not divide 3 and also a does not divides 7.  For a to be printed both parts of the conjunction has to be true, so the cases where a is not printed are the cases where at least one of the parts are false.  That is a divides 3 or a divides 7.  This is what De Morgan's laws tells you.
Comment: @Dukeling `( (a % 3 != 0) && (a % 7 != 0) )`
Comment: @Caridorc OP only has a problem with the logic of how `&&` works - no amount of brackets will change that.
Comment: @Taemyr Yeah but technically, since the condition is supposed to execute when a is not divisible by 3 and is not divisible by 7, if a is not divisible by 7 but divides by three it should still get printed, shouldn't it? It seems so weird to me.
Comment: @Caridorc I'll try doing that in the future to see if it helps, although I have no clue why exactly it would help since I think the condition should be pretty clear as is. Obviously, as I said I am a beginner, so I could be wrong.
Comment: @Ornstein For A and B to be true neither A nor B can be false.  So let's say that A is Not P, and B is Not Q.  Then A and B is the same as Not P and Not Q, if P is false and Q is true then A is true, but since Q is true then B is false.  Hence A and B would be false.  Now let Q be "divides 7" and P be "divides 3".
Comment: thanks for the answer - if only for the reference of naming `De Morgan's laws`. sometimes it is nice to know the official classification and history of something you are using everyday ...
Comment: @wrschneider I know what De Morgan's laws consist in, I just think I didn't comprehend them before reading several of the answers here which together contributed to me figuring out how things work. This answer was mostly a link to Wikipedia, which is appreciated, but I've already read the article a while ago. I just thought that multiple other answers contributed much more to me grasping the concept.
Answer: Should be:
if ( !(a % 3 == 0 && a % 7 == 0) )
{
    Console.WriteLine(a);
}

It means exactly: all the numbers except for those that are divisible by 3 and 7 at the same time.
You could also rephrase it as:
if ( a % 3 != 0 || a % 7 != 0 )
{
    Console.WriteLine(a);
}

Comment: Thank you, your solution worked. The second piece of code seems a bit weird to me but it makes sense. Can you explain to me in a little more detail why your first statement works but mine doesn't, if possible?
Comment: @Ornstein Using words as @MatthewWatson did, your statement said `if a is not divisible by 3 AND a is not divisible by 7`, but @user2622016's answer says `if it's not true that a is divisible by BOTH 3 and 7`. A number like **6** would not pass your check, but it would pass @user2622016's check.

If you distribute the `not` at the beginning of the @user2622016's code, you get the second piece of code. It's almost identical to the code that you originally posted, but, when distributing `not`s, we need to change `&&` to `||` and change `||` to `&&`.
Answer: All you really need is:
if ((a%21) != 0) Console.WriteLine(a);

Explanation: The numbers that are divisible by both a and b are essentially the numbers divisible by the LCM of a and b. Since, 3 and 7 are prime number, you are basically looking for numbers that are not divisible by 3*7.
Comment: It took a second to realize that you had a point that no one else had made.
Comment: @kleineg it was made in a comment.  But yes, this is by far the best way to solve this problem.  All those posts that clearly and extensively explain how to make the badly designed program work... sad.
Comment: @Yakk I agree. It does makes sense that people answered the question at face value (although a lot of the answers are redundant) because it promotes an understanding of De Morgan's laws, which would be helpful when negating a conditional statement. But it is also true that in this case there does exist a... more elegant solution. Thumbs and votes up for that.
Comment: @Yakk: I posted the answer before reading the comment, then I read the comment and then posted my comment there too. The highest upvoted comment on the question is actually misleading. It's working because 3 and 7 are prime. Won't work for, let's say 4 and 6. For non coprime numbers, it's not the multiplication but, as I said, the LCM that is to be used.
Comment: 4 * 6 is 24. But the first number filtered by 24 would be 24 itself while 12 is a multiple of both 4 and 6 and should be filtered as well. And that's because 4 and 6 aren't coprimes.
Comment: @displayName Yes, but the upvoted comment doesn't talk about 4 and 6, and the question isn't about 4 and 6.  ;)
Comment: @Yakk: That's why I said it is *misleading* and not incorrect. :)
Answer: What you said:
   if not (divisible by 3 and divisible by 7) then print

What you wrote:
   if not divisible by 3 and not divisible by 7 then print

Not the same thing.  Aristotle thought of it first, Augustus De Morgan wrote the laws 158 years ago, apply the not operator to the operands and invert the logical operation:
   if not divisible by 3 or not divisible by 7 then print

Which produces:
   if (a % 3 != 0 || a % 7 != 0)

Or just write it the way you said it:
   if (!(a % 3 == 0 && a % 7 == 0))

Comment: The first part makes a lot of sense. After you mention the logical OR operator I just get lost. How could an OR operator possibly encompass a situation where two values need to answer a condition in the same time? I understand that what you're saying is correct, but I don't see why. I know that De Morgan's laws state lots about inverting operators, but an OR operator satisfying a simultaneous condition sounds absolutely confusing and impossible to me. Could you give me a simple explanation on that if you wouldn't mind?
Comment: Not sure I can understand your hangup, I've been doing this for too long.  I'm guessing you got confused by the replacement of == by !=.  Maybe it is easier to get when you work this out with variables of type *bool* instead.  Like bool divisiblyBy3 = a % 3 == 0;  same for divisiblyBy7 and then write the if() statement.  Other than that, Mister DeMorgan is your friend, always keep him handy.
Comment: Some other answers managed to fill in the gaps and I understand it now. It's just that using the OR operator makes the way of deciding whether a is divisible by 3 and 7 radically different than when using the AND operator. Also, perhaps I should've re-read the task itself a couple more times because now that I did it I managed to grasp the concept more easily. Either way, your answer in combination with 2 others managed to help me understand the issue. Thank you very much for your help and your time!
Answer: Looking at your conditional statement's Truth Table you can see that if
 X(NOT multiple of 3) Y(NOT multiple of 7)   X && Y
      true                   true            'a' printed as it is not a multiple of either
      true                   false           'a' not printed, it is multiple of 7
      false                  true            'a' not printed, it is multiple of 3
      false                  false           'a' not printed, it is multiple of both

That is why all the multiples of 3 or 7 or 21 are not printed.

What you want: Numbers, that are

not a (multiple of 3 AND 7). And that is
!(a%3==0 && a%7==0) or even further simplified to
!(a%21 == 0) or even
(a%21 != 0)
Comment: I think **this** is really the primary answer to the question. The `&&` operator is doing _exactly_ what it says it will do; just follow the evaluation of the expression step by step.
Answer: a % b != 0 means "a is not divisible by b".
If something is not divisible by 3 and not divisible by 7, it's divisible by neither. Thus if it's a multiple of 3 or a multiple of 7, your statement will be false.
It often helps to think of logic in terms of real-world things:
(keep in mind that true and false == false and true or false == true)

The ocean is blue (a is divisible by 3).
  The ocean is not yellow (a is not divisible by 7).
What you have:
  The ocean is not blue and the ocean is not yellow - this is false (you want this to be true).
What you want:
  The ocean is not (blue and yellow) - this is true (the ocean is only blue, not both blue and yellow).
  The ocean is not blue or the ocean is not yellow - this is true (the ocean is not yellow).

The equivalent of the last 2 statements would be:
!(a % 3 == 0 && a % 7 == 0)
(a % 3 != 0 || a % 7 != 0)

And you can convert one to the other using De Morgan's laws.
Answer: If you don't know how to implement an algorithm, try breaking it down into obviously correct functions that each implement part of the algorithm.
You want to "print all the numbers from 1 to N (user input) except for those that are divisible by 3 and 7 at the same time."  Old timers can quickly spit out a correct and efficient implementation using logical operators.  As a beginner, you may find it helps to break it down into pieces.
// write out the highest level problem to solve, using functions as
// placeholders for part of the algorithm you don't immediately know
// how to solve
for ($x = 1; $x <= $N; $x++) {
    if (is_not_divisible_by_3_and_7($x)) {
        print "$x\n";
    }
}

// then think about the function placeholders, writing them out using
// (again) function placeholders for things you don't immediately know
// how to do
function is_not_divisible_by_3_and_7($number) {
    if (is_divisible_by_3_and_7($number)) {
        return false;
    } else {
        return true;
    }
}

// keep repeating this...
function is_divisible_by_3_and_7($number) {
    if (is_divisible_by_3($number) && is_divisible_by_7($number)) {
        return true;
    } else {
        return false;
    }
}

// until you have the simplest possible functions
function is_divisible_by_3($number) {
    if ($number % 3 === 0) {
        return true;
    } else {
        return false;
    }
}

function is_divisible_by_7($number) {
    if ($number % 7 === 0) {
        return true;
    } else {
        return false;
    }
}

This is easier to follow, because each function does one thing and the function name describes exactly that one thing.  This also satisfies the first rule of programming: correct code comes first.
You can then start to think of making the code better, where better can mean:

fewer lines of code
less calculations
more comments

Taking this approach with the code above, an obvious improvement is to replace is_divisible_by_3 and is_divisible_by_7 with a generic function:
function is_divisible_by_n($number, $divisor) {
    if ($number % $divisor === 0) {
        return true;
    } else {
        return false;
    }
}

You can then replace all the big, bulky if x return true else return false with the ternary operator, which gets you to:
function is_divisible_by_n($number, $divisor) {
    return ($number % $divisor === 0) ? true : false;
}

function is_divisible_by_3_and_7($number) {
    return (is_divisible_by_n($number, 3) && is_divisible_by_n($number, 7)) ? true : false;
}

function is_not_divisible_by_3_and_7($number) {
    return (is_divisible_by_3_and_7($number)) ? false : true;
}

Now, notice that is_not_divisible_by_3_and_7 looks exactly like is_divisible_by_3_and_7, except the returns are switched, so you can collapse those into one method:
function is_not_divisible_by_3_and_7($number) {
    // look how it changed here ----------------------------------------------VVVVV - VVVV
    return (is_divisible_by_n($number, 3) && is_divisible_by_n($number, 7)) ? false : true;
}

Now, rather than using ternary operators you can leverage the fact that comparisons themselves return a value:
function is_divisible_by_n($number, $divisor) {
    // this expression returns a "truthy" value: true or false
    //     vvvvvvvvvvvvvvvvvvvvvvvvvv
    return ($number % $divisor === 0);
}

function is_not_divisible_by_3_and_7($number) {
    // also returns a truthy value, but inverted because of the !
    //    vvv
    return ! (is_divisible_by_n($number, 3) && is_divisible_by_n($number, 7));
}

Finally, you can just mechanically replace the function calls with their equivalent logical operations:
for ($x = 1; $x <= $N; $x++) {
    // all I did below was copy from the function, replace variable names
    //  v  vvvvvvvvvvvvvv    vvvvvvvvvvvvvv
    if (! (($x % 3 === 0) && ($x % 7 === 0))) {
        print "$x\n";
    }
}

As bonus points, you can then apply DeMorgan's rule, to distribute the not through the expression:
for ($x = 1; $x <= $N; $x++) {
    if ($x % 3 !== 0 || $x % 7 !== 0) {
        print "$x\n";
    }
}

Additionally, you might observe that two co-prime numbers have common factors  if and only if they have common factor N times M, so:
for ($x = 1; $x <= $N; $x++) {
    if ($x % (3*7) !== 0) {
        print "$x\n";
    }
}

You can take this further by using your language's features to compact the expression more:
array_walk(
    range(1, $N),
    function ($x) {
        if ($x % 21 !== 0) print "$x\n";
    }
);

And so on.  The point is that you start by making your code correct, then you make it better.  Sometimes making code correct means thinking long and hard.  Sometimes it just means writing it out in very small, very explicit steps.
Answer: && behaves differently to ||
To understand the difference, it may help to do some tests with simpler expressions:
if (true && false)
if (true || false)

So, your problem is with understanding the other operators in your code (!= and %).
It often helps to split conditions into smaller expressions, with explanations:
bool divisbleBy3 = (a % 3 == 0);
bool divisbleBy7 = (a % 7 == 0);

if (divisbleBy3 && divisibleBy7)
{
    // do not print
}
else
{
    // print
}

Comment: Yes, the result is different. That's the whole point of having two different operators, if the result was the same one of the operators would be redundant. What is your point?
Comment: Well, the point is to answer the question. Look at the title... :-)
Comment: You've answered the title then, but not the question
Comment: Actually this doesn't even answer the title?!
Comment: @buffjape I know the difference between logical AND and logical OR. The issue is that in my program, the logical AND behaves like a logical OR, at least as far as my understanding goes.
Answer: Obviously && and || are different.
It states:
if (true && false) = false
if (true || false) = true

&& operator behaves like || operator


Setting boundaries for gesture-detector drag

Question: I want to make drag only in the image so there are boundaries on each side of the widget, so the user may not drag out-of-bounds.
here is the stack and the image below , i want the gesture detectors dosen't surpass the image
please can anyone help me achieve this !
Here's the code:
Column Team1() {
   return Column(
     children:[ **\[**][1]
       Stack(
         children: [
           Image.asset(
             "assets/field.jpg",
             height: 500,
             fit: BoxFit.cover,
           ),
           for (var i in LineupList)
             Positioned(
               left: i["offset"].dx,
               top: i["offset"].dy,
               child: Padding(
                 padding: EdgeInsets.only(left: i["left"], top: i["top"]),
                 child: GestureDetector(
                     onTap: () {
                       ShowPlayer();
                     },
                     onPanUpdate: (details) {
                       setState(() {
                         i["offset"] = Offset(
                             i["offset"].dx + details.delta.dx,
                             i["offset"].dy + details.delta.dy);
                       });
                     },
                     child: new Container(
                       width: 50.0,
                       decoration: DottedDecoration(
                           shape: Shape.box,
                           color: Colors.white,
                           strokeWidth: 3),
                       child: new Column(children: [
                         SizedBox(
                           height: 50,
                         ),
                       ]),
                     )),
               ),
             ),
         ],
       ),
       Padding(
         padding: const EdgeInsets.all(8.0),
         child: Column(
           children: [
             Text(
               "REMPLAÇANTS",
               style: TextStyle(color: Color.fromARGB(255, 112, 112, 112)),
             ),
             Row(
               children: [
                 new Container(
                   width: 50.0,
                   decoration: DottedDecoration(
                       shape: Shape.box,
                       color: Color.fromARGB(255, 152, 152, 152),
                       strokeWidth: 3),
                   child: RawMaterialButton(
                       constraints: BoxConstraints.tight(Size(26, 26)),
                       onPressed: () {},
                       child: IconTheme(
                         data: IconThemeData(
                             color: Color.fromARGB(255, 152, 152, 152),
                             size: 16),
                         child: Icon(Icons.add),
                       )),
                 )
               ],
             )
           ],
         ),
       )
     ],
   );
 }

Answer: There are few key factors to control the object in two dimension.

every object on On UI must be 2D and calculate accordingly.

Tap event will get on single point, to place object center you need to minimize the of object half size. same goes for boundary.

if you like to have free axis movement   place logic separately, don't combine x and y-axis logic with and operator.

There are many more, you can check this as an example
class BoundaryTest extends StatefulWidget {
  BoundaryTest({Key? key}) : super(key: key);

  @override
  State<BoundaryTest> createState() => _BoundaryTestState();
}

class _BoundaryTestState extends State<BoundaryTest> {
  double dx = 100, dy = 100;

  Size containerSize = const Size(100, 100);
  Size? screen;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(
        builder: (context, constraints) {
          // box allowed 90% of body from center
          final boxSize =
              Size(constraints.maxWidth * .9, constraints.maxHeight * .9);

          screen ??= Size(constraints.maxWidth, constraints.maxHeight);
          return Stack(
            alignment: Alignment.center,
            children: [
              Align(
                child: Container(
                  width: boxSize.width,
                  height: boxSize.height,
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.red, width: 4)),
                ),
              ),
              Positioned(
                top: dy,
                left: dx,
                child: Container(
                  width: containerSize.width,
                  height: containerSize.height,
                  color: Colors.deepPurple,
                ),
              ),
              GestureDetector(
                onTap: () {},
                onPanUpdate: (details) {
                  final tapPos = details.globalPosition;

                  if (tapPos.dx <
                          screen!.width * .95 - (containerSize.width / 2) &&
                      tapPos.dx - (containerSize.width / 2) >
                          screen!.width * .05) {
                    //moveable to x
                    dx = tapPos.dx - (containerSize.width / 2);
                    setState(() {});
                  }
                  if (tapPos.dy <
                          screen!.height * .95 - (containerSize.height / 2) &&
                      tapPos.dy >
                          screen!.height * .05 + (containerSize.height / 2)) {
                    //moveable to
                    dy = tapPos.dy - containerSize.height / 2;
                    setState(() {});
                  }

                  debugPrint(tapPos.toString());
                },
              ),
            ],
          );
        },
      ),
    );
  }
}

In this image, the purple box is only allowed to move within the red area. And you can think the different way of decorating your logic
Comment: how to adapt this concept to mine ?
Comment: Did you run this snippet?
Comment: yep it works , but in my case the borders are the image itself.
Comment: yes you can calculate  it by wrapping with sizedBox and providing height 500 and also you need to measure the width of the image
Comment: I did that and it worked , but there is one thing that disturbs . when i click on the container to drag it it goes below automatically , do you have any idea what is wrong ? thank you in advance !
Comment: You can use `onTapDown`


Field extension $L/K$ such that every element has degree $1$ or $2$ over $K$

Question: Let $L$ be a field extension of a field $K$ of characteristic $\neq 2$ such that every element of $L\setminus K$ has degree $2$ over $K$, can we show that $[L:K]=2$ by elementary methods, without using the primitive element theorem ?
If $L$ is a separable extension of $K$, it is easy to prove this by using the primitive element theorem. Let $\alpha, \beta \in L\setminus K$. There exists $\gamma \in L$ such that $K(\gamma) = K(\alpha,\beta)$, therefore $[K(\alpha,\beta):K] = 2= [K(\alpha):K]$ and $K(\alpha,\beta)= K(\alpha)$, and $\beta \in K(\alpha)$. Since this is true for all $\beta \in L\setminus K$, $L=K(\alpha)$.
However, we have a counterexample if the characteristic of $K$ equal to $2$ : if $L= \mathbb F_2(X,Y)$ and $K=\mathbb F_2(X^2,Y^2)$, any element $f\in L$ is a root of $T^2-f^2 \in K[T]$, so has degree $1$ or $2$ over $K$, but $[L:K]= 4$.
Comment: Would the argument in the last paragraph also work for $L = k(x, y)$ and $K = k(x^2, xy, y^2)$ for an arbitrary field $k$?
Answer: Take any $\alpha \in L\backslash K$. If $K[\alpha] \not= L$, pick $\beta \in L\backslash K[\alpha]$ so that $[K[\alpha,\beta]:K]=4$ and has a K-basis $\{1,\alpha, \beta, \alpha\beta\}$. Now show that $[K[\alpha + \beta]:K]=4$ by observing that it contains at least three K-linearly independent vectors $\{1, \alpha + \beta, (\alpha\beta + v) \}$ where $v$ lies in span$_K(\alpha,\beta)$ (here you need the fact that 2 is invertible in $K$). This gives a contradiction.
Comment: Nice! I first thought that you need to pick $\alpha$ and $\beta$ in such a way that their squares are in $K$ (something you can easily arrange because $2$ is invertible). Then I realized that your argument works the same without such extra twiddling.
Comment: Nice argument, thank you.


Is it possible to use WHERE with ANY and ARRAY together?

Question: I have a table called 'reviews' that I want to start the data cleaning process, so I want to find out if there are any records that have any NULL columns (there are 6 columns in the table).
So, instead of using the code below:
SELECT *
FROM reviews
WHERE listing_id IS NULL
    OR id IS NULL
    OR date IS NULL
    OR reviewer_id IS NULL
    OR reviewer_name IS NULL
    OR comments IS NULL

'''

I would like to simplify the code, using something like this:
SELECT *
FROM reviews
WHERE ANY( ARRAY [listing_id, id, date, reviewer_id, reviewer_name, comments]) IS NULL

But It doesn't work.

What's wrong with the second code?
Are there other more efficient ways to check?
Answer: you can use num_nulls()
where num_nulls(listing_id, id, date, reviewer_id, reviewer_name, comments) > 0


True/False exam Question

Question: Given a pair of lines $L_{1}$ and $L_{2}$ in the plane, meeting only at the origin, there is a unique $2×2$ matrix $A$ so that $L_{1}$ is the $(\lambda = 2)$ eigenspace of $A$ while $L_{2}$ is the $(\lambda = 7)$ eigenspace of $A$
The question was in an exam paper I have and there are about 10 T/F question and you don't need to justify your answer he gives +1 for correct or -1 for incorrect.
I said the answer was true because I was guessing but I felt it had something to do with linear transformation of the lines but I didn't know exactly why it was true. Can anyone explain what is being asked?
Comment: EIgenspaces are, by definition, associated with  linear transformations. So no credit for thinking this question had * something to do with linear transformations.*
Answer: You were right. The idea is the following, the two Lines span $\def\R{\mathbf R}\R^2$ and hence vectors from it form a basis of $\R^2$. Say $b_1 \in L_1 - \{0\}$, and $b_2 \in L_2 - \{0\}$. As $(b_1, b_2)$ is a basis of $\R^2$, any map linear map on $\R^2$ is uniquely defined by its values for $b_1$ and $b_2$. Hence, define $A \colon \R^2\to \R^2$ by $Ab_1 := 2b_1$ and $Ab_2 := 7b_2$. Then $b_1$ is a $2$-eigenvector (and hence $L_1$ the $2$-eigenspace) and $b_2$ the $7$-eigenvector.
$A$ is uniquely defined by its values on $b_1$, $b_2$, hence its the unique linear map with this properties.
Comment: Brilliant explanation! Thank you.
Comment: Is it uniquely defined though? A vector **is** uniquely defined by its decomposition in $b_1$ and $b_2$ but if i say $v = (x, y) $ I can either have $v = xb_1 + yb_2$ or $v = xb_2 + yb_1$. This means I can have two changes of basis and 2 different matrices, as seen in my answer. Right?
Answer: There are $u,v \in \mathbb R^2$ linear independent such that
$L_1=\{tu: t \in \mathbb R\}$ and $L_2=\{tv: t \in \mathbb R\}$.
You have to show that there is a unique $2×2$ matrix $A $ with:
$(*)$ $Au=2u$ and $Av=7v$.
Let $x \in \mathbb R^2$, then there are unique $p,q \in \mathbb R$ such that $x=pu+qv$.
Now its your turn to construct $A$ such that $(*)$ holds and to show that $A$ is uniquely determined by $(*)$
Comment: Since the eigenvalues are distinct that must mean that the eigenspaces are unique. The eigenvectors are linearly independent. The matrix A can be written as a linear combination of these eigenvectors. The eigenvectors would be the columns of the matrix.
Answer: An eigenspace $E $ of a matrix A is a linear space such that $v \in E \rightarrow Av \in E $. Furthermore, all eigenspaces have associated eigenvalues. That is, if the eigenspace is a linear space of dimension 1, then it is spanned by one vector.
Therefore, if $dim\ E = 1$, $v \in E$ and $Av \in E $, then $Av$ must be a multiple of $v $. Imagine $Av = \lambda v $. Then we say $\lambda $ is an eigenvalue of $A $ and $E $ is its associated space and $v $ is an eigenvector associated with that eigenvalue.
We call it an eigenspace because vectors in that space, after transformed, keep their direction. They only get scaled by the transformation.
Now imagine the two lines they talked about. If $L_1$ and $L_2$ only meet at the origin then they are not coincident nor parallel, but they intersect eachother. Take a vector $v_1$ that spans $L_1$ and a vector $v_2$ that spans $L_2$. Then $v_1$ and $v_2$ are linearly independent and form a basis for $\Bbb R^2$. Right?
Now imagine making a change of basis, making the new lines the coordinate system. You can either pick $L_1$ to be your new $x $-axis or $y $-axis. $L_2$ will be the other. Now you just define a new linear transformation such that $T(v_1) = 2v_1$ and $T(v_2) = 7v_2$. Since any other vector in $\Bbb R^2$ can be written as $\alpha v_1 + \beta v_2$, the linear transformation is defined for all vectors already.
Now all it takes is to check the uniqueness of the matrix.
Your matrix will be 2x2 and will have 0s on the positions 1.2 and 2.1 with a 2 and a 7 in the diagonal. Now if $L_1$ is the new $x$-axis, you get
$$\begin{bmatrix}
2 &0 \\
0 & 7
\end{bmatrix}$$
on the other hand, if $L_1$ was your new $y $-axis you get
$$\begin{bmatrix}
7 &0 \\
0 & 2
\end{bmatrix}$$
And thus there are 2 matrices that work fine.
Comment: @martini isn't my train of thought right? Why can't we have 2 different matrices?
Comment: great answer! :)
Comment: @PatrickMoloney thanks. The only problem is that it contradicts the other 2 answers. The point is, the relevant linear transformation is **unique**, but it has an infinitude of possible matrix representations (by change of basis), and thus the matrix is not unique.

True/False exam Question


Probabilistic problem with two dice

Question: Two dice are rolled.
Event A is all combinations for which the sum is greater than 9.
Event B is all combinations for which at least a face is 6. What are P(A|B) and P(B|A)?
Maybe you will find it very easy, but I couldn't come up with an answer based on using Bayes' theorem and not just writing down the possibilities.
Comment: What does "at least a face is B" mean?
Comment: Sorry, I meant 6. I've updated the question
Answer: To extend Peter Flom's counting answer, assume we know (by counting or some other source), the following things:

$P(A) = \frac{1}{6}$,
$P(B) = \frac{11}{36}$, and
$P(A|B) = \frac{5}{11}$.

Bayes' theorem lets us calculate P(B|A) from those values in a fairly straightforward way. Namely, it says that:
$$P(B|A) = \frac{P(A|B) \cdot P(B)}{P(A)}$$
so, you'd plug in those values and get
$$P(B|A) = \frac{\frac{5}{11} \cdot \frac{11}{36}}{\frac{1}{6}}= \frac{5}{6}$$
This matches what you'd get by counting (see Peter Flom's answer for the enumeration). If you knew $P(B|A)$ instead, you could use a similar procedure to calculate $P(A|B)$, but you still need to do some counting to find  $P(A)$, $P(B)$ and one of $P(A|B)$ or $P(B|A)$.
Your example is a good homework exercise, but we often find ourselves in a situation where $P(B|A)$ would be useful to know, but incredibly difficult to calculate, while $P(A|B)$ is less useful but easier to estimate. Bayes' rule lets convert the former situations into the latter. For example, we'd very much like to know P(email is spam | its contents), which is hard to recover directly. However, given a lot of labelled emails, we can easily estimate P(email contains a certain word | the source email is spam), just by counting how often a word occurs in spam and non-spam emails and the overall rate of spam.
Answer: Based on the enumeration {(1,6),(2,6),(3,6),(4,6),(5,6),(6,1),(6,2),(6,3),(6,4),(6,5),(6,6)}, isn't P(B) = 11/36?
Alternatively, take the number of ways a single die will NOT show a 6 when rolled (five) and multiply this by the number of ways the second die will NOT show a 6 when rolled (five). Subtract the product from the total number of ways two dice can appear (36) and you get 11.
P(A|B) = P(A and B) / P(B) = (5/36) * (36/11) = 5/11
P(B|A) = P(A and B) / P(A) = (5/36) * (36/6) = 5/6
Answer: The other answers are not complete and/or ignoring the part of the question that says:
<code>and not just writing down the possibilities
</code>
This may be important in the case of a large number of faces of the die $N$, in which case writing down all possibilities becomes too tedious.
A die $k$ has an outcome space $X_{k}=\{1,2,\ldots,N\}_{k}$.
Assuming fair dice in the following.
It follows, that for throwing dice 1 and 2, $P(B)=\frac{2N-1}{N^{2}}$. (It may help to imagine that the possible outcomes form a matrix: the outer product of $X_{1}$ and $X_{2}$). Substituting $N=6$ gives
$P(B)=\frac{11}{36}$.
We can now evaluate $P(A|B)$ without enumerating all possibilities. Because, since one die already shows $6$ and the sum $X_{1}+X_{2}>9$, it follows for the other die $X>2N-9$, or $X>3$. So:
$P(A|B)=\frac{N-3}{2N-1}+\frac{N-3}{2N-1}-\frac{1}{2N-1}=\frac{5}{11}$.
To evaluate $P(A$), I don't see how to avoid enumerating at least some possibilities. However, in any case, the enumeration is over a finite number of possibilities, since it necessarily includes no more than $9^{2}$ possibilities, regardless of $N$. This leads to:
$P(A)=\frac{1}{6}$.
Substituting into Bayes formula, gives:
$P(B|A)=\frac{P(A|B)\,P(B)}{P(A)}=\frac{(5/11)(11/36)}{1/6}=\frac{5}{6}$.
Answer: P(A) = P(10, 11, 12). There are 3 rolls that total 10, 2 for 11 and 1 for 1 so that's 1/6.
P(B) = 1/6 + 1/6 -1/36 = 11/36
P(A|B): rolls are (4,6), (5,6), (6,4), (6,5), (6,6); 5 rolls out of 12 = 5/11
P(B|A): rolls are (4,6), (5,6), (6,4), (6,5), (6,6): 5 rolls out of 6 = 5/6 (all but (5,5))
Comment: The OP wanted a solution *without* counting possibilities.

Probabilistic problem with two dice


Como pegar o resultado de outro método em Java?

Question: Como eu pego o resultado do método 2 e coloco junto com Resultado.setText do método 1?

1

public void CalcularIMC(View view) {

        //recuperar valores digitados
        String Didade = editeIdade.getText().toString();
        String Daltura = editeAltura.getText().toString();
        String Dpeso = editePeso.getText().toString();

        //Convertendo string para números
        int    idade = Integer.parseInt(Didade);
        double altura = Double.parseDouble(Daltura);
        double peso = Double.parseDouble(Dpeso);

        // variaveis
        double ideal = altura * altura;
        double resultado = peso / ideal;

        //ARREDONDAR E DIMINUIR O NÚMERO DE CASAS DECIMAIS EM JAVA
        DecimalFormat formatador = new DecimalFormat("00.00");

        if (resultado <= 18.5) {
            Resultado.setText("Idade : " + idade +  "\nSeu IMC é: " + formatador.format(resultado) +
                    "\nMagreza: \nQuando o resultado é menor que 18,5 kg/m2");
        }
        if (resultado >= 18.5 || resultado <= 24.9) {
            Resultado.setText("Idade : " + idade + "\nSeu IMC é: " + formatador.format(resultado) +
                    "\nNormal: \nQuando o resultado está entre 18,5 e 24,9 kg/m2");
        }
        if (resultado >= 24.9 || resultado <= 30) {
            Resultado.setText("Idade : " + idade + "\nSeu IMC é: " + formatador.format(resultado) +
                    "\nSobrepeso: \nQuando o resultado está entre 24,9 e 30 kg/m2");
        }
        if (resultado >= 30) {
            Resultado.setText("Idade : " + idade + "\n Seu IMC é: " + formatador.format(resultado) +
                    "\n Obesidade: \nQuando o resultado é maior que 30 kg/m2");
        }

    }

2

public void radiobutton(){
                    genero.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                            if (checkedId == R.id.radioButtonM){
                                Resultado.setText("Masculino");
                            }else if (checkedId == R.id.radioButtonF){
                                Resultado.setText("Feminino");
                            }
                        }
                    });
                }

Comment: O que você quer dizer com "resultado do método 2"? Colocar o que exatamente no método 1?
Comment: Preciso colocar o  Resultado.setText("Masculino"); para aparecer junto com Resultado.setText("Idade : " + idade +  "\nSeu IMC é: " + formatador.format(resultado) +
                    "\nMagreza: \nQuando o resultado é menor que 18,5 kg/m2");
Answer: Imagino que a variável Resultado seja um input. Como você está dando um setText(String), no método 1 você consegue dar um getText() e concatenar, exemplo:
if (resultado <= 18.5) {
            Resultado.setText(resultado.getText() + "\n" + "Idade : " + idade +  "\nSeu IMC é: " + formatador.format(resultado) +
                    "\nMagreza: \nQuando o resultado é menor que 18,5 kg/m2");
        }

Uma sugestão, use a classe StringBuilder para dar um setText no resultado, exemplo:
        StringBuilder text = new StringBuilder();
        text.append(Resultado.getText() + "\n");

        if (resultado <= 18.5) {
            text.append(("Idade : " + idade +  "\nSeu IMC é: " + formatador.format(resultado) +
                    "\nMagreza: \nQuando o resultado é menor que 18,5 kg/m2");
        }
        if (resultado >= 18.5 || resultado <= 24.9) {
            text.append("Idade : " + idade + "\nSeu IMC é: " + formatador.format(resultado) +
                    "\nNormal: \nQuando o resultado está entre 18,5 e 24,9 kg/m2");
        }
        Resultado.setText(text.toString());

Comment: Muito Obrigado! você me salvou.


How to output specific php depending on value of content type radio

Question: In my 'Basic page' content type I've added a yes/no radio field. Currently that is outputting as the value chosen. If yes is chosen I want to output a specific button, if no was chosen I don't want to output anything. How do I go about overriding the basic page template to achieve this?
--EDIT--
I don't want the radio option showing for the site visitor, only for the content editor. I want either the button or nothing showing to the site visitor.
Comment: I have never used it, but I guess you could give this one a try: http://drupal.org/project/conditional_fields
Comment: Conditional field is for fields in node editing, not in display. Though, using something like "if second field is empty", you could achieve this.
Answer: By using @Neograph734's advice I did use conditional fields.
Within the content type structure I added a field a link field(the button I wanted to conditionally show). Then used the conditional field to show this link when needed.


How to disable entrybox when it's empty in tkinter?

Question: I am trying to get a button to be disabled when the entrybox is empty and enabled when I type in something.
this is a part where the button and the entybox is.
self.description = tk.StringVar()
self.entry_ds = ttk.Entry(self, width=25,
                          textvariable=self.description)
self.entry_ds.grid(column=0, row=1, padx=13, pady=4)
self.entry_ds.focus()

self.co_button = ttk.Button(self, text='Confirm', command=self.on_press_ds)
self.co_button.grid(column=0, row=2, pady=4)

def on_press_ds(self):
    description = self.description.get()
    if description:
        self.master.listbox.insert('end', description)
    self.destroy_ds()
    self.destroy()

I've tried using
if not self.description.get():
    self.co_button['state'] = 'disabled'

and was able to get the entrybox disabled when it's empty, but I was unable to get enabled when I typed in something.
Answer: The simplest way would be to add a trace on the related variable. Within the trace you can change the state of the button based on the current value.
First, define a function to be called by the trace:
def on_entry_trace(self, *args):
    new_state = "disabled" if self.description.get() == "" else "normal"
    self.co_button.configure(state=new_state)

Next, create the trace and force it to be called to set the initial state. You would do this in the same function that creates the variable.
The first argument to trace tells tkinter when to call the associated function. "w" says to call the function whenever the variable is written to (ie: the value changes). The second argument is the function to be called.
self.description.trace("w", self.on_entry_trace)
self.description.set("")  # initialize the state

Once that is set up, the function will be called whenever the value of the entry widget changes.
For more information on what the arguments to a function called by trace see What are the arguments to Tkinter variable trace method callbacks?
Effbot has a decent write-up of the variable traces, including information about traces, on the page The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)
Comment: I added your code. But for function ```on_entry_trace``` pycharm says  parameter```*args``` is not used. And gives me errors like ```Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\82104\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:\Users\82104\PycharmProjects\Macro\GUI.py", line 256, in on_entry_trace
    self.co_button.configure(state=new_state)
AttributeError: 'Description' object has no attribute 'co_button'```
Comment: ```co_button``` is in class ```Description``` I don't understand why it's not attributed.
Comment: @김상언: I can't help you with that -- it's all code that you didn't show in your question. As for pycharm, it's telling the truth: `*args` is not used. However, the arguments are required because the trace will send parameters to the function.


Existence and uniqueness for SDE 2D linear system

Question: I have the  following SDE $$\ddot{x} +x = \dot{B(t)}$$
with some given initial condition $(x_0,\dot{x_0})$ and where $B(t)$ is a standard Brownian motion. I can reduce it to first order by introducing the variable  $y(t)= \dot{x}(t)$.
Hence the system writes
$$
d \vec{x} = A \vec{x}dt + \begin{bmatrix} 0 \\ 1\end{bmatrix} dB(t)
$$
and $$A = \begin{bmatrix} 0 & 1 \\-1 & 0\end{bmatrix}$$
I want to show existence and uniqueness for such a SDE, (i.e. I want to show Lipschitz condition and linear growth), but I don't know how to do because usually I have a scalar SDE, while now I have to write it as a system of first order SDEs.
How can I move? I have never faced such a 2dimensional case.
Comment: Write out the LHS of the system as a vector and ensure existence and uniqueness for every entry in the vector. This gives existence and uniqueness for the entire system.
Comment: could you elaborate your comment in an answer? I've not understood
Comment: I don't know anything specific about SDE's, so I don't feel comfortable giving an answer. Usually when dealing with systems of differential equations, they are actually vector differential equations, which is why evaluating it entry-wise is a possibility if you are not familiar with higher-dimensional differential equations.
Comment: Ok, but here the systems is coupled, even if it's linear... I can't prove entry-wise existence and uniqueness
Comment: That makes sense. Have you attempted to show that the system satisfies a Lipschitz condition, and do you know about matrix-norms?
Comment: Yes I'm familiar with them, but never used to prove existence and uniqueness. How can I start?
Comment: Using the Frobenius norm as an example we have that $||Ax||_F \leq ||A||_F ||x||$. Hopefully this could help with finding your Lipschitz constant.
Comment: To show lipschtiz conditions I can do $||Ax-Ay)|| = ||A(x-y)|| \leq ||A|| ||x-y||$.

I should also show linear growth, but I don't know if in the sdes system context it is the same in the ode case
Answer: In this specific example you do not need SDE theory for the stated purposes. To that end, use $y=\dot x-B$ as second state variable, then
\begin{align}
\dot x(t) &= y(t)+B(t)\\
\dot y(t) &=  -x(t)
\end{align}
is an linear ODE system with continuous inhomogeneity (assuming you take a pathwise continuous realization of the Brownian motion, as is usually done).
Comment: Thanks for your answer. I thought I had to prove lipschitz condition and linear growth, maybe using matricial norms.  So in practice you're reating $t \mapsto B(t)$ as a general linear function (in this case nowhere differentiable) right?
Comment: $t\mapsto B(\omega,t)$ is for any fixed $\omega$ of the probability space a continuous function. Thus the ODE existence and uniqueness theorems apply for every $\omega$ separately. You might still have to invoke the SDE theory if you want to use claims on statistical properties. Then you get the cited conditions from the fact that the system is linear.


Makefile match any target / task

Question: I want to write a makefile that can be run with any task and just echo all the task names.
Is there any way to do this?
Like:
<code>%.%:
    echo "$@"
</code>
Comment: What do you mean by "all the task names"?
Comment: @200_success: Q title specifies `target / task`. Good luck to all.
Comment: But in the general case, not all targets can be known.
Answer: Assuming that your make is GNU make or alike, use the following Makefile:
<code>.PHONY: all

%:
       @echo "Here I am! $@"
</code>
See the result:
<code>> make first
Here I am! first
> make second
Here I am! second
> make first second
Here I am! first
Here I am! second
</code>

Makefile match any target / task


Quotient of $\Bbb Z$ with the right half-line topology

Question: Let $\Bbb Z$ be the set of integers with the topology $\mathscr T_{\Bbb Z} = \{U_x \mid x \in \Bbb R\}$ where $U_x := \{z \in \Bbb Z \mid z > x\}$.
Let $\sim$ be a equivalence relation such that $x \sim y \iff x^2 = y^2$ , $\Bbb Z/_\sim$ the quotient space and $\pi:\Bbb Z \longmapsto \Bbb Z /_\sim$ the quotient-projection.
I have to understand the structure of $\Bbb Z /_\sim$ and tell if it is compact.
I suppose that $\Bbb Z /_\sim$ is homeomorphic to $\Bbb N$ and then I started searching for a homeomorphism between $\Bbb Z /_\sim$ and $\Bbb N$. I believe that this function is $h: \Bbb Z /_\sim\rightarrow \Bbb N \quad [z] \longmapsto |z|$ where $[z]$ is the equivalence class of $z$. Now I need to understand what kind of topology have $\Bbb Z /_\sim$.
Suppose $A$ is an non-empty open set of $\Bbb Z /_\sim$ such that $A \neq \Bbb Z /_\sim$. There is $[p] \in A$. Suppose that $p > 0$; since $A$ is open $\iff B := \pi^{-1}(A)$ is open we have that $p,-p \in B$ and $B = U_x$ with $x<-p$. Let $q > |x|$: of course $q \in U_x$ hence $[q] \in A$. But if $[q] \in A$ then $-q \in B$ and that is absurd so $\mathscr T_{\Bbb Z /_\sim} = \{\emptyset,\Bbb Z /_\sim\}$. Since $\Bbb Z /_\sim$ has the trivial topology it is compact.
My question is, how can I know what topology $\Bbb N$ have? I can choose it just to make my function $h$ an homeomorphism? Are there any errors in my reasoning? Thank you in advance.
Answer: Let's skip the fact that the topology you provide is not a topology as it does not include the empty set and assume you just forgot.
So you give some thought about the equivalence relation and you realise that you are basically gluing pairs of integers, $x\sim\pm x$ and so the equivalence classes correspond to the natural numbers (or any other set of the same size) and we can use your quotient map, $q : n \mapsto |n|$ (note I am including 0 in the naturals).
Now recall the definition of a quotient topology: $U$ is open in the quotient space if and only if $q^{-1}(U)$ is open in the original space.
Now think of your favourite number. Your favourite number is 7. Think really hard and you see that $q^{-1}(7) = \{7,-7\}.$ Suppose that 7 is in an open set. Then it's preimage must be open. Thus it's preimage must include the fibre of 7. What open sets in $\Bbb Z$ include the preimage of 7? Well it's all open sets $U_x$ where $x<-7$. And then for $x<-7$, $q(U_x) \subset q(\Bbb N) = \Bbb N.$
We think a little harder and now write down a proof that if an open set in our quotient space is not empty then it is the whole space. This is not a very interesting topology.
Answer: Your reasoning is correct, and the quotient space has the trivial topology. There are of course many possible topologies on the natural numbers. However, the most natural way (I think at least) to think of the natural numbers is that they sit inside $\mathbb{R}$, as a subset. There is a standard topology on $\mathbb{R }$, which induces a standard topology (the subspace topology) on the subset $\mathbb{N}$.
This subspace topology on the naturals is the discrete topology, since for each natural number we can find a small open interval in the reals containing it and no other naturals. This is intuitive since you probably think of the naturals as a set of lone points which are entirely disconnected, i.e. discrete.
So in a way, your quotient space is topologically as different from the natural numbers as a countable space can be - the trivial topology being the coarsest and the discrete topology the finest.


AWS is eating up storage space

Question: I have ec2 account setup with size of 80GB. I have uploaded ML code of 2gb on this ec2 instance. However for some reasons my instance is 99% occupied in terms of storage space
ubuntu@ip-172-31-41-142:/dev$ df xvda1
Filesystem     1K-blocks     Used Available Use% Mounted on
/dev/xvda1      76171508 75318652    836472  99% /

Something is eating up almost 98% of my ec2 instances storage space. What is it and how do I clear this space
Answer: That something may be log files which have become too large and need to be removed.
Try eliminating the ones above 4MB size:
find / -type f -size +4M -exec ls -lh {} \;

If you attempted file deletions, make sure there are not processes still accessing them and check into deleted ones:
find /proc/*/fd -ls | grep  '(deleted)'

Comment: They usually have .log extension. Examples: /var/log/eb-activity.log

/var/log/eb-commandprocessor.log

/var/log/eb-version-deployment.log . See here some info on where to find other logs: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.logging.html
Comment: I do get a list of files, after executing your first command. But how do I distinguish between a log file and normal files. Do log files have any specific file extentions
Comment: For example I am no sure if "-rwxrwxr-x 21 ubuntu ubuntu 11M Mar 22  2018 /home/ubuntu/anaconda3/envs/chainer_p36/lib/libmkl_vml_mc.so
-rwxrwxr-x 21 ubuntu ubuntu 11M Mar 22  2018 /home/ubuntu/anaconda3/envs/chainer_p36/lib/libmkl_gf_lp64.so
" is a log file or not
Answer: The version that I took of AWS shipped with pre-installed conda virtual environments. I needed to do
conda env list

and then delete the unnecessary virtual environments
Answer: Sometimes looking for the largest directories can be a good option.  Here's a method I use frequently: du -hx / | sort -hr | head -n 30 - this gives the top 30 directories occupying the most space.  Change 30 to whatever number you want - I usually try to make it a few lines less than the number of lines on my terminal.
Once you have an idea of which directories are large, you can research what they're used for and how to clean them up best.  e.g. If /var/cache/apt is large, you probably should consider running apt clean; if /var/log is the largest, you should work out which applications are logging the most and look into tuning their log output to be less verbose.
Of course, sometimes it's all legitimate disk space usage, and the simplest and most expedient solution is just to add more disk.

AWS is eating up storage space


Spring-boot ErrorPage not working with standalone Tomcat

Question: I am still struggling to get the Spring-boot error page stuff working completely in a standalone tomcat with deployed WAR file.
I have a configuration class as follows:
@Configuration
@ComponentScan
@EnableAutoConfiguration(exclude = [ GroovyTemplateAutoConfiguration, SecurityAutoConfiguration, ErrorMvcAutoConfiguration, JmxAutoConfiguration ] )
class Application extends SpringBootServletInitializer {

    @Override protected SpringApplicationBuilder configure( SpringApplicationBuilder application ) {
        application.sources( Application )
    }

and also have my error handling configuration as follows:
@Configuration
class ErrorConfiguration implements EmbeddedServletContainerCustomizer {

    @Override public void customize( ConfigurableEmbeddedServletContainer container ) {
        container.addErrorPages(new ErrorPage( HttpStatus.NOT_FOUND, "/errors/404" ))
    }

This info seems to be getting used, but not as I would expect - If I just go to a non-existent URL then I get the tomcat default 404 page - however, Spring does seem to be returning my ErrorPage path, as the Tomcat page looks like this:
HTTP Status 404 - //errors/404

type Status report

message //errors/404

description The requested resource is not available.

Apache Tomcat/7.0.54

If I change my error config and use a different path, then that path gets passed through as the 404 message - Does anyone know what I have missed? I am expecting the message to just be something like "Not found" and the path /errors/404 to be used to resolve a view/controller to render the error page.

UPDATE
I have the error path mapped as a standard view controller in my web config:
@Configuration
@EnableWebMvc
class WebMvcConfiguration extends WebMvcConfigurerAdapter {

    /**
     * Register static views that dont need controller calls - map URLs direct to views
     */
    @Override public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/errors/404").setViewName("errors/404")
        registry.addViewController("/errors/500").setViewName("errors/500")
    }

Also, if I just go straight to the error path in the browser - /errors/404 - then I get the error page I expect.

UPDATE 2
I have created a dummy Spring Boot web app with auto-error handling and deployed to my tomcat running in Eclipse and the whitelabel error page displays correctly. I then deploy it on to my development server tomcat and the whitelabel error pages stop working (I see default tomcat 404 page).
My web.xml is the same across both (copied the web.xml from eclipse to dev server) and the server.xml is below (essentially the same as the eclipse version really)
<Server port="8005" shutdown="SHUTDOWN">
  <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
  <Listener className="org.apache.catalina.core.JasperListener"/>
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <GlobalNamingResources>
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
  </GlobalNamingResources>

  <Service name="Custom">
    <Executor name="tomcatThreadPoolwr" minSpareThreads="4" maxThreads="500" namePrefix="catalina-execwr-"></Executor>
    <Connector port="8081" protocol="org.apache.coyote.http11.Http11Protocol" connectionTimeout="20000" redirectPort="8443" executor="tomcatThreadPoolwr" maxThreads="10"></Connector>
    <Connector port="9998" protocol="AJP/1.3" redirectPort="8445" maxThreads="500" tomcatAuthentication="false" connectionTimeout="21000"></Connector>
    <Engine jvmRoute="custom" name="Custom" defaultHost="localhost">
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"></Realm>
      </Realm>
      <Host name="localhost" autoDeploy="true" deployOnStartup="true"  unpackWARs="false" appBase="/tmp/dev/custom" workDir="/tmp/dev/custom/work" createDirs="true">
        <Context docBase="/tmp/dev/ROOT" path="/" reloadable="true" override="true"/>
        <Valve pattern="common" directory="/var/log/tmp" prefix="custom_access_log." className="org.apache.catalina.valves.AccessLogValve" suffix=".log" resolveHosts="false"/>
      </Host>
    </Engine>
  </Service>
</Server>

Furthermore:

If i navigate directly to /error I see the whitelabel page, so the endpoint is working correctly
If I create a file called "error" in the webroot, this gets picked up and displayed. So it seems like the application is trying to re-route my 404 correctly, but for some reason is only looking for "error" file, rather than the "error" endpoint in the application

UPDATE 3
I have investigated further, and even if I use the exact same server.xml and web.xml on a local, clean tomcat install it still works locally.
I have also seen that it appears to be a problem with the RequestDispatch for the request.
If I run the following code on my development server (anywhere, but from a controller for example) it doesn't work:
request.getRequestDispatcher("/errors/404").forward(request,response);

But the following does:
servletContext.getRequestDispatcher("/errors/404").forward(request,response);

(where request and response are HttpServletRequest/Response and servletContext is an autowired ServletContext object)
Both of the above example work correctly on a clean local tomcat install - any ideas what might cause problems for the request linked RequestDispatcher whilst the ServletContext RequestDispatcher still works?  The ErrorPageFilter uses the request linked RequestDispatcher so hits this problem.
Comment: Where did you define the handler for "/errors/404"?
Comment: Its defined as a view controller in my web config- just mapping to src/main/resources/templates/errors/404.HTML (im using thymeleaf, but that's just static HTML file)
Comment: Can you post that code? It seesm like it's the viewhandler that it can't find.
Comment: Thanks @DaveSyer - have updated with the config.  I have tried including/excluding the Boot error config and neither seems to make a difference to this behaviour - is there any other error config I am missing?
Comment: Isn't it the "//" (double slash) that's broken (Tomcat can't resolve it, and doesn't bother to try and normalize the path). I guess you need to register it without the leading "/" in the container?
Comment: Wait, didn't you say this was in a standalone Tomcat? There is no point registering an error page for the embedded container in that case is there?
Comment: @DaveSyer I have tried removing the leading slash but still no joy - the message with the 404 becomes relative to the current URL you are on and still just the default tomcat 404 page
Comment: @DaveSyer This is what I originally would have guessed, but from the docs/comments in the source code, I was understanding that the ErrorPageFilter basically made this supported in standalone deployments? https://github.com/spring-projects/spring-boot/blob/master/spring-boot/src/main/java/org/springframework/boot/context/web/ErrorPageFilter.java
Comment: Ah, yes, that rings a bell. So it should be working. Can you create a test project and post a link on Github?
Comment: Sure thing, will try and re-create it.
Comment: @DaveSyer I created a basic Spring boot starter project and deployed it to my tomcat instance, and that had the same problem just trying to load the default whitelabel page. I then deployed it to a fresh tomcat on my local machine and that worked ok - so looks like some config in my tomcat config that is affecting it - any ideas what might be?  web.xml more or less looks the same across the two - the server.xml is a bit more complicated as it has specific service/connectors defined for the app - that likely to cause issues you think?
Comment: Hmm, interesting. I couldn't say without looking at the `server.xml`. Does it set a default `web.xml`?
Comment: @DaveSyer it has a server level web.xml (I havent added an application specific web.xml) - but looking through it, except for some MIME mappings there isnt any difference between that web.xml and the web.xml I have on my local tomcat running (where it is working)
Comment: So can we see the server.xml?
Comment: @DaveSyer still no joy - I have now added some details on the setup using the dummy Spring Boot app. I have also included the server.xml configuration.  The error handling just doesn't seem to be routing to application/controller endpoints
Comment: Different version of Tomcat?
Comment: @DaveSyer 7.0.54 and 7.0.47 - will try using the same version of tomcat, but only minor differences, so assume that should be ok?
Comment: @DaveSyer tried both on 7.0.54 - results both as in original scenario.
Comment: @DaveSyer - added another update :) Looks like the request linked RequestDispatcher is not mapping it ok. Any ideas?
Answer: In the end it was caused because there was a ROOT directory being created in the tomcat appBase (this was being created as part of the WAR deploy process) - and it looks like that then caused some confusion with two ROOT contexts (the WAR was deployed as a ROOT war).
Fixing the tomcat setup so it just had the WAR file as expected this started to work.


Elixir build on Heroku review app fails with (ArgumentError) argument error :erlang.binary_to_atom(nil, :utf8) when running mix release

Question: We have a Phoenix application that has been running in production on Heroku for the last year.
Now I am attempting to enable pull request versions of the application to run via review apps as part of a Heroku pipeline.
The application has three Heroku buildpacks:

https://buildpack-registry.s3.amazonaws.com/buildpacks/hashnuke/elixir.tgz
https://github.com/gjaldon/heroku-buildpack-phoenix-static
our own buildpack (see below)

Our own buildpack is very straightforward. Here is the bin/detect script:
#!/bin/sh

exit 0

And here is the bin/compile script:
#!/bin/bash

cd $1
mix release

Whilst the build has been working for production, unfortunately for the PR which is designed to enable review apps, it is failing when it gets to the final buildpack. Here is the relevant output from the Heroku build:
-----> https://github.com/orgname/buildpack-name.git app detected
** (ArgumentError) argument error
    :erlang.binary_to_atom(nil, :utf8)
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (stdlib) erl_eval.erl:878: :erl_eval.expr_list/6
    (stdlib) erl_eval.erl:236: :erl_eval.expr/5
    (stdlib) erl_eval.erl:228: :erl_eval.expr/5
    (stdlib) erl_eval.erl:878: :erl_eval.expr_list/6
    (stdlib) erl_eval.erl:404: :erl_eval.expr/5
 !     Push rejected, failed to compile https://github.com/orgname/buildpack-name.git app.
 !     Push failed

So it seems to be failing in the mix release step but the error message doesn't give me a good idea of why. I have found a similar problem report, which suggests that the problem I'm trying to solve may be due to one or more missing environment variables. However, I've double checked and can't see any environment variables that are missing.
Any suggestions about how I might solve this problem would be most welcome.
Comment: Just a clarification: are you aware of `mix release` does compile `config.exs`, but during release startup it loads **only** `releases.exs`?
Comment: @AlekseiMatiushkin thanks. Yes, I've been reviewing https://hexdocs.pm/mix/Mix.Tasks.Release.html as part of ensuring I understand the various aspects of this problem. What I'm currently trying to figure out is what's different about the review app environment compared with production with respect to releases.
Comment: In any case, that's surely an unset environment variable issue. Try to print all of them out upon `Application.start/2` and see what's missing?
Answer: Thanks to Aleksei Matiushkin for his comments, which helped me track down the cause of the problem.
I had introduced a new environment variable, which I was fetching in both config/prod.exs and config/releases.exs. When I removed it from config/prod.exs then mix release succeeded in building the release for the Heroku review app.
I guess the moral of this story is to not configure a value both at build-time and runtime.


Running maximum absolute value of Wiener process

Question: In Wikipedia a formula is given for the distribution of $$M_t = \max_{0\leq s \leq t} W_s$$
even conditioned on $W_t$.
I wonder if there is also a simple expression for (note the absolute value)
$$\tilde M_t = \max_{0\leq s \leq t} |W_s|$$
maybe conditioned on $|W_t|$?
Comment: the derivation of $M_t$ comes from reflection principle. At moment, i cannot see how it would work for $\tilde{M}$
Answer: I'd recomment Borodin and Salminen's Handbook of Brownian Motion - Facts and Formulae. There's no simple expression for the distribution, but formula 1.1.8 at page 250 gives for $y > \max(x,z)$:
$$P_x(\max_{0<s<t}|W_s|<y, |W_t| \in dz) = $$
$$\frac{1}{\sqrt{2\pi t}} \sum_{k=-\infty}^\infty(-1)^k \left( e^{-(z-x+2ky)^2/2t} +  e^{-(z+x+2ky)^2/2t} \right)\,dz $$
Isn't that a beautiful work of art... You can use standard techniques to obtain all the formulas you want (but they'll still look like this).
EDIT (as a reply to the a comment): We have the following for the cdf:
$$P_x(\max_{0<s<t}|W_s| \geq y) = $$
$$\sum_{k=-\infty}^\infty (-1)^k \textrm{sign}(x+(2k+1)y) \textrm{Erfc}\left( \frac{|x+(2k+1)y|}{\sqrt{2}t}\right) $$
and to obtain the expectation on does $E_x(\max \ldots) = \int_0^\infty P_x(\max\ldots)\,dy$.
Comment: What is $x$ here?
Comment: @Greg P it's standard notation to have $P_x(X_t \in A) := P(X_t \in A \,|\,X_0=x)$. Long story stort it's the starting position. In his particular case: $x= W_0 = 0$.
Comment: Thanks. I have been trying to calculate this quantity (say, with $x=0$) without the conditioning over $|W_t|$. Due to the constraint $y > \max(x,z)$ I'm not certain how to get it. Should I integrate $P$ over $z$ from $0$ to $y$?
Comment: @Greg Yes that is what you should do, but you'll just obtain a series of error functions. The same book I cited also gives it in a simpler form, as the inverse of a Laplace Transform. $P(\max |W_s|\leq y) = \mathcal{L}^{-1}_\gamma (1/\gamma ch(y\sqrt{2\gamma}))$. The book also has it as a sum of *erfc* but the comment section is a bit small.
Comment: You could put it in your answer, since it seems relevant to the question ;-)
Comment: Is there a simple expression for the expectation value of $\max |W_s|$?
Comment: @GregP I've added the part that you've asked me to, to the answer and I'll get back to you for the expectation.
Comment: @GregP In the case $x=0$, $E(\ldots)=t\sqrt{\pi/8}$. (May have an error but there's a simple answer). To calculate: cut the sum on integers in two sums on strictly negative and on positive integers. Simple change of variable will give that both sums are equal. Integrate now and by using a simple integration by parts (i.e. a $y^\prime$ artificially to derivate the Erfc). From then it's easy, dont forget the series expansion or arctan to reduce the sum.
Comment: Hi, can you please take a look at a similar problem? https://math.stackexchange.com/questions/3126681/max-of-absolute-value-of-a-brownian-motion/3126708?noredirect=1


Change spaces with underscore in filename

Question: I have a multiples files with space, and I want replace this for a underscore with command line (Mac)
xxx xxx.jpg -> xxx_xxx.jpg
It's possible with only line command?
Answer: For all files in current directory
for i in *;do mv "$i" "${i// /_}";done

If you only want to match files with spaces (to prevent tons of error messages when it tries to move files into themselves) though you could use extended glob
shopt -s extglob
for i in +(* *);do mv "$i" "${i// /_}";done

Comment: @Inian Who said anything was wrong with it? It hasn't been downvoted?
Comment: Upvote for utilizing Bash's built-in regex abilities instead of piping through to something else. Nice!
Comment: Please always use `mv -i` to avoid accidental overwritten files in bulk moves!


scikit learn train_test_split for loop

Question: I want to create 5 different training and test sets by looping train_test_split like:
for i in range(0,5):
X_train, X_test, y_train, y_test = train_test_split(features, y, test_size=0.2, random_state=i)

and I want to create a list that stores 5 different splits and from each split I can run testing. My question is how should I create a list to store X_train, X_test, y_train, y_test and afterwards how do you call each split from the list to run test?
For the test I mean running ml algorithms.
Answer: My suggestion as a simple solution:
datas = []
for i in range(0,5):
    a,b,c,d = train_test_split(features, y, test_size=0.2, random_state=i)
    datas.append((a,b,c,d)

if you want get any sets from datas you can use this code. For expample you want use to index 3.
X_train, X_test, y_train, y_test = datas[3]

Answer: To OPs question for creating 5 different test and train dataframes, the following should work:
from random import randint
trainX_list=[[]]
trainY_list=[[]]
testX_list=[[]]
testY_list=[[]]
for i in range (0,4):
    X_train, X_test, y_train, y_test = train_test_split(features, y, test_size=0.2, random_state=randint(100, 1000))
    trainX_list.append([X_train])
    trainY_list.append([y_train])
    testX_list.append([X_test])
    testY_list.append([y_test])

You can then do pd.concat(trainX_list[i]) to view each dataframe!

scikit learn train_test_split for loop


A question about the definition of measurable sets.

Question: $\newcommand{\scrF}{\mathscr{F}}$
I've been thinking about some of the topics I've learned in basic measure theory and I'm having a bit of a conceptual issue. We introduced first the notion of a $\sigma$-algebra so that if $X$ is a non-empty set and $\scrF$ is a $\sigma$-algebra defined on $X$ then the pair $(X,\scrF)$ is a measurable space. Then we studied measures for a while and measurable functions etc; where the measurability of some $f:X \rightarrow \mathbb{R}$ is intimately related to the measurable space $(X,\scrF)$ since a function is measurable only if preimages of Borel sets in $\mathbb{R}$ happen to live in $\scrF$.
I suppose I never thought to question this critically but why do we say that $(X,\scrF)$ constitutes a measurable space? What about the structure of a $\sigma$-algebra makes the subsets it contains measurable? A reason I ask is because I was reading this answer about the construction of measures from outer measures and I realized that I didn't really know what was nice about the sets in a $\sigma$-algebra. Why do they play so well with integration and measure theory, and why couldn't we have a theory of integration/measure without $\sigma$-algebras? Thanks in advance for the clarification.
Comment: Basically the conditions of closure under complements/countable unions are needed for a measure function to make sense. Some of the answers [here](https://stats.stackexchange.com/q/199280/307706) may be helpful too
Comment: the approach of Percy [Daniell](https://en.wikipedia.org/wiki/Daniell_integral) and extended by Marshall Stone is one way to build integration without measure theory. Measure theory (and sets structures such as $\sigma$-algebras) are obtained as a byproduct. A brief summary of this method is [here](https://math.stackexchange.com/a/4573598/121671)
Comment: I discuss a bit *why* you need some sort of "measure of sets" to develop the kind of integration theory a la Lebesgue [here](https://math.stackexchange.com/a/7444/742),
Answer: The motivation comes from trying to define a measure on the real numbers. To be useful, it should reflect our intuitive notions about length. We are trying to find a function $\mu : \mathcal{P}(\mathbb{R})\rightarrow \mathbb{R}$ that respects the following properties:

If $I$ is an interval $[a, b]$, then $\mu(I) = b - a$,
For any $a \in \mathbb{R}$, $\mu(A + a) = \mu(A)$ for all sets $A \subset \mathbb{R}$,
If $(A_i)_{i \in \mathbb{N}}$ is a countable collection of pairwise disjunct sets, then $\mu(\bigcup A_i) = \sum \mu(A_i)$.

It turns out that such a function cannot exist: An easy way to show this is by using a Vitali set, defined as follows. We define a relation $\sim$ on $[0,1]$ by $a \sim b$ if $a - b \in \mathbb{Q}$. It is easy to show this is an equivalence relation. Take the quotient $[0,1]/\sim$ and choose one representative for each equivalence class. Call the set of these representatives $V$.
It is now easy to show that any two copies of $V$ translated by rational numbers are disjunct (i.e. $V + p \cap V + q = \emptyset$ for any $p \neq q$, $p, q \in \mathbb{Q}$.
Thus, by property (3), $ \mu(\bigcup_{q \in \mathbb{Q}, |q| < 1} V + q \cap [0, 1]) = \sum_{q \in \mathbb{Q}, |q| < 1} V + q \cap [0, 1]$. However, it is easy to show that $\bigcup_{q \in \mathbb{Q}, |q| < 1} \mu(V + q \cap [0, 1]) = [0,1]$, thus,
$$ 1 = \sum_{q \in \mathbb{Q}, |q| < 1} \mu(V + q \cap [0, 1])$$
by property (1). By property (2),
$$ \sum_{q \in \mathbb{Q}, |q| < 1} \mu(V + q \cap [0, 1]) = \sum_{q \in \mathbb{Q}, |q| < 1} \mu(V \cap [0, 1]),$$
but it is clear that there is no real number $\mu(V \cap [0, 1])$ other than $0$ such that this series converges.
All this shows that a function defined on all of $\mathcal{P}(\mathbb{R})$ with the properties 1-3 cannot exist. Usually, one moves on from this by defining the outer Lebesgue measure and then finding ''good'' (measurable) sets for which these properties do hold. One then shows that these sets form a sigma algebra, which is useful for showing that certain sets are also measurable. When moving on to abstract measure spaces, one starts from the sigma algebra, having learned that one usually cannot define a good measure on the entire power set.
Comment: It is good to note that we used the axiom of (countable) choice in constructing $V$. This is not a quirk of this particular example. In fact, non-measurable sets of real numbers can only be constructed using some version of choice.


What does Citrix's definition of Load Bias mean?

Question: I'm having trouble understanding the definition. It can be found here. Small section:

The Load Bias also called the Protocol Mask, is retained in the memory resident database referred to as the dynamic store on the data collector. The dynamic store uses the Load Bias value to inflate the load for the server during the client resolution phase until the true load value is received.
If a server is least loaded by a load value of 1000, a Load Bias of 100 decimal allows 10 connections to be resolved to that server before subsequent connections are balanced to the other servers. This is a temporary condition until the server sends the load update to the local data collector.
Answer: Minimum load assignment and preference at initial client connect/access until the "true" load is determined.
Comment: so is it just an upper bound on "true" load? Like a load will first be assumed to be 100, then it's later updated to its true value of 40? So if that were true for all connections, then 10 would connect, and the server would think its full, but after they all updated you'd have room for 6 more initial connections, etc?
Comment: Initial assumption until the true load is determined - where to "park" initial sessions as all session initiations may not follow-through to become actual sessions (e.g. DoS attacks).


Exchange 2013 send connector issue

Question: Hi I am new for exchange server . In my organisation we having exchange server 2013 & I had purchase 2 domain from hosting provider. I want to configure both the domain with my exchange server. My problem is currently on one send connector is working which used for send the emails. I want to configure two send connectors to my two different domains.
Domain 1 emails should be send through domain 1 send connector and domain 2 emails should be send through domain 2 send connectors.
Also, note i have not created child domain, i have only added the authoritative domain and email address policy is created for the same.
To use both the domain for different send connectors, what procedure we should follow.
Request you to suggest the same.
Regards
Shadab Ansari
Answer: The question that has to be asked is why?
Exchange doesn't route based on the originating domain, only on the recipient domain. Therefore out of the box, what you want to do isn't possible, and isn't necessary.
To work correctly, you just need a static IP address. Decide on a host name that will apply to your Exchange server and configure an A record for that host name in either of the two domains. Ask the ISP to set a PTR to match that host name, and configure the host name in the FQDN field of your send connector.
As long as all three things match, then you will be able to send email for any domain hosted by the Exchange server.
If you insist, then you will have to use a third party transport agent known as a sender based routing agent.

Exchange 2013 send connector issue


Efeito CSS TRANSITION invertido

Question: Como faço para que essa barra de pesquisa em vez de ser aberta para direita ser aberta para esquerda?

<form action=" " method="post">
  Buscar
  <input class="input_home" type="search" id="busca" name="q">
  <button type="submit">OK</button>
</form>
Answer: Pelo que eu entendi vc quer que a barra cresça, mas que o btn OK fique na direita certo.
Da forma que vc construiu o Form a maneira que encontrei foi colocando um margin-left no button com um transition quando vc fizer o focus no input. Então ao mesmo tempo que vc faz o focus no input e faz o transition nele eu tb faço um transition no button que vem a seguir com

Vc vai reparar que eu usei dois transition no button, ou antes e outro depois do :focus, isso foi preciso para fazer o "ajuste fino" enquanto o elemento abre e fecha para que fica mais sincronizado, mas vc pode brincar com esses valores para ver o que mais te agrada.
Segue o código da imagem acima

input.input_home {
 height: 50px;
 border: none;
 outline: none;
 padding-left: 50px;
 width: 0;
 position: absolute;
 top: 0;
 left: 0;
 background: none;
 z-index: 3;
 transition: width 1s ease-out;
 cursor: pointer;
}

input:focus {
 border: 1px solid #ccc;
 border-radius: 25px;
 width: 50%;
 z-index: -1;
 padding-right: 50px;

 transition: width 1s linear;
}

button {
 transition: margin-left 0s linear;
}

input:focus+button {
 margin-left: calc(50% - 65px);
 transition: margin-left 900ms linear;
 transition-delay: 100ms;
}

form {
 width: 50%;
}

button {
 height: 50px;
 width: 50px;
 background: url('lupa.png') center no-repeat;
 /* background:  url('https://placecage.com/50/50')  center no-repeat; */
 border: none;
 position: absolute;
 top: 0;
 z-index: 2;
 cursor: pointer;
}

button:focus {
 outline: none;
}

/* esconde o LABEL "Buscar" */
label {
 position: absolute;
 width: 1px;
 height: 1px;
 padding: 0;
 margin: -1px;
 overflow: hidden;
 clip: rect(0, 0, 0, 0);
 border: 0;
}
<form action=" " method="post">
 Buscar
 <input class="input_home" type="search" id="busca" name="q">
 <button type="submit">OK</button>
</form>
Comment: O que eu gostaria brother é justamente o contrario, que o botão ficasse na direita e ao clicar nele a barra fosse pra esquerda
Comment: @Cairoodev se ela for pra esquerda vai ir para fora da tela...
Comment: ai basta eu colocar o botao do lado esquerdo também não? você consegue fazer isso?
Comment: ai o input e o btn vai ir para fora da tela, não vejo sentido nisso, acho que devo ter entendido algo errado, pois crescendo para esquerda não me parece correto. Tem como mostrar um exemplo ou explicar com um pouco mais de detalhe?
Comment: Isso que eu gostaria de saber se é possível fazer com esse código po. Basta imaginar esse efeito indo da direita para esquerda
Comment: @Cairoodev se é que eu entendi acho que daria sim, mas no caso o ideal seria ter um outro elemento ali por tras que nele teria essa borda cinza, e ele cresceria ao contrario. Vc teria que pensar em outra forma de montar essa estrutura de HTML e o CSS tb mudaria bastante.

Efeito CSS TRANSITION invertido


spark-hive - Upsert into dynamic partition hive table throws an error - Partition spec contains non-partition columns

Question: I am using spark 2.2.1 and hive2.1. I am trying to insert overwrite multiple partitions into existing partitioned hive/parquet table.
Table was created using sparkSession.
I have a table 'mytable' with partitions P1 and P2.
I have following set on sparkSession object:
"hive.exec.dynamic.partition"=true
"hive.exec.dynamic.partition.mode"="nonstrict"

Code:
val df = spark.read.csv(pathToNewData)
df.createOrReplaceTempView("updateTable") //here 'df' may contains data from multiple partitions. i.e. multiple values for P1 and P2 in data.
spark.sql("insert overwrite table mytable PARTITION(P1, P2) select c1, c2,..cn, P1, P2 from updateTable") // I made sure that partition columns P1 and P2 are at the end of projection list.
I am getting following error:
org.apache.spark.sql.AnalysisException: org.apache.hadoop.hive.ql.metadata.Table.ValidationFailureSemanticException: Partition spec {p1=, p2=, P1=1085, P2=164590861} contains non-partition columns;

dataframe 'df' have records for P1=1085, P2=164590861 .  It looks like issue with casing (lower vs upper). I tried both cases in my query but it's still not working.
EDIT:
Insert statement works with static partitioning but that is not what I am looking for:
e.g. following works
spark.sql("insert overwrite table mytable PARTITION(P1=1085, P2=164590861) select c1, c2,..cn, P1, P2 from updateTable where P1=1085 and P2=164590861")
Create table stmt:

`CREATE TABLE `my_table`(
  `c1` int,
  `c2` int,
  `c3` string,
  `p1` int,
  `p2` int)
PARTITIONED BY (
  `p1` int,
  `p2` int)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
LOCATION
  'maprfs:/mds/hive/warehouse/my.db/xc_bonus'
TBLPROPERTIES (
  'spark.sql.partitionProvider'='catalog',
  'spark.sql.sources.schema.numPartCols'='2',
  'spark.sql.sources.schema.numParts'='1',
  'spark.sql.sources.schema.part.0'='{.spark struct metadata here.......}';
  'spark.sql.sources.schema.partCol.0'='P1', //Spark is using Capital Names for Partitions; while hive is using lowercase
  'spark.sql.sources.schema.partCol.1'='P2',
  'transient_lastDdlTime'='1533665272')`

In above, spark.sql.sources.schema.partCol.0 uses all uppercase while PARTITIONED BY statement uses all lowercase for partitions columns
Comment: Can you share the 'Create table..." statement for 'mytable'? Was it created as a partitioned table?
Comment: @venBigData added create table stmt it in description
Answer: Based on the Exception and also assuming that the table 'mytable' was created as a partitioned table with P1 and P2 as partitions. One way to overcome this exception would be to force a dummy partition manually before executing the command. Try doing
spark.sql("alter table mytable add partition (p1=default, p2=default)").
Once successful, execute your insert overwrite statement. Hope this helps?
Answer: As I mentioned in EDIT section issue was in fact with difference in partition columns casing (lower vs upper) between hive and spark! I created hive table with all Upper cases but hive still internally stored it as lowercases but spark metadata kept is as Upper cases as intended by me. Fixing create statement with all lower case partition columns fixed the issue with subsequent updates!
If you are using hive 2.1 and spark 2.2 make sure following properties in create statement have same casing.
PARTITIONED BY (
p1int,
p2int)
'spark.sql.sources.schema.partCol.0'='p1',
  'spark.sql.sources.schema.partCol.1'='p2',


jqassistant Report generation fails with Maven site

Question: I've set up jqassistant successfully, created some rules which are checked in our maven build.
However, when I try to create a Report from the results of the checks I'm getting the following infofrom the console when running mvn site and of course no report is generated:
[INFO] --- maven-site-plugin:3.3:site (default-site) @ mvb-bfa ---
[INFO] configuring report plugin org.apache.maven.plugins:maven-project- info-reports-plugin:2.8.1
[INFO] configuring report plugin    com.buschmais.jqassistant.scm:jqassistant-maven-plugin:1.1.2
[WARNING] ignoring com.buschmais.jqassistant.scm:jqassistant-maven-plugin:1.1.2:report goal since it is not a report: should be removed from reporting configuration in POM

Relevant part of pom.xml:
<reporting>
    <plugins>
        <plugin>
            <groupId>com.buschmais.jqassistant.scm</groupId>
            <artifactId>jqassistant-maven-plugin</artifactId>
            <reportSets>
                <reportSet>
                     <reports>
                          <report>report</report>
                     </reports>
                </reportSet>
            </reportSets>
       </plugin>
    </plugins>
</reporting>

Scanning and analyzing is working without problems.
Any Ideas?
Edit: Configuration for scan/analyze
<build>
    <plugins>
        <plugin>
            <groupId>com.buschmais.jqassistant.scm</groupId>
            <artifactId>jqassistant-maven-plugin</artifactId>
            <version>1.1.2</version>
            <extensions>true</extensions>
            <executions>
                <execution>
                    <id>default</id>
                    <goals>
                        <goal>scan</goal>
                        <goal>analyze</goal>
                    </goals>
                    <configuration>
                        <failOnViolations>false</failOnViolations>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Answer: The problem in your configuration is that you have <extensions>true</extensions> in your configuration.
From the documentation, the basic correct configuration for the plugin is the following and note that:

The jQAssistant Maven plugin must be configured in the pom.xml of the root module, it should not be overwritten by sub-modules.

This means this configuration needs to be at the top-level POM in a multi-module project.
<project>
    ...
    <build>
        <plugins>
            <plugin>
            <groupId>com.buschmais.jqassistant.scm</groupId>
                <artifactId>jqassistant-maven-plugin</artifactId>
                <version>1.1.2</version>
                <executions>
                    <execution>
                        <id>scan</id>
                        <goals>
                            <goal>scan</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>analyze</id>
                        <goals>
                            <goal>analyze</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>com.buschmais.jqassistant.scm</groupId>
                <artifactId>jqassistant-maven-plugin</artifactId>
                <version>1.1.2</version>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>report</report>
                        </reports>
                    </reportSet>
                </reportSets>
            </plugin>
        </plugins>
    </reporting>
    ...
</project>

It appears that the current documentation has both versions (with and without <extensions>true</extensions>) because it might be needed in build environments where other extensions are present. An issue was created to track this: https://github.com/buschmais/jqassistant/issues/349
Comment: BTW: Thanks @tunaki for helping on that issue!
Comment: @DirkMahler I edited my answer with the link to the issue just created, it will also document this :)


generating ics file programmatically but never able to produce what timezone invitation was produced

Question: Hi I was trying send meeting invites through my asp.net MVC application. There was a requirement to show which timezone this invite was created as in following image. I tried various things as told by Microsoft support, neither of them worked.

As per Microsoft Exchange Server support's advice I created following.
TZID:Sri Jayawardenepura
BEGIN:STANDARD
TZOFFSETFROM:+0530
TZOFFSETTO:+0530
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
DTSTART;TZID=Sri Jayawardenepura:20140416T033000Z
DTSTAMP:20140327T113138Z
DTEND;TZID=Sri Jayawardenepura:20140416T060000Z
LOCATION: Board room

After adding TZID inside DTSTART, it is not coming as invite to gmail.
but following works fine as invitation both in outlook configured with Exchange Server and webmails like gmail.
 TZID:Sri Jayawardenepura
BEGIN:STANDARD
TZOFFSETFROM:+0530
TZOFFSETTO:+0530
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
DTSTART:20140318T033000Z
DTSTAMP:20140327T122640Z
DTEND:20140318T060000Z
LOCATION: Board room
however that requirement of showing timezone where invite was created not fulfilled yet.
Can anyone help me. Thanks in advance.
Answer: If you look at http://www.kanzaki.com/docs/ical/dateTime.html it states that UTC time is identified by a Z suffix character as well as  The TZID property parameter MUST NOT be applied to DATE-TIME properties whose time values are specified in UTC.
I would suspect that if you are using a timezone identifier that you need to remove the Z from the end of the date to get it to work properly.
EDIT: So, I was having troubles with timezones before as well, so I had only used UTC time, however I just got one to work with a timezone, so I hope this helps. Inside VTIMEZONE, you have a STANDARD, but you do not have a DTSTART inside the STANDARD. Again, quoting from the above link, The standard or daylight component MUST include the "DTSTART", "TZOFFSETFROM" and "TZOFFSETTO" properties.
Comment: when I remove the Z, it does not change the time accordingly when the recipient is in the different timezone. Anyhow thanks for the reply josh
Answer: It is not RFC5545 compliant but many calendars will expect a TZID to be compatible with the Olson DB and also may expect to have the calendar property X-WR-TIMEZONE set.
What I have seen is that when doing all of above you increase your calendar compatibility ratio.


cassandra setup - uneven load - what did I do wrong?

Question: For the sake of understanding I setup a 4 node cluster using the latest/greatest(released) version of Cassandra. The four nodes were brought up in sequence using almost entirely default settings and seem to be communicating properly.
I then created a schema as follows:
CREATE KEYSPACE first WITH replication = {
  'class': 'SimpleStrategy',
  'replication_factor': '1'
};

Create a simple table with 5 columns and added ~100K rows of data. All well and good. Data is available from every client so I'm thinking it's evenly spread about.
So I'm looking into a backup strategy and starting to mess about with snapshots and so forth. After running nodetool snapshot on each machine I want to know what it created. I go to the first machine and look in /var/lib/cassandra/data/first and see that it's empty. Hmm.. second machine.. same thing.. third.. finally on the 4th machine I see files in the data folder and a snapshot directory.
Running nodetool ring shows that each system owns roughly 25% but the load is heavily biased towards the one system that (seems to have) ended up with all the data.
Is all the data truly on this one machine? What step did I miss in the configuration?
Answer: Cassandra assigns token range to each node in the cluster.
Since there are 4 nodes in your configuration, 25% of tokens are assigned to each node.
Every insert query will have a hash generated for that row data. The hash will always belong to one and only one of the token ranges, so this row data is stored in that particular physical node.
In your case , mostly the insert queries have same or similar partition key leading to the same physical node i.e. node 4.
For more details, watch datastax website explaining partitioning.


How to implement redis's pubsub timeout feature?

Question: I want to use Redis's pubsub feature to implement comet, but pubsub doesn't have timeout, so if I use ps.listen(), it will block, even if client closes browser.
Greenlet has a timeout feature when spawn process, but I don't know how to combine them.
Flask's pseudo code:
@app.route('/')
def comet():
    rc = redis.Redis()
    ps = rc.pubsub()
    ps.subscribe('foo')
    for item in ps.listen():
        if item['type'] == 'message':
            return item['data']
    # ps.listen() will block, so how to make it timeout after 30 s?

Answer: Because you're not threading (and I'm assuming this is intentional and in some cases wise) you must use a type of interrupt. Signals are a type of interrupt on Unix systems to allow you to return to a callback during a call that could block.
This example of a file open which will never return is in line with what you want to do. It's taken from http://docs.python.org/library/signal.html#module-signal
But a warning. Because Python uses a Global Interpreter Lock to perform OS signal handling it is subject to some stability problems. These problems should be rare normally though.
import signal, os

def handler(signum, frame):
    print 'Signal handler called with signal', signum
    raise IOError("Couldn't open device!")

# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)

# This open() may hang indefinitely
fd = os.open('/dev/ttyS0', os.O_RDWR)

signal.alarm(0)          # Disable the alarm

Answer: p = redis.pubsub(
     ignore_subscribe_messages=True
)

p.subscribe(
    DB_PREFIX + CHANEL_KEY
)

message = None
timeout = 20
stop_time = time.time() + timeout

# little hack for setting get_message polling timeout
# because redis-py have bug and first call this method processed
# without timeout
while time.time() < stop_time:
    message = p.get_message(timeout=stop_time - time.time())
    if message:
        break

if message:
    data = json.loads(message["data"])
else:
    raise HTTPRequestTimeout