text:
Q: Why do we usually use || over |? What is the difference? I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.
I mean, look at the following:
if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass

if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.

A: | does not do short-circuit evaluation in boolean expressions. || will stop evaluating if the first operand is true, but | won't.
In addition, | can be used to perform the bitwise-OR operation on byte/short/int/long values. || cannot.

A: || is the logical or operator while | is the bitwise or operator.
boolean a = true;
boolean b = false;

if (a || b) {
}

int a = 0x0001;
a = a | 0x0002;

A: a | b: evaluate b in any case
a || b: evaluate b only if a evaluates to false

A: In Addition to the fact that | is a bitwise-operator: || is a short-circuit operator - when one element is false, it will not check the others.
 if(something || someotherthing)
 if(something | someotherthing)

if something is TRUE, || will not evaluate someotherthing, while | will do. If the variables in your if-statements are actually function calls, using || is possibly saving a lot of performance.

A: So just to build on the other answers with an example, short-circuiting is crucial in the following defensive checks:
if (foo == null || foo.isClosed()) {
    return;
}

if (bar != null && bar.isBlue()) {
    foo.doSomething();
}

Using | and & instead could result in a NullPointerException being thrown here.

A: Logical || and && check the right hand side only if necessary. The | and & check both the sides everytime.
For example:
int i = 12;
if (i == 10 & i < 9) // It will check if i == 10 and if i < 9
...

Rewrite it:
int i = 12;
if (i == 10 && i < 9) // It will check if i == 10 and stop checking afterward because i != 10
...

Another example:
int i = 12;
if (i == 12 | i > 10) // It will check if i == 12 and it will check if i > 10
...

Rewrite it:
int i = 12;
if (i == 12 || i > 10) // It will check if i == 12, it does, so it stops checking and executes what is in the if statement
...

A: If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand alone.
It's a matter of if you want to short-circuit the evaluation or not -- most of the time you want to.
A good way to illustrate the benefits of short-circuiting would be to consider the following example.
Boolean b = true;
if(b || foo.timeConsumingCall())
{
   //we entered without calling timeConsumingCall()
}

Another benefit, as Jeremy and Peter mentioned, for short-circuiting is the null reference check:
if(string != null && string.isEmpty())
{
    //we check for string being null before calling isEmpty()
}

more info

A: | is the binary or operator

|| is the logic or operator

A: The operators || and && are called conditional operators, while | and & are called bitwise operators. They serve different purposes.
Conditional operators works only with expressions that statically evaluate to boolean on both left- and right-hand sides.
Bitwise operators works with any numeric operands.
If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.

A: A side note: Java has |= but not an ||=
An example of when you must use || is when the first expression is a test to see if the second expression would blow up. e.g. Using a single | in hte following case could result in an NPE.
public static boolean isNotSet(String text) {
   return text == null || text.length() == 0;
}

A: 1).(expression1 | expression2), | operator will evaluate expression2 irrespective of whether the result of expression1 is true or false.
Example:
class Or
{
    public static void main(String[] args)
    {
        boolean b=true;

        if (b | test());
    }

    static boolean test()
    {
        System.out.println("No short circuit!");
        return false;
    }
}

2).(expression1 || expression2), || operator will not evaluate expression2 if expression1 is true.
Example:
class Or
{
    public static void main(String[] args)
    {
        boolean b=true;

        if (b || test())
        {
            System.out.println("short circuit!");
        }
    }

    static boolean test()
    {
        System.out.println("No short circuit!");
        return false;
    }
}

A: The other answers have done a good job of covering the functional difference between the operators, but the answers could apply to just about every single C-derived language in existence today. The question is tagged with java, and so I will endeavor to answer specifically and technically for the Java language.
& and | can be either Integer Bitwise Operators, or Boolean Logical Operators. The syntax for the Bitwise and Logical Operators (§15.22) is:
AndExpression:
  EqualityExpression
  AndExpression & EqualityExpression

ExclusiveOrExpression:
  AndExpression
  ExclusiveOrExpression ^ AndExpression

InclusiveOrExpression:
  ExclusiveOrExpression
  InclusiveOrExpression | ExclusiveOrExpression

The syntax for EqualityExpression is defined in §15.21, which requires RelationalExpression defined in §15.20, which in turn requires ShiftExpression and ReferenceType defined in §15.19 and §4.3, respectively. ShiftExpression requires AdditiveExpression defined in §15.18, which continues to drill down,  defining the basic arithmetic, unary operators, etc. ReferenceType drills down into all the various ways to represent a type. (While ReferenceType does not include the primitive types, the definition of primitive types is ultimately required, as they may be the dimension type for an array, which is a ReferenceType.)
The Bitwise and Logical Operators have the following properties:

*

*These operators have different precedence, with & having the highest precedence and | the lowest precedence.

*Each of these operators is syntactically left-associative (each groups left-to-right).

*Each operator is commutative if the operand expressions have no side effects.

*Each operator is associative.

*The bitwise and logical operators may be used to compare two operands of numeric type or two operands of type boolean. All other cases result in a compile-time error.

The distinction between whether the operator serves as a bitwise operator or a logical operator depends on whether the operands are "convertible to a primitive integral type" (§4.2) or if they are of types boolean or Boolean (§5.1.8).
If the operands are integral types, binary numeric promotion (§5.6.2) is performed on both operands, leaving them both as either longs or ints for the operation. The type of the operation will be the type of the (promoted) operands. At that point, & will be bitwise AND, ^ will be bitwise exclusive OR, and | will be bitwise inclusive OR. (§15.22.1)
If the operands are boolean or Boolean, the operands will be subject to unboxing conversion if necessary (§5.1.8), and the type of the operation will be boolean. & will result in true if both operands are true, ^ will result in true if both operands are different, and | will result in true if either operand is true. (§15.22.2)
In contrast, && is the "Conditional-And Operator" (§15.23) and || is the "Conditional-Or Operator" (§15.24). Their syntax is defined as:
ConditionalAndExpression:
  InclusiveOrExpression
  ConditionalAndExpression && InclusiveOrExpression

ConditionalOrExpression:
  ConditionalAndExpression
  ConditionalOrExpression || ConditionalAndExpression

&& is like &, except that it only evaluates the right operand if the left operand is true. || is like |, except that it only evaluates the right operand if the left operand is false.
Conditional-And has the following properties:

*

*The conditional-and operator is syntactically left-associative (it groups left-to-right).

*The conditional-and operator is fully associative with respect to both side effects and result value. That is, for any expressions a, b, and c, evaluation of the expression ((a) && (b)) && (c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a) && ((b) && (c)).

*Each operand of the conditional-and operator must be of type boolean or Boolean, or a compile-time error occurs.

*The type of a conditional-and expression is always boolean.

*At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8).

*If the resulting value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated.

*If the value of the left-hand operand is true, then the right-hand expression is evaluated; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8). The resulting value becomes the value of the conditional-and expression.

*Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

Conditional-Or has the following properties:

*

*The conditional-or operator is syntactically left-associative (it groups left-to-right).

*The conditional-or operator is fully associative with respect to both side effects and result value. That is, for any expressions a, b, and c, evaluation of the expression ((a) || (b)) || (c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a) || ((b) || (c)).

*Each operand of the conditional-or operator must be of type boolean or Boolean, or a compile-time error occurs.

*The type of a conditional-or expression is always boolean.

*At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8).

*If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.

*If the value of the left-hand operand is false, then the right-hand expression is evaluated; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8). The resulting value becomes the value of the conditional-or expression.

*Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

In short, as @JohnMeagher has repeatedly pointed out in the comments, & and | are, in fact, non-short-circuiting boolean operators in the specific case of the operands being either boolean or Boolean. With good practices (ie: no secondary effects), this is a minor difference. When the operands aren't booleans or Booleans, however, the operators behave very differently: bitwise and logical operations simply don't compare well at the high level of Java programming.

A: Also notice a common pitfall: The non lazy operators have precedence over the lazy ones, so:
boolean a, b, c;
a || b && c; //resolves to a || (b && c)
a | b && c; //resolves to (a | b) && c

Be careful when mixing them.

A: In addition to short-circuiting, another thing to keep in mind is that doing a bitwise logic operation on values that can be other than 0 or 1 has a very different meaning than conditional logic.  While it USUALLY is the same for | and ||, with & and && you get very different results (e.g. 2 & 4 is 0/false while 2 && 4 is 1/true).
If the thing you're getting from a function is actually an error code and you're testing for non-0-ness, this can matter quite a lot.
This isn't as much of an issue in Java where you have to explicitly typecast to boolean or compare with 0 or the like, but in other languages with similar syntax (C/C++ et al) it can be quite confusing.
Also, note that & and | can only apply to integer-type values, and not everything that can be equivalent to a boolean test.  Again, in non-Java languages, there are quite a few things that can be used as a boolean with an implicit != 0 comparison (pointers, floats, objects with an operator bool(), etc.) and bitwise operators are almost always nonsensical in those contexts.

A: The only time you would use | or & instead of || or && is when you have very simple boolean expressions and the cost of short cutting (i.e. a branch) is greater than the time you save by not evaluating the later expressions.
However, this is a micro-optimisation which rarely matters except in the most low level code.

A: || returns a boolean value by OR'ing two values (Thats why its known as a LOGICAL or)
IE:
if (A || B)

Would return true if either A or B is true, or false if they are both false.
| is an operator that performs a bitwise operation on two values. To better understand bitwise operations, you can read here:
http://en.wikipedia.org/wiki/Bitwise_operation

A: One main difference is that || and && exhibit "short-circuiting", so the RHS will only be evaluated if needed.
For e.g.
if (a || b) {
    path1...
} else {
    path2..
}

Above if a is true then b will not be tested and path1 is executed. If | was used then both sides would be evaluated even if 'a' is true.
See Here and here, for a little more information.
Hope this helps.

A: Non short-circuiting can be useful.  Sometimes you want to make sure that two expressions evaluate.  For example, say you have a method that removes an object from two separate lists.  You might want to do something like this:
class foo {

    ArrayList<Bar> list1 = new ArrayList<Bar>();
    ArrayList<Bar> list2 = new ArrayList<Bar>();

    //Returns true if bar is removed from both lists, otherwise false.
    boolean removeBar(Bar bar) {
        return (list1.remove(bar) & list2.remove(bar));
    }
}

If your method instead used the conditional operand, it would fail to remove the object from the second list if the first list returned false.
//Fails to execute the second remove if the first returns false.
boolean removeBar(Bar bar) {
    return (list1.remove(bar) && list2.remove(bar));
}

It's not amazingly useful, and (as with most programming tasks) you could achieve it with other means.  But it is a use case for bitwise operands.

A: The basic difference between them is that | first converts the values to binary then performs the bit wise or operation. Meanwhile, || does not convert the data into binary and just performs the or expression on it's original state.
int two = -2; int four = -4;
result = two | four; // bitwise OR example

System.out.println(Integer.toBinaryString(two));
System.out.println(Integer.toBinaryString(four));
System.out.println(Integer.toBinaryString(result));

Output:
11111111111111111111111111111110
11111111111111111111111111111100
11111111111111111111111111111110

Read more: http://javarevisited.blogspot.com/2015/01/difference-between-bitwsie-and-logical.html#ixzz45PCxdQhk

A: When I had this question I created test code to get an idea about this.
public class HelloWorld{

   public static boolean bool(){
      System.out.println("Bool");
      return true;
   }

   public static void main(String []args){

     boolean a = true;
     boolean b = false;

     if(a||bool())
     {
        System.out.println("If condition executed");
     }
     else{
         System.out.println("Else condition executed");
     }

 }
}

In this case, we only change left side value of if condition adding a or b.

|| Scenario , when left side true [if(a||bool())]

output "If condition executed"

|| Scenario , when left side false [if(b||bool())]

Output-
Bool
If condition executed

Conclusion of || When use ||, right side only check when the left side is false.

| Scenario , when left side true [if(a|bool())]

Output-
Bool
If condition executed

| Scenario , when left side false [if(b|bool())]

Output-
Bool
If condition executed

Conclusion of | When use |, check both left and right side.

A: | = bitwise or, || = logic or

A: usually I use when there is pre increment and post increment operator. Look at the following code:
package ocjpPractice;
/**
 * @author tithik
 *
 */
public class Ex1 {

    public static void main(String[] args) {
    int i=10;
    int j=9;
    int x=10;
    int y=9;
    if(i==10 | ++i>j){
        System.out.println("it will print in first if");
        System.out.println("i is: "+i);
    }

    if(x==10 ||++x>y){
        System.out.println("it will print in second if");
        System.out.println("x is: "+x);
    }
    }
}

output:

it will print in first if
  i is: 11
  it will print in second if
  x is: 10

both if blocks are same but result is different.
when there is |, both the conditions will be evaluated. But if it is ||, it will not evaluate second condition as the first condition is already true.

A: There are many use cases suggesting why should you go for || rather than | . Some use cases have to use | operator to check all the conditions.
For example, if you want to check form validation and you want to show the user all the invalid fields with error texts rather than just a first invalid field.
|| operator would be,
   if(checkIfEmpty(nameField) || checkIfEmpty(phoneField) || checkIfEmpty(emailField)) {
      // invalid form with one or more empty fields
   }

   private boolean checkIfEmpty(Widget field) {
      if(field.isEmpty()) {
        field.setErrorMessage("Should not be empty!");
        return true;
      }
      return false;
   }

So with above snippet, if user submits the form with ALL empty fields, ONLY nameField would be shown with error message. But, if you change it to,
   if(checkIfEmpty(nameField) | checkIfEmpty(phoneField) | checkIfEmpty(emailField)) {
      // invalid form with one or more empty fields
   }

It will show proper error message on the each field irrespective of true conditions.

A: After carefully reading this topic is still unclear to me if using | as a logical operator is conform to Java pattern practices.
I recently modified code in a pull request addressing a comment where
if(function1() | function2()){
  ...
}

had to be changed to
boolean isChanged = function1();
isChanged |= function2();
if (isChanged){
  ...
}

What is the actual accepted version?

Java documentation is not mentioning | as a logical non-shortcircuiting OR operator.

Not interested in a vote but more in finding out the standard?!
Both code versions are compiling and working as expected.

A: | is a bitwise operator. || is a logical operator.
One will take two bits and or them.
One will determine truth (this OR that) If this is true or that is true, then the answer is true.
Oh, and dang people answer these questions fast.

A: || is a logical or and | is a bit-wise or.

A: Java operators
| is bitwise or, || is logical or.

A: Take a look at:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html
| is bitwise inclusive OR
|| is logical OR


text:
Q: How to sum 2-dimensional arrays I have a two-dimensional array with sub-arrays of equal size, for example:
array = [
  [10, 12, 15 ,17], [16, 32, 65, 47], [45, 48, 41, 23],
  [36, 25, 74, 98], [32, 19, 66, 88]
]

I would like to create a new array by summing the corresponding elements of every 4th sub-array, i.e. the elements that are "on top of each other" in the above example:
new_array = [
  [10 + 36, 12 + 25, 15 + 74, 17 + 98],
  [16 + 32, 32 + 19, 65 + 66, 47 + 88],
  [45, 48, 41, 23]
]

These are just examples, the actual arrays can be larger.

A: Complete Matrix
You can use each_slice, transpose, map and transpose again to navigate your matrix.
The code first uses join('+') to show what is being calculated :
array= [[10,12,15,17],[16,32,65,47],[45,48,41,23],[36,25,74,98],[32,19,66,88],[1,2,3,4]]

array.each_slice(3).to_a.transpose.map{|r| r.transpose.map{|x| x.join('+')}}
# => [["10+36", "12+25", "15+74", "17+98"], ["16+32", "32+19", "65+66", "47+88"], ["45+1", "48+2", "41+3", "23+4"]]

array.each_slice(3).to_a.transpose.map{|r| r.transpose.map{|x| x.inject(:+)}}
# => [[46, 37, 89, 115], [48, 51, 131, 135], [46, 50, 44, 27]]

Warning!
You need to carefully select the each_slice parameter to suit your original array. transpose might raise an exception otherwise :
array = [[10,12,15,17],[19,32,65,47],[45,48,41,23],[36,25,74,98],[10,12,15,17],[16,98,65,47],[69,48,65,23],[66,25,74,98]]
array.each_slice(3).to_a.transpose.map{|r| r.transpose.map{|x| x.inject(:+)}}
#=> IndexError: element size differs (2 should be 3)
array.each_slice(4).to_a.transpose.map{|r| r.transpose.map{|x| x.inject(:+)}}
#=> [[20, 24, 30, 34], [35, 130, 130, 94], [114, 96, 106, 46], [102, 50, 148, 196]]

Incomplete Matrix
If the matrix size isn't a multiple of width :
array = [
  [10, 12, 15 ,17], [16, 32, 65, 47], [45, 48, 41, 23],
  [36, 25, 74, 98], [32, 19, 66, 88]
]

you could add subarrays full of 0s to get :
matrix = [
  [10, 12, 15 ,17], [16, 32, 65, 47], [45, 48, 41, 23],
  [36, 25, 74, 98], [32, 19, 66, 88], [ 0,  0,  0,  0]
]

Array#fill does the job :
def maxtrix_column_sums(array, width)
  size    = array.size
  size2   = array.first.size
  missing = (-size) % width
  matrix  = array.dup.fill(Array.new(size2, 0), size...size + missing)
  matrix.each_slice(width).to_a.transpose.map { |r| r.transpose.map { |x| x.join('+') } }
end

p maxtrix_column_sums(array, 3)
#=> [["10+36", "12+25", "15+74", "17+98"], ["16+32", "32+19", "65+66", "47+88"], ["45+0", "48+0", "41+0", "23+0"]]

A: Here's a variation of Eric Duminil's answer using zip instead of transpose to account for an "odd" number of sub-arrays:
first, *rest = array.each_slice(3).to_a
first.zip(*rest).map { |r| r.compact.transpose.map { |x| x.inject(:+) } }
#=> [[46, 37, 89, 115], [48, 51, 131, 135], [45, 48, 41, 23]]

How it works:
each_slice separates the array into groups of 3:
array.each_slice(3).to_a
#=> [
#     [[10, 12, 15, 17], [16, 32, 65, 47], [45, 48, 41, 23]],
#     [[36, 25, 74, 98], [32, 19, 66, 88]]
#   ]

first.zip(*rest) combines the first slice "column"-wise with the remaining slices, adding nil when a slice is missing:
first.zip(*rest)
#=> [
#     [[10, 12, 15, 17], [36, 25, 74, 98]],
#     [[16, 32, 65, 47], [32, 19, 66, 88]],
#     [[45, 48, 41, 23], nil]
#   ]

The map / compact / transpose part then restructures the sub-array while getting rid of nil values:
first.zip(*rest).map { |r| r.compact.transpose }
#=> [
#     [[10, 36], [12, 25], [15, 74], [17, 98]],
#     [[16, 32], [32, 19], [65, 66], [47, 88]],
#     [[45],     [48],     [41],     [23]]
#   ]

And inject(:+) finally sums the inner elements.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implement C-Style callback functions using swift? I found an example for IOKit:
var notification:io_object_t

let matching:NSDictionary = IOServiceNameMatching("IODisplayWrangler").takeRetainedValue()
let displayWrangler = IOServiceGetMatchingService(kIOMasterPortDefault, matching)
let notificationPort = IONotificationPortCreate(kIOMasterPortDefault)
    IOServiceAddInterestNotification(notificationPort, displayWrangler, kIOGeneralInterest, displayPowerNotificationsCallback, nil, &notification)

CFRunLoopAddSource (CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode);
   IOObjectRelease (displayWrangler);

The above example is clear to me - so far. But IOServiceAddInteresNotification wants a callback function. In  it's simple to do this, by implementing the C-Style function somewhere in the .m-file.
The documentation says that I have to use a callback of type IOServiceInterestCallback.
In C-Style it is defined as follows:
typedef void ( *IOServiceInterestCallback)( void *refcon, io_service_t service, uint32_t messageType, void *messageArgument );

And on objC everything seems to work out perfectly.
What is the equivalent solution in swift? How do I declare the callback function without creating a C or objC file for this?
Any ideas?
Cheers,
Jack

A: You cannot create C function like callbacks in Swift as closures are not compatible with CFunctionPointer. You can implement some workaround in Objective-C or C. Example is describe in Objective-C Wrapper for CFunctionPointer to a Swift Closure


text:
Q: Change the height of option tag from select I have the next component:

 <Select
        mode="multiple"
        placeholder="Inserted are removed"
        value={selectedItems}
        onChange={this.handleChange}
        style={{ width: "100%" }}
      >
        {filteredOptions.map(item => (
          <Select.Option key={item} value={item}>
            {item}
          </Select.Option>
        ))}
 </Select>

In my demo: https://codesandbox.io/s/hide-already-selected-ant-design-demo-39xfe?file=/index.js:542-889, i added some styles:

.ant-select-item-option-content {
  background-color: red;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
  height: auto;
}

Why  height:10px; does not work? And how to apply 10px of heigth for that selector?

A: You should remove height:auto:
.ant-select-item-option-content {
  background-color: red;
  height: 5px;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
}

Or perhaps you need something like this:
.ant-select-item-option-content {
  background-color: red;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
  height: auto;
}

.ant-select-item-option-active:not(.ant-select-item-option-disabled) .ant-select-item-option-content {
  background-color: blue;
}

A: I checked your link. It seems like there is another style rule thats applying a min-height:32px; to the active element.
Either remove that or include min-height in your CSS like so:
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  min-height: 10px;
  height: 10px;
  background-color: blue;
}


text:
Q: Creating 0 entries for missing values in a date sequence for a unique set of columns in Excel I have been struggling to fix a database that contains market size information. Because it is internal data I can't share the original file. The original file is just the example but much much bigger.
Right now I do not even know what tool to use, or even what function I could use. Sorry if maybe SE is not the appropriate place to be asking this because it is more about codding, but any general guidance helps a bunch! Thank you so much!
Description of data:
I have a worksheet containing the market size of certain products per month for multiple countries. Example(Row 2): In January 2018(Column B) the market size of Albania for apples was 100kg. The data contains information from 2018 to 2019, and multiple countries and products.
The objective:
Have a complete file of market shares for all periods, products and dates.
The problem: Sometimes dates are skipped.
In the example, the market size for Honduras between February(02) and May (04) of 2018 are missing. The entries do not exist in the original file, but that does not mean that the market size does not exist. Instead, it means that the market size for that period, for that particular product, for that particular country, was 0.
The solution I am trying for:
Create market size entries equal to 0 for these missing periods.
What I have tried:
My first attempt was to fix this in Tableau by trying to input 0s in the missing fields, but then I realized that Tableau is not ideal for this job, and also I realized that the problem is not that the entries are NA, but instead that there are no entries. Tableau example
So I moved on to Excel, where I have tried to first identify the places in which there is missing information.
Basic missing identifier Now I know where the missing data is, but I have no clue how to create the entries based on whether column E is equal to "missing" or not.
Finally I realized I should try to use R because there are over 400,000 entries and every calculation I make on Excel takes ages unless the software crashes first. However, I am not sure even how to begin to solve this with R.
Thanks in advance for any help! If anyone can tell me first what tool to use and maybe some functions that can create entries for missing values in a sequence, I would already have something to start with.
If you think my approach is completely off then let me know that as well.
Example of data:
Country Date Product MarketSize
Honduras 201801 apples 100
Honduras 201802 apples 500
Honduras 201806 apples 900
Honduras 201808 apples 1000
Honduras 201809 apples 300
Thailand 201905 pencils 100
Thailand 201906 pencils 0
Example of desired result:
Country Date Product MarketSize
Honduras 201801 apples  100
Honduras 201802 apples  500
Honduras 201803 apples  0
Honduras 201804 apples  0
Honduras 201805 apples  0
Honduras 201806 apples  900
Honduras 201808 apples  1000
Honduras 201809 apples  300
Honduras 201810 apples  0
Honduras 201811 apples  0
Honduras 201812 apples  0
Honduras 201901 apples  0
Honduras 201902 apples  0
Honduras 201903 apples  0
Honduras 201904 apples  0
Honduras 201905 apples  0
Honduras 201906 apples  0
Honduras 201907 apples  0
Honduras 201908 apples  0
Honduras 201909 apples  0
Honduras 201910 apples  0
Thailand 201801 pencils 0
Thailand 201802 pencils 0
Thailand 201803 pencils 0
Thailand 201804 pencils 0
Thailand 201805 pencils 0
Thailand 201806 pencils 0
Thailand 201807 pencils 0
Thailand 201808 pencils 0
Thailand 201809 pencils 0
Thailand 201810 pencils 0
Thailand 201811 pencils 0
Thailand 201812 pencils 0
Thailand 201901 pencils 0
Thailand 201902 pencils 0
Thailand 201903 pencils 0
Thailand 201904 pencils 0
Thailand 201905 pencils 100
Thailand 201906 pencils 0
Thailand 201907 pencils 0
Thailand 201908 pencils 0
Thailand 201909 pencils 0
Thailand 201910 pencils 0

A: You are not looking to sum up related items, simply to fill in the blanks, so to speak?
Excel is fine for this, except for the slowness you report. I cannot address R as I do not use it, but I would think something very similar to the Excel fix would be easily done.
Excel fix:  in an empty column, like the one just to the right of the one with the missing entries (call that column E because the data takes up the first four columns), put a formula like the following into the top cell, then fill down with it (use Fill, copy and paste, whatever you like best) to the end of the column:
=IF( D1=0, 0, D1 )

Excel, you see, already considers the blank cells to be 0 so blank cells will result in the formula putting a 0 in that cell in column E. If not blank, whatever it has already will be the result.
Then copy that column of cells and Paste|Special|Values in column D, the source data column. Now you have an actual value in EVERY cell in that column.
Then delete the spare column ("helper column") and you're all set.
R should certainly have some similar functionality, so you would just be adapting the typing of the formula to fit R's nomenclature.


text:
Q: How to get the corresponding json data in different { } and [ ] (using Python)? I am trying to use Python Flask to process JSON data.
Here is what my data looks like:
[
    {   'className': 'BoardGame',
        'fields': {
            'objectId': {'type': 'String'},
            'playerName': {'type': 'String'},
            'cheatMode': {'type': 'Boolean'},
            'score': {'type': 'Number'},
            'updatedAt': {'type': 'Date'},
            'createdAt': {'type': 'Date'}
        },
        'classLevelPermissions': {
            'addField': {'*': True},
            'create': {'*': True}, 'get': {'*': True},
            'update': {'*': True}, 'find': {'*': True},
            'delete': {'*': True}
        }
    },
    {   'className': 'RPGGAme',
        'fields': {
            'objectId': {'type': 'String'},
            'GameId': {'type': 'String'},
            'robotName': {'type': 'String'},
            'updatedAt': {'type': 'Date'},
            'createdAt': {'type': 'Date'}
        },
        'classLevelPermissions': {
            'addField': {'*': True},
            'create': {'*': True}, 'get': {'*': True},
            'fields': {'*': True}, 'find': {'*': True},
            'delete': {'*': True}
        }
    }
]

The problem is that I cannot get the corresponding data due to the complex format of [] and {}
Here is what I want:
[0]["className"]: "BoardGame" <---String
[0]["fields"]: ["objectId","playerName","cheatMode"....] <-- List Of String
[1]["className"]: "RPGGame"    <---String
[1]["fields"]: ["objectId","GameId",....]   <-- List Of String

Thus I tried the code here:
def findkeys(node, kv):
    if isinstance(node, list):
        for i in node:
            for x in findkeys(i, kv):
                yield x
    elif isinstance(node, dict):
        if kv in node:
            yield node[kv]
        for j in node.values():
            for x in findkeys(j, kv):
                yield x

However, it can only find the special key's value, but cannot set the range (what I mean by range is that the first "{}" as array 0 + the second "{}" as array 1+ the "fields" in classLevelPermissions won't be involved in the result, in some sense I guess is the depth level ). I still cannot resolve the problem and get what I want.
How can I set the depth and put to corresponding array e.g. [0],[1]?

A: data = [
    {   'className': 'BoardGame',
        'fields': {
            'objectId': {'type': 'String'},
            'playerName': {'type': 'String'},
            'cheatMode': {'type': 'Boolean'},
            'score': {'type': 'Number'},
            'updatedAt': {'type': 'Date'},
            'createdAt': {'type': 'Date'}
        },
        'classLevelPermissions': {
            'addField': {'*': True},
            'create': {'*': True}, 'get': {'*': True},
            'update': {'*': True}, 'find': {'*': True},
            'delete': {'*': True}
        }
    },
    {   'className': 'RPGGAme',
        'fields': {
            'objectId': {'type': 'String'},
            'GameId': {'type': 'String'},
            'robotName': {'type': 'String'},
            'updatedAt': {'type': 'Date'},
            'createdAt': {'type': 'Date'}
        },
        'classLevelPermissions': {
            'addField': {'*': True},
            'create': {'*': True}, 'get': {'*': True},
            'fields': {'*': True}, 'find': {'*': True},
            'delete': {'*': True}
        }
    }
]

Try this:
oput = {}
for idx, dict in enumerate(data):
    oput[idx] = {}
    oput[idx]["className"] = dict["className"]
    oput[idx]["fields"] = dict["fields"].keys()

then:
oput[0]["className"]
>> 'BoardGame'

oput[0]["fields"]
>>  ['objectId', 'playerName', 'cheatMode', 'score', 'updatedAt', 'createdAt']

oput[1]["className"]
>> 'RPGGAme'

oput[1]["fields"]
>> ['robotName', 'GameId', 'createdAt', 'objectId', 'updatedAt']


text:
Q: Common Lisp: How to get (in-package ...) to work from within Emacs Slime 64-bit Windows 7
Clozure Common Lisp Version 1.9 WindowsX8632
Emacs 24.3.1
Slime changelog date 2014-06-17
I have an example .lisp file which starts out as follows:
(ql:quickload 'qt)
(in-package "QT")

The rest of the program shows a dialog box.
When I run this from the command line, wx86cl -load helloqt.lisp it seems to work fine.
When I run this from Emacs Slime (C-x C-k) it says there is no package "QT".
However if I first evaluate the first line individually (C-x C-e) then I can compile the whole thing and it works, modulo the normal issues of trying to run a QT thread from within Slime on Windows.
How do I make it so I can compile/run the file from emacs without having to manually evaluate the first line first?
Also, why doesn't (in-package ...) change the current package in the Slime session?  I have to change it manually if I want to interact with the package contents.

A: When you compile the file as a whole, it is first read as a whole.  At that time, none of it has yet been evaluated, so the package QT is not defined yet.
You can either use eval-when to evaluate something at an earlier time, or use a system definition facility (ASDF is predominant nowadays) to load your system in the right order.
Eval-when:
(eval-when (:compile-toplevel :load-toplevel :execute)
  (ql:quickload '#:qt))

(in-package #:qt)

Note that you usually should not muck around in library packages but define your own, fresh package to hold your code:
(eval-when (:compile-toplevel :load-toplevel :execute)
  (ql:quickload '#:qt))

(defpackage #:qt-example
  (:use #:qt))

(in-package #:qt-example)

;; your code here

(In case you are wondering, defpackage, defun, defclass etc. are specially designed macros that expand to a form inside such an eval-when.)
This is sometimes OK for little one-off scripts.  For systems of any noteworthy size, especially as soon as they have more than one source file, use ASDF:
;;;; qt-example.asd

(in-package #:cl-user)

(asdf:defsystem #:qt-experiments
  :description "Some experiments with QT."
  :serial t
  :components ((:file "package")
               (:file "qt-example"))
  :depends-on (#:qt))

;;;; package.lisp

(defpackage #:qt-example
  (:use #:qt))

;;;; qt-example.lisp

(in-package #:qt-example)

ASDF comes with most open-source Common Lisp implementations.  You might need to set up the ASDF registry.  I like to have one or two base directories for all my local projects, so that I can just put the following into ~/.config/common-lisp/source-registry.conf:
(:source-registry
  (:tree (:home "devel"))
  (:tree (:home "src"))
  :inherit-configuration)

Then ASDF finds all systems defined below those directories.  In SLIME, you can just use ,load-system or ,open-system from the REPL with the system name to load it, resp. open all files in it, optionally loading it.
When compiling a single toplevel form (using C-c C-c) from a file, SLIME looks backward from there for an in-package form to find out what package it should assume.  Conventionally, you should only have a single in-package form per file, at its top.
A commonly useful shortcut is C-c ~ in Lisp source files, which switches the REPL to the directory of the file and the effective package at point.

A: A little hard to find, but there is slime-repl-set-package:
(defun slime-connected-hook-switch-to-stumpwm-package ()
  (slime-repl-set-package "STUMPWM"))

(add-hook #'slime-editing-mode-hook
          #'slime-connected-hook-switch-to-stumpwm-package)


text:
Q: What does the Borel $\sigma$-algebra of $\mathbb{R}$ look like? The definition for a Borel $\sigma$-algebra is hard for me to grasp. I understand that it can be thought of as the "smallest" $\sigma$-algebra of some set from this post.
For concreteness, if we take the example of a Borel $\sigma$-algebra on $(0,1]$, what does it look like? More generally, what does $\mathbf{B}(\mathbb{R})$ look like?
A picture or image would be appreciated.

A: This is a very large set. In what follows, I'm basically going to quote a discussion that can be found in the Notes and References Section of Folland's real analysis book (Section 1.6)
Start with some subsets, $\mathcal{E}$ of $\mathbb{R}$. Then proceed inductively. Let $\mathcal{E}_1 = \mathcal{E} \cup \{E^c : E \in \mathcal{E}\}$. Keep going by taking compliements and "unioning" it with the original set. Do this "more than countably infinite times." The result is:

$\sigma(\mathcal{E})  = \cup_{\alpha \in \Omega}\mathcal{E}_{\alpha}$ where $\Omega$ is the set of countable ordinals

(Prop 1.23 in my edition of the source quoted above)

Just to add to my note, I think the reason we work with sigma algebra in the way you mention in your post is to avoid dealing with this "transfinite induction." The non-constructive definition is often easier (conceptually) to work with.


text:
Q: Why do I go to the top of the page when I open my fixed navigation menu? I have a fixed side navigation menu that has a height of 100%. When you click the hamburger in the corner its width gets set to 15%-100% depending on your window's size. And when you click the x its width is set to 0. The percentage is set relative to the body. This seemed to be working great until I added content so that I could scroll. When you scroll down and then open/close the side nav it brings you back to the top of the page.
I'm not very familiar with JavaScript so it is possible there is a problem in there. I searched Google and StackOverflow but I didn't find anything. It's possible I might not be searching for the right problem. I tried changing all of the percentages to vh and vw and that changed nothing. I also don't believe it is a browser problem (I use Chrome) because I tried it in Microsoft Edge as well and that produced the same results.

         /*an Icon font I have downloaded*/

      ×
      Home
      Portfolio
      Blog

    //side-menu script
    var sideMenuWidth;
    var sideMenuIsActive = true;
    window.onload = function() {
      if (window.innerWidth > 1143) {
        sideMenuWidth = '15%';
      }else{
        sideMenuWidth = '100%';
      }
    }
    function openSlideMenu () {
      document.getElementById('side-menu').style.width = sideMenuWidth;
        sideMenuIsActive = true;
    }
    function windowResize() {
      if (window.innerWidth > 1143) {
        sideMenuWidth = '15%';
        if (sideMenuIsActive == true) {
          document.getElementById('side-menu').style.width = sideMenuWidth;
        }
      }else{
        sideMenuWidth = '100%';
        if (sideMenuIsActive == true) {
        document.getElementById('side-menu').style.width = sideMenuWidth;
        }
      }
    }
    function closeSlideMenu() {
      document.getElementById('side-menu').style.width = '0';
      sideMenuIsActive = false;
    }
  //end of side-menu script

#side-menu {
  width:15%;
  z-index: 1;
  transition: 0.5s;
  top:0;
  left:0;
  background-color: black;
  height: 100%;
  position: fixed;
}

#hamburger {
  display: absolute;
  top: 0;
  left:0;
  margin: 1rem 0 0 1rem;
  position: fixed;
  color: black;
}

Any help is greatly appreciated!

A: You need to prevent default behaviour for link with attr href="#" or remove href
https://www.w3schools.com/jsref/event_preventdefault.asp

A: If you need interactive element, but don't need href attribute use <button> element instead and apply needed CSS for this element. This is better option from accessibility concern.


text: Q: easiest way to host your node ftp server I have been using heroku for my node js servers. This time I created an ftp server using ftp-srv npm package. However I have no idea how to host it. If I try to deploy it to heroku again, it provides me with an https url. I need to use ftp protocol, so need a url with ftp://. What could I do to deploy my server?


text:
Q: MySQL Trigger Question I have a mysql table called books that has a "votes" column, and another table called series which has a "total_votes" column.  The votes column tracks votes for an individual book, while the total_votes column is a tabulation of all votes for all books within a series.
In the administration section, an admin can manually change the number of votes an individual book has.  I want to create a mysql trigger so that whenever a vote is changed, the difference between old vote value and new vote value is reflected in the total_votes column.  For example, if Book A has 10 votes and Series 1 has a total of 100 votes, when I change the vote count of Book A to 5, I want the total_vote count of Seris 1 to be 95.
I understand how to make a basic trigger, but I'm not sure how update the Series table with the difference between the old and new vote values.
TIA.

A: Don't worry about the difference, just update based on a new sum.  For example:
(Not sure if this is the exact MySql syntax)
update series
set total_votes = sum(select votes from books b where b.seriesid = seriesid)


text:
Q: SQL Server: exclude records whose name column matches values in a 2nd exclusions table In SQL Server, I have a table that contains names of doctor's offices (Providers) that I want to return a list of.  If any of these office names contain any keywords found in a 2nd table (Keywords), I want to exclude that Provider record from being returned in the list.  I have a query that works fine, however my problem is...
I need to match WHOLE words in the Provider's name to the keyword, in order to exclude it.  If a keyword is merely a portion of a word contained in the doctor's office name, that record shouldn't be excluded. I'm not sure how to do this.
Here's an example:
IF OBJECT_ID(N'tempdb..#Keywords') IS NOT NULL
BEGIN
     DROP TABLE #Keywords
END
GO

IF OBJECT_ID(N'tempdb..#Providers') IS NOT NULL
BEGIN
    DROP TABLE #Providers
END
GO

CREATE TABLE #Keywords (KeywordId INT, Keyword varchar(50))
CREATE TABLE #Providers (ProviderId INT, ProviderName varchar(100))

INSERT INTO #Keywords(KeywordId, Keyword) VALUES (1, 'ACUPUNCTURE')
INSERT INTO #Keywords(KeywordId, Keyword) VALUES (2, 'CHILD & ADOLESCENT PSYCHIATRY')
INSERT INTO #Keywords(KeywordId, Keyword) VALUES (3, 'Ent')
INSERT INTO #Keywords(KeywordId, Keyword) VALUES (4, 'VA')

INSERT INTO #Providers(ProviderId, ProviderName) VALUES (111,'Family Practice of Pennsylvania')
INSERT INTO #Providers(ProviderId, ProviderName) VALUES (222,'Dr. Smiths Acupuncture')
INSERT INTO #Providers(ProviderId, ProviderName) VALUES (333,'Patient First')
INSERT INTO #Providers(ProviderId, ProviderName) VALUES (444,'Chicago Child & Adolescent Psychiatry')
INSERT INTO #Providers(ProviderId, ProviderName) VALUES (555,'Manhattan Family Practice')
INSERT INTO #Providers(ProviderId, ProviderName) VALUES (666,'Dr. Levys Oncology VA')

SELECT * FROM #Keywords
select * FROM #Providers

SELECT p.*
FROM #Providers p
WHERE NOT EXISTS (SELECT 1
                   FROM   #Keywords k
                   WHERE  p.ProviderName LIKE CONCAT('%', k.Keyword, '%'))

In the above sql, any provider's offices that contain any of those 4 values in the #Keywords table, should be excluded.  Therefore, since ProviderId's 222, 444 & 666 have matching keywords, they should be excluded and I should return the following 3 records:

*

*111, Family Practice of Pennsylvania

*333, Patient First

*555, Manhattan Family Practice

My problem however, if you run that above script, you'll notice only ONE record is returned.  This is because ProviderId 111 contains "VA" in "Pennsylvania" and ProviderId 333 contains "ENT" in "Patient".
How can I re-work my query to ensure my keywords match a WHOLE word from a Provider's office name rather than just a portion of one?

A: You need to compare whole words only - so keywords like 'Ent' aren't matched within a word.
Does the following work for you by including a space either-side of the keyword and the same with the name:
where not exists (
  select 1 from #Keywords k
  where Concat(' ',p.ProviderName,' ') like Concat('% ', k.Keyword, ' %')
)

Example Fiddle


text:
Q: Script that verify a whitelist of domains I have easy question. I need to verify a string and validate a whitelist domain like this:
$WList = array('mega.co.nz','mediafire.com','putlocker.com','');
$Dominio = str_replace("www.","",parse_url($EnlaceUrl,PHP_URL_HOST));
if(in_array($Dominio,$WList)){//ok}

but this method doesnt retieve me domains like:
www42.zippyshare.com,www51.zippyshare.com,www71.zippyshare.com,www23.zippyshare.com

how resolve this problem? :)

A: Try this which removes all that begin with www until the first dot (inclusive):
$Dominio = preg_replace('~^www[^.]*\.~', '', parse_url($EnlaceUrl,PHP_URL_HOST));

A: You can use this:
if (preg_match('/[\w\d-]+\.(\w{3,4}|(\w{2,3}\.\w{2}))$/', $Dominio, $match))
    $Dominio = $match[1];

It will convert anything.domainname.suffix into domainname.suffix so you can test against your list.

A: Yet another preg_match example :
if(preg_match("/(?:([^.]+).)?([^.]+).([^\\/]+)/", $Dominio, $m)) {
    $Dominio = $m[2] . '.' $m[3];
}


text:
Q: Using MATLAB to analyse freefall. A ball is thrown up into the air at an initial speed v of $30$ $m /s  $. Assume the acceleration due to friction against the air is directed opposite to the direction of the velocity, and proportional to the speed of the ball, such that the total acceleration of the ball is $ a = -g - kv$, where $g$ is the acceleration due to gravity and $v$ is the speed of the ball. How long does it take for the ball to reverse its motion? Take $ k = 0.1$ and solve the problem using a while loop.
So I wrote the following algorithm in order to solve this problem in MATLAB. I defined a function $T$ that takes the variables $v, k, dt$ as arguments and returns the time $T$ until the ball reverses motion; with the help of the while loop as described below:
MATLAB
function T = freefallX(v,k,dt); %defining the function
time = 0;                       %the start time
k = 0.1;                        %some constant of proportionality
dt = 0.01;                      %fixed time step
v = 30;                         %initial velocity of the ball
while v >= 0                    %defining the while-condition
    a = -9.81 -(k*v);           %net acceleration of ball
    dv = a*(dt);                %velocity steps
    v = v + dv;                 %velocity of ball at any instant
    time = time + (dt);         %increase time in steps of dt
end
T = time                        %give the time until reversal of motion, i.e, v=0

My Problem
The result I get from the above algorithm is dependent on the choice of the time-step "$dt$". For different time-steps I get different values of $T$. Now I wanted to see how these different $T$'s vary with time-step. To this end, I tried to plot a graph of the different $T$'s against the corresponding $dt$. All attempts were in vain. How can I go about achieving this?

A: Something like this should work:
Ts=zeros(6,1);
dts=10.^[-6 -5 -4 -3 -2 -1];
for i=1:6
  Ts(i)=freefallX(30,0.1,dts(i));
end
plot(dts,Ts).

This computes $T$ for $dt=10^{-6},10^{-5},\dots,10^{-1}$. Note that if you're going to take $v$ and $k$ as arguments to the function "freefall" then you don't need to define them within the body of the function, they get defined in the outer scope.

A: Once you have your function defined, you can store different values of the function for different values of $dt$.  For instance, let's say you've already defined your function, and have values of $v$ and $k$ stored.  Let's say you also want to vary $dt$ from $.01$ to $.1$ in increments of $.01$.  Then you can do:
dt = .01:.01:.1;
T = zeros(size(dt));

for ii = 1:length(dt)
  T(ii) = freefallX(v,k,dt(ii));
end

plot(dt,T);

EDIT: Change your function to:
function T = freefallX(v,k,dt); %defining the function
time = 0;                     %the start time
% DELETE THIS k = 0.1;        %some constant of proportionality
% DELETE THIS dt = 0.01;      %fixed time step
% DELETE THIS v = 30;         %initial velocity of the ball
while v >= 0                  %defining the while-condition
  a = -9.81 -(k*v);           %net acceleration of ball
  dv = a*(dt);                %velocity steps
  v = v + dv;                 %velocity of ball at any instant
  time = time + (dt);         %increase time in steps of dt
end

T = time                        %give the time until reversal of motion, i.e, v=0

With those three lines, you're overwriting the user-input values of $v$, $k$ and $dt$, so you need to delete them.


text:
Q: maven javadoc plugin: package doesn't exist when an external JAR is used Not sure why Maven Javadoc Plugin reports:
[ERROR] /project/src/main/a/b/SomeClass.java:3: error: package com.x does not exist
[ERROR] import com.x.y;

The plugin related part in pom.xml
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <sourcepath>${project.basedir}/src/main/java</sourcepath>
                    <excludePackageNames>com.x.*</excludePackageNames>
                    <dependencySourceExcludes>com.x.*</dependencySourceExcludes>
                </configuration>
            </plugin>

As can be seen from the above code I tried to include the project sources that I want to be processed by JavaDoc in <sourcepath> and exclude the problematic package
The problem may be caused by the fact that package com.x.y is contained within an external jar which is added to the project in the following configuration:
           <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.3</version>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <configuration>
                            <tasks>
                                <echo>Unpack JAR archive with JNI interface</echo>
                                <unjar src="${project.basedir}/x/lib63.jar" dest="${project.build.directory}/classes">
                                    <patternset>
                                        <include name="**/*.class"/>
                                    </patternset>
                                </unjar>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

How to ignore those import errors?
I don't use the plugin on daily basis so I may not understand all the nuances.
But I don't understand why it even tries to analyze the imports. Shouldn't it just analyze my sources and create html files based on javadoc comments?
P.S. Without javadoc plugin the build is successful


text:
Q: What does adding Name and Namespace to DataContract do? I tried calling a WebInvoke method called Register which returns takes in a User object and immediately just returns that object.  It looks like the following:
User Register(User user)
{
    return user;
}

I am not sure what the Name and Namespace attributes do to the DataContract attribute when calling http://localhost:8081/user/register for example?
The reason I ask is because I initially had my class decorated with the DataContract attribute like this:
[DataContract]
public class User
{
   // Properties
}

When I opened up Fiddler, and sent a Post request, it said method not allowed, but when I changed DataContract to:
[DataContract(Name="User", Namespace="")]

It worked.

A: These properties control the namespace and name of the element in the WSDL. The important part in your code is the Namespace="": this will override the default namespace (http://tempuri.org) and set its value to an empty URL.
In the end, the User class will be renamed in the WSDL from http://tempuri.org/User to simply User.

A: In additional to the other answers, the Namespace in a DataContract allows for two objects of the same name in different namespaces - i.e. versioning.
These two objects are allowed to exist as different properties in a WSDL and will be known deserializable types provided they have different namespaces:
[DataContract(Namespace = "http://myservice/v1/thing")]
V1.Thing

[DataContract(Namespace = "http://myservice/v2/thing")]
V2.Thing

Of course, they need to exist in your C# code as well for it to be valid.  Or, alternatively you can change the name that the objects are known by using the Name attribute for clarity.
[DataContract(Name = "Thing")]
V1.Thing

[DataContract(Name= = "newThing")]
V2.Thing

You might use this when the class' name has changed in your project, but you need to support existing clients that use the 'old' names.
In summary, the Name and Namespace properties control how your objects will be serialized and deserialized when transmitted over the wire.  When you set them, you are controlling how the client will see your data contract.

A: Johann's answer, IMO is the correct one.
It works this way because when you send SOAP messages, the elements need to be namespace qualified, otherwise the WCF doesnt know how to deserialize the SOAP into the User data contract because of the namespace mismatch.
In C#, these two objects are different because they are in different namespaces...
namespace UserServices
{
    public class User
    {
        public string FirstName { get; set; }
    }
}

namespace TempuriServices
{
    public class User
    {
        public string FirstName { get; set; }
    }
}

The Namespace in XML / SOAP serves the same purpose, to make sure the objects are from the same "body" / "company" / "organization" / "domain" etc.
From what I have found, when I build SOAP services, I tend to keep all of my data contracts, service contracts, and binding namespaces in the same namespace, e.g. "http://mycompany.com/services/serviceName"
here are some great resources...
Data Contract Equivalence => http://msdn.microsoft.com/en-us/library/ms734767.aspx
Data Contract Versioning Best Practices => http://msdn.microsoft.com/en-us/library/ms733832.aspx
Hope this helps.

A: In addition to other answers, I will try to add what I know to this topic.
In short, they both overwrite the default Name and Namespace of the [DataContract] and [DataMember] (Name) with whatever you supply to these properties.
According to the MS's documentation for DataContractAttribute.Namespace property (they are called properties of the attribute, not attribute), on the 'Tip' section it states link, "For the data to be successfully transmitted, the name of the data in a data contract must be the same in both the client and the server. Visual Basic projects, by default, add a prefix to the namespace defined in each file (called the "root namespace," named after the project). Adding this prefix causes the client and server namespaces to be different for the same type. The solution is to set the Namespace property to "", or to explicitly set the data contract namespace in this property."
From what I have understood, for DataContract attribute to be able to serialize/deserialize the data, the data must have a matching namespace in both client and the server side, which might always not be the case in a real world situation. For instance, your data on the Server side, if named in a readable and sensible way, might be under the namespace that has a name something like "NameOfTheSolution.Server.NameOfTheProject," whereas on the client side, it could be something like "NameOfTheSolution.Client.NameOfTheProject." Due to different namespace the DataContracts are in, [DataContract] attribute won't be able serialize/deserialize the data between the client and server.  I am not positive, but this could be the reason why it said method not allowed in your case, due to a mismatched namespace. In a situation where namespaces do not match, 'Namespace' property could be used while using the [DataContract] attribute and provide the class on the either side (client/server) with the same namespace, although they physically lay in different namespaces.
[DataContract (Namespace = "Whatever you want, usually uri")]
public class User
{}

As far as the 'Name' property of the [DataContract] attribute goes, it overrides the name of your datacontract with the name you provide to this property.  One use of it, in the context of DataMember attribute is to overload a method within a data contract. A DataContract doesn't allow two DataMember with the same name, so in such scenario, 'Name' property is useful.

A: Based on another question and on:

I am not sure what the Name and
  Namespace attributes do to the
  DataContract attribute when calling
  http://localhost:8081/user/register
  for example?

I suggest that you are using REST service. When you called the service without setting Namespace to empty string did you define User XML with namespace xmlns="http://tempuri.org"? If not you sent to service different/unknown "data type" and it is probably reason for returned error.


text:
Q: What does capital D above an equal sign mean? I was beginning to self study time series and came across this notation: $\stackrel{\mathcal{D}}{=}$. I wonder what it means? (I have limited access to the textbooks for the moment, so I have to post a question here.)
For more context, it was in the definition for a strongly stationary sequence, where the article states the condition for such a sequence being $(X_{t_1},...,X_{t_k})\stackrel{\mathcal{D}}{=}(X_{t_1+h},...,X_{t_k+h})$ for all $\{t_1,...,t_k\}$ and $h$.

A: In the context of the linked notes, the symbol refers to equality in distribution ---i.e., the statement:
$$(X_{t_1},...,X_{t_k})\stackrel{\mathcal{D}}{=}(X_{t_1+h},...,X_{t_k+h})
\quad \quad \quad \text{for all } t_1,...,t_k \text{ and } h,$$
is a shorthand way of saying that:
$$\mathbb{P}(X_{t_1},...,X_{t_k} \leqslant \mathbf{x}) = \mathbb{P}(X_{t_1+h},...,X_{t_k+h} \leqslant \mathbf{x})
\quad \quad \quad \text{for all } t_1,...,t_k, h \text{ and } \mathbf{x}.$$


text:
Q: Perl installation issue using Docker I am trying to build the docker image with perl installation.
Dockerfile:
FROM amazonlinux
WORKDIR /shared
RUN yum -y install gcc
ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
RUN tar -xzf perl-5.22.1.tar.gz

WORKDIR /shared/perl-5.22.1
RUN ./Configure -des -Dprefix=/opt/perl-5.22.1/localperl

RUN make
RUN make test
RUN make install

all these steps are executed i am can see it executing the make, make test and make install commands but when i do :
docker run -it testsh /bin/bash

Error:
when I  check perl -v it says command not found.
and I need to go the perl directory
'cd perl-5.22.1' and run 'make install' again then perl -v works
But I want the perl installation to work when I build it with docker image. can anyone tell me what is going wrong here?

A: perl was indeed installed, just wasn't added to the path.
export PATH=$PATH:/shared/perl-5.22.1 should do it -- but of course, you'd want to add a PATH update in the Dockerfile.

A: At first glance I thought that when you run make install second time, it adds perl's bin directory to PATH env, but when I compared output of env before and after make install it showed the same PATH variable content.
The reason you getting perl -v working after make install in running container is that make install puts perl binary to /usr/bin/perl. I don't know why it works such way, but it is just as it is. Also, it's almost useless to store sources inside of your image.
Anyway, I agree with @belwood suggestion about adding your perl's bin directiry to PATH environment variable. I just wanna correct the path: /opt/perl-5.22.1/localperl/bin
You need to add it in your Dockerfile (basically I've rewritten your file to make it produce more efficient image), for example:
FROM amazonlinux

RUN mkdir -p /shared/perl-5.22.1
WORKDIR /shared/perl-5.22.1

RUN yum -y install gcc \
  && curl -SL http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz -o perl-5.22.1.tar.gz \
  && tar --strip-components=1 -xzf perl-5.22.1.tar.gz \
  && rm perl-5.22.1.tar.gz \
  && ./Configure -des -Dprefix=/opt/perl-5.22.1/localperl \
  && make -j $(nproc) \
  && make -j $(nproc) test \
  && make install \
  && rm -fr /shared/perl-5.22.1 /tmp/*

ENV PATH="/opt/perl-5.22.1/localperl/bin:$PATH"
WORKDIR /root

CMD ["perl","-de0"]

When you simply run container with this image, you'll immediately get into perl's shell. If you need bash, then use docker run -it --rm amazon-perl /bin/bash
It would be also good to look at Environment replacement section in the Dockerfile reference documentation, just to figure out how things work. For example, it isn't a best pratice to have that many RUN lines in your Dockerfile because of the RUN instruction will execute commands in a new layer on top of the current image and commit the results. So you'll get many unnecessary layers.


text:
Q: PhoneGap Media Plugin - can you detect when url stream has loaded? I been having some issues getting my audio player to work correctly in iOS and Android using the PhoneGap Media plugin through Build 3.1
I have play and stop buttons that work fine but when you hit play there is a slight delay as the audio url loads and it freezes the OS. I can kind of cope with that as its a short delay so I thought I'd pop up a loading icon onscreen.
Ive posted a few time here trying to get the JS to work as im no expert but just now I've realised that there is nothing in my code to check if the audio is actually PLAYING!
The playAudio function loads in the audio and then sets the play button to a stop button. I thought function success() {meant it was playing but it actually means it FINISHED playing.
In my code when the link to the audio is clicked the loader function makes a spinner appear on screen and I thought 'success' would turn the loader off because its loaded when in fact whats happening is the laoder stays on and goes away after the track has finished!
I've realized I need a way of detecting if the track is actually PLAYING!
How do I do that?!?!!
Heres the function:
function loadPlay(src, trackName) {
   loader();
   playAudio(src, trackName);
}

function loader() {
        // make a loader spinner appear as track loads
    $(".loading").addClass("loadingnow");
}

function playAudio(src,trackname) {
    // for Android
    if (audioPlaying === false) {
        if (device.platform == 'Android') {
            src = '/android_asset/www/' + src;
        }
        media = new Media(src, success, error_error);
        media.play();
        //add playing class so play button is replaced with stop button
        document.getElementById(trackname).parentNode.className="playing";
        audioPlaying = true;
    } else {
        //audio is already playing
    }
}

function success() {
    // track isplaying so remove the stop button put play button back
    $(".playing").removeClass("playing");
    // now track is playing remove the loader spinner
    $(".loading").removeClass("loadingnow");

    audioPlaying = false;
}

function error_error(e) {
    //alert('great error');
    //alert(e.message);
}

function stopAudio() {
    // stop playing track
    if (media) {
        media.stop();
        audioPlaying = false;
    }
}

Heres a link to the PhoneGap Media plugin API:
http://docs.phonegap.com/en/3.1.0/cordova_media_media.md.html#Media
Do I need to use this bit?
Media.MEDIA_STARTING = 1;
Media.MEDIA_RUNNING = 2;
Media.MEDIA_PAUSED = 3;
Media.MEDIA_STOPPED = 4;

A: From the docs:
The following constants are reported as the only parameter to the mediaStatus callback function.

Media.MEDIA_NONE = 0;
Media.MEDIA_STARTING = 1;
Media.MEDIA_RUNNING = 2;
Media.MEDIA_PAUSED = 3;
Media.MEDIA_STOPPED = 4;

The mediaStatus callback is an optional 3rd callback supplied in your Media constructor...
media = new Media(src, success, error_error, status_change);

function status_change(code) {
    switch (code) :
    case Media.MEDIA_STOPPED : doSomething(); break;
}

A: From what I can tell, ilovett's answer might not work for you, because the doSomething() function will get called in two other cases:

*

*When someone stops the music with a media.stop()

*When the media gets released (media.release()) on android (not sure about others, but iOS wont call it).

the way I'm doing it is setting a variable to make sure that the function is not getting called accidentally.


text:
Q: Intellij git branches - group them into folders I'm using gitflow for my project.
I decided not to squash feature commit for the moment because it's an experimental project and I want fine grane control over modification. Hence I have many branches named feature/<some_feature_name>.
The default behavior of the "Branches..." view of IDEA is to flatten them out displaying a long list that looks like:
├─ master/
├─ develop/
├─ feature/f1
├─ feature/f2
├─ feature/f3
├─ [...]
├─ hotfix/h1
├─ hotfix/h2
└─ [...]

Many git GUIs graphically groups them into "folders", something like:
├─ master/
├─ develop/
├─ feature/
│   ├─ f1
│   ├─ f2
│   ├─ f3
│   └─ [...]
└─ hotfix/
    ├─ h1
    ├─ h2
    └─ [...]

Is there any plugin/setting to achieve that?

A: This won't be support by IntelliJ IDEA.
See:

*

*https://youtrack.jetbrains.com/issue/IDEA-140691

*https://youtrack.jetbrains.com/issue/IDEA-127468
Reason
IntelliJ IDEA tries to have a consistent UX. One thing you can rely on is that you can start to filter/search in any view by just start typing. This is really easy and helps to create a consistent mouseless experience.
If you want to see all hotfix branches, just type hotfix!
In short: A flattened tree is easier to filter and search if you follow the mouseless UX matra.


text:
Q: Find the locus of the point $P$ on the circumference of the circle which is on the origin at the initial position of the circle.
Consider the circle of radius $1$ with its centre at the point $(0,1)$. From this initial position, the circle is rolled along the positive $x$-axis without slipping. Find the locus of the point $P$ on the circumference of the circle which is on the origin at the initial position of the circle.

My approach:
Let us assume that the circle is moving with a constant velocity $v$. Then after time $t$, the distance travelled by the centre of the circle, as measured from the initial position is $d=vt$. Now let the point $P$ be at a new position $P'=(a,b)$.
This also implies that the centre of the circle is at $(d,1)=(vt,1)$.
Note that $(a,b)$ is a point of the circle having centre at $(vt,1)$ and radius $1$.
Therefore, $(a,b)$ must satisfy the equation of that circle. Now, the equation of that circle is $(x-vt)^2+(y-1)^2=1$. Thus, we have $(a-vt)^2+(b-1)^2=1$.
Also, a geometric approach helps us in showing that $$a=vt-\sin vt \text{ and } b=1-\cos vt.$$
But, what's the locus then?


text:
Q: CSS make select box the same size as my input text boxes I have tried a lot of different things and looked on the web but I can't figure how I can have my boxes in a form aligned and at the same size.
I am using a form and inside the form a table. The table as a class and from there I try to give width and height to my input and select with:
table.form-override {
    border-collapse: collapse;
}
table.form-override tr td {
    border-top-style: none;
    border-right-style: none;
    border-bottom-style: none;
    border-left-style: none;
    padding-bottom: 5px;
}
table.form-override label {
    padding-right: 10px;
    vertical-align:center;
}
table.form-override input, select, option {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}
table.form-override input, select {
    width: 300px;
    height: 35px;
    border : 1px #ccc solid;
    vertical-align: center;
}

But of course, it is not working.
How can I achieve that?
Thanks.

A: Your CSS works fine - see http://codepen.io/raad/pen/FniEy
</style>
body, td, form {
  padding: 5px;
}
table.form-override {
    border-collapse: collapse;
    background-color: #fdf;
}
table.form-override tr td {
    border-top-style: none;
    border-right-style: none;
    border-bottom-style: none;
    border-left-style: none;
    padding-bottom: 5px;
}
table.form-override label {
    padding-right: 10px;
    vertical-align:center;
}
table.form-override input, select, option {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}
table.form-override input, select {
    width: 300px;
    height: 35px;
    border : 1px #ccc solid;
    vertical-align: center;
}
</style>

<form>

      Hello
      <input type="text" />

      World

        <select>
            <option value="1">One</option>
            <option value="2">Two</option>
            <option value="3">Three</option>
        </select>

</form>

What you may need is a reset like Normalize or Reset.
Although these are used more for reducing browsers inconsistencies in default object metrics, they may help with giving different objects the same metrics.


text:
Q: Why is a ActiveRecord query with a less than operator in a having clause not returning the expected records? This first squeel query gives me what I expect: all of the QuoteStops with the highest sequence for their given quote.
QuoteStop.joins{quote}.group{quote.id}.having{sequence == max(sequence)}.pluck("quote_stops.sequence")

SELECT quote_stops.sequence FROM "quote_stops" INNER JOIN "quotes" ON "quotes"."id" = "quote_stops"."quote_id" GROUP BY "quotes"."id" HAVING "quote_stops"."sequence" = max("quote_stops"."sequence")

[2, 3 ... 2]

But, if I change the comparison in the having clause to < the SQL looks right but the result is an empty list when I'd like to be all of the QuoteStops that didn't have the highest sequence.
QuoteStop.joins{quote}.group{quote.id}.having{ sequence < max(sequence) }.pluck("quote_stops.sequence")

SELECT quote_stops.sequence FROM "quote_stops" INNER JOIN "quotes" ON "quotes"."id" = "quote_stops"."quote_id" GROUP BY "quotes"."id" HAVING "quote_stops"."sequence" < max("quote_stops"."sequence")

[]

What am I missing? Squeel or ActiveRecord answers are fine.


text:
Q: Animate changes to Array - SwiftUI ForEach I'm new to SwiftUI coming from UIKit. I'm trying to achieve the following:

*

*Given an array of mutable states in a view model that represents current progress to be displayed on a Circle using trim(from:to:)

*Loop over each item to render a circle with the current progress and animate changes from the old to the new position

*A view model will periodically update the array that is a @Published value in an ObservableObject.

I setup a demo view that looks like this

@StateObject var demoViewModel: DemoViewModel = DemoViewModel()

var body: some View {
            ForEach(demoViewModel.progress, id: \.self) { progress in
                Circle()
                    .trim(from: 0, to: progress.progress)
                     .stroke(style: StrokeStyle(lineWidth: 15, lineCap: .round))
                     .foregroundColor(.red)
                     .frame(width: 100)
                     .rotationEffect(.degrees(-90))
                     .animation(.linear(duration: 1), value: demoViewModel.progress)
            }
        }

and a test view model like this
class DemoViewModel: ObservableObject {

    @Published var progress: [Demo] = [.init(progress: 0)]

    struct Demo: Hashable {
        let progress: Double
    }

    init() {
        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
            let current = self.progress[0]

            if current.progress < 1 {
                self.progress[0] = .init(progress: current.progress + 0.1)
            }

        }
    }
}

For the sake of the demo the array only has one item. What I expected was on each iteration a new value is written to the item in the array which triggers the animation to animate to that value. What actually happens is the progress updates, but it jumps to each new value for no animation.

A: Try this approach, where the self.demos[0].progress in init()
is updated rather than creating a new Demo(...) at each time tick.
Note, modified a few other things as well, such as the .animation(...value:..) and in particular the ForEach loop with the added Demo unique id.
struct ContentView: View {
    @StateObject var demoViewModel: DemoViewModel = DemoViewModel()

    var body: some View {
        VStack {
            ForEach(demoViewModel.demos) { demo in  // <-- here
                Circle()
                    .trim(from: 0, to: demo.progress)
                    .stroke(style: StrokeStyle(lineWidth: 15, lineCap: .round))
                    .foregroundColor(.red)
                    .frame(width: 100)
                    .rotationEffect(.degrees(-90))
                    .animation(.linear(duration: 1), value: demo.progress) // <-- here
            }
        }
    }
}

class DemoViewModel: ObservableObject {
    @Published var demos:[Demo] = [Demo(progress: 0)]

    struct Demo: Identifiable, Hashable {  // <-- here
        let id = UUID()  // <-- here
        var progress: Double  // <-- here
    }

    init() {
        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
            if self.demos[0].progress < 1 {
                self.demos[0].progress = self.demos[0].progress + 0.1 // <-- here
            }
        }
    }

}


text:
Q: ng-grid not working in IE8 I'm going nuts trying to figure out why ng-grid isn't working in IE8.  I get this error: Expected identifier, string or number ng-grid-2.0.5.debug.js, line 1535 character 17.
I'm copying an example straight from the ng-grid homepage (all the examples there load correctly, by the way). Anyone have an idea here?
I would put up a Plnkr or fiddle, but neither will even load in IE8, so it kind of defeats the purpose.
using Angular 1.0.4, jQuery 1.8.1, ng-grid 2.0.5
html

    <meta charset="utf-8">
    <title>Getting Started With ngGrid Example</title>
    <link rel="stylesheet" type="text/css" href="ng-grid.css" />
    <link rel="stylesheet" type="text/css" href="style.css" />

CSS
.gridStyle {
  border: 1px solid rgb(212,212,212);
  width: 400px;
  height: 300px;
}

Javascript
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope) {
    $scope.myData = [{name: "Moroni", age: 50},
                     {name: "Tiancum", age: 43},
                     {name: "Jacob", age: 27},
                     {name: "Nephi", age: 29},
                     {name: "Enos", age: 34}];
    $scope.gridOptions = {
        data: 'myData',
        columnDefs: [{field:'name', displayName:'Name'}, {field:'age', displayName:'Age'}]
    };
});

A: Turns out the answer was not so obvious.  There was a bug in ng-grid 2.0.5 where the devs were using the Javascript forEach method in one spot instead of angular.forEach.  This is not supported by IE8 and was causing the error. I submitted it to the group and they'll fix it, but for now I just made the change.

A: Internet Explorer requires special treatment for accommodating AngularJS.
Please read this.
http://docs.angularjs.org/guide/ie


text:
Q: Regex: how to match list of specific domains I need a regex which will match a specific list of domains in e-mail addresses.
I know this is probably not a popular issue, but it's for internal use, and for a limited list of e-mail addresses. I have like 10-12 domains that I need to be able to match.
The domain names do not contain sub domains or dots and the suffix is always the same, like:
*@onedomain.com
*@anotherdomain.com
*@thirddomain.com

I have tried with this:
/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@(?i)(onedomain|anotherdomain|thirddomain|domain4)\.com$/

But I get this error: Invalid syntax.
Can anybody help with this, please?
Thanks.

A: It seems you can't use (?i) with javascript regex.
You have to use the /i modifier instead.
pattern = new RegExp('^[\w-]+(\.[\w-]+)*@(onedomain|anotherdomain|thirddomain|domain4)\.com$','i')

A: I know you asked for a regex solution, but if the list of domains is long, you might want to consider not doing it purely in regex. 10-12 domains could make for one long nasty expression.
Instead you can use regex to match a basic email format, and then keep an array of whitelisted domains that are allowed. That way you don't need to put all the domains into the expression itself.
function isValidEmail(address) {
    var domains = ["onedomain","anotherdomain","thirddomain","domain4"];

    // Basic .com email matching
    var regex = /^[\w-]+(?:\.[\w-]+)*@(.*)\.com$/i;
    var matches = regex.exec(email);

    // Assert that address is an .com email address
    if (matches === null)
        return false;

    // return true if domain is in whitelist, false otherwise
    return (domains.indexOf(matches[1]) != -1);
}

Changing @(.*)\.com to @(.*\..{2,}) will enable you to put the full domain in the whitelist array should you need to match other domains than .com you'd then have to put domain4.com etc. in the array instead.

A: If the issue is about the regex, you could try this :
/^[\w-\.]+@domain(1|2|3|4)\.com$/

About your regex : I think the syntax error is in the (?i) part. I don't really see what is this group for, and it is invalid.

A: Try this regex to match @domainX.com:
[A-Za-z0-9!#$%&'*+-/=?^_`\.{|}~]+@domain[1-4]\.com

it matches
test@domain1.com
user123@domain4.com

and much more
EDIT
to match every domain use this regex:
[A-Za-z0-9!#$%&'*+-/=?^_`\.{|}~]+@([a-z0-9_-]+[\.]?)*


text:
Q: Regex help, words that contain numbers without a space I have been trying for hours now to figure out this regex and it will not work correctly.
What i need is one that will match the following:
I need it to match IF any word in the entire description is a character followed by a number, without a space
for example:
MC15 this is a test description - MATCH
MC 15 this is another description - NO MATCH
another test MC55 description - MATCH
another test MC 55 description - NO MATCH
i greatly appreciate any help!
thanks for your time!

A: Can you use "find" instead of "match"?  (I.E., the regular expression method you call on your pattern - in order to search for a substring instead of matching against the entire input?)  If so, this will do nicely:
([a-zA-Z]+\d+)

Otherwise, it can be expanded to work with "match", using something like:
\b*([a-zA-Z]+\d+)\b*

A: In perl, a regexp like /[a-zA-Z]+\d+/ would work:

*

*[a-zA-Z] denotes any letter

*\d denotes any decimal

*the + after each character class says it has to be present one or more times

A: (?<aMatch>[a-zA-Z]+[0-9]+)
This matches any a-z or A-Z character one or more times followed by any number 0-9 one or more times, no spaces or any other character allowed to separate them


text: Q: Помогите спроектировать программу. Не могу сделать код логически правильным В общем есть класс, назовем его FTP, в нем методы ConnectFTP, CompareFiles и Download Files и форма которая вызывает метод ConnectFTP по нажатию кнопки. Этот метод, который вызывает кнопка из формы, вызывает другой метод CompareFiles, который потом вызывает DownloadFiles. Мне кажется этот код, который я написал, отвратительным, но я хочу придерживаться этих трех методов. Первое что мне бросается в глаза - это то, что я вызываю скачивание через "ConnectFTP". Это не отражает сути, но я не знаю как это правильно спроектировать. Нужно запускать из формы например так DownloadFiles(); и чтобы этот метод вызвал в начале ConnectFTP, потом CompareFiles и только потом начал выполняться сам. Прошу обратить внимание на то, что методы асинхронные) Если это важно.


text:
Q: MongoDB obtain select field Currently in the process of creating a script with pymongo. I have a python script setup so whenever a user registers their account it stores the UserID and Account name in MongoDB.
At the moment I want to add a feature so whenever a user discontinues the service it sends a message which only contains their Account name.
I have this code:
y = patreons.find_one({"ID": ctx.message.author.id})

And it returns the following:
{'_id': ObjectId('5dccf3c54d7b9081ad285a15'), 'ID': 203268468613709824, 'Github': 'Bencey2 '}

Any idea how I can get it so it only returns the Github Field?
Much appreciated
Bencey

A: Specify the fields you need as you're trying to find a document. This should work:
y = patreons.find_one({"ID": ctx.message.author.id}, {"Github": 1, "ID": 0, "_id": 0})


text:
Q: Android surface canvas.drawRect has a decaying shadow effect I'm writing an Android app which uses custom draw on SurfaceView and I'm getting a decaying shadow effect when i move the object (currently a rect). Below is portion of my code.
    canvas = _surfaceHolder.lockCanvas(null);
    if (canvas != null) {
        synchronized (_surfaceHolder) {
        // Starts of actual drawing code
            if (paintFg != null) {
                canvas.drawARGB(55, 55, 55, 55);
                canvas.drawRect(x, y, x+100, y+100, paintFg);
                }
            }
        }
    }

When I change x and y, the box is drawn elsewhere, but the existing place have a decaying effect. I would like disable that.
Btw, I'm testing this on a Galaxy S3 with JellyBean. Not sure if ProjectButter that causes this, and I've get to tried on a older phone.

A: I found that if I change canvas.drawARGB(55, 55, 55, 55); to canvas.drawRGB(0, 0, 0); it solved the problem. But I'm still not sure what's the cause. Anyone care to point out?


text:
Q: Custom Attribute Search using SearchCriteria I have created some custom attribute like city and I need to search how many products I have in a specific city using SearchCriteria.
The SearchCriteria I apply does not filter products on my city attribute and I always get all the products.
This is my code for getting a specific city Products:
   $objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
    $filter_1 = $objectManager
        ->create('Magento\Framework\Api\FilterBuilder')
        ->setField('city')
        ->setConditionType('like')
        ->setValue("Chennai%")
        ->create();
    $search_criteria =$objectManager
        ->create('Magento\Framework\Api\SearchCriteriaBuilder')
        ->setFilterGroups([$filter_group])
        ->create();

    $repo =$objectManager->get('Magento\Catalog\Model\ProductRepository');
    $result = $repo->getList($search_criteria);
    $products = $result->getItems();
    echo count($products);

I can get all the products using the below filter:
   $filter_1 = $objectManager
    ->create('Magento\Framework\Api\FilterBuilder')
    ->setField('city')
    ->setConditionType('like')
    ->setValue("%")
    ->create();

Can you suggest me how to get products filtering on a specific attribute?


text:
Q: ¿Cómo separar con coma números en JavaScript? Tengo una tipo calculadora en que ingresas una cantidad y te va a dar el ahorro que vas a generar.
El problema que tengo es que quieren que esté la cantidad del ahorro separada por una coma cuando son cantidades grandes.
Estuve revisando la funcion split() pero veo que solo sirve en string.
En este input ingresas la cantidad que quieras:
 <input required id="valor" type="text" placeholder="$$" onkeyUp="calcular();">

En este span se genera la cantidad que se va a ahorrar:

Aquí mando llamar el valor del input y del span:
  var valor = document.getElementById("valor").value;
  var totalahrr = document.getElementById('totalahrr');

Y aquí hago la formula para los resultados:
  var ahorro = parseInt(totalant) - parseInt(totalds);

Codigo

A: Puedes hacer uso del método toLocaleString, es fácil de utilizar espero te funcione.

var n = new Number(1000000);
var myObj = {
  style: "currency",
  currency: "MXN"
}

document.write(n.toLocaleString("es-MX", myObj));

A: tambien puedes usar esta funcion
function currencyFormat(num) {
return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');}


text:
Q: Wordpress wp_editor jquery drag drop offset issue I'm having an issue with the following code:
i'm initializing an tinyMCE editor in Wordpress:
    wp_editor("
HTML content
", "id-of-editor", $settings);

This generates an tinyMCE editor within an iframe. Inside that iframe i have a dropppable jquery ui div.
I want to drop content from outside the iframe, into the iframe.
So far i have made this:
$( "#drag" ).draggable({
            helper: "clone",
            revert:"valid",iframeFix:true
         });

$("#editor-iframe").contents().find(".droppable-div").droppable({

         accept: "#drag",

    });

Everything works, except for one thing. There is a 150px offset between the cursor position, and the real drag position.
Because of this, the drag event only is detected when i put the draggable item far away from the droppable zone.
Any help ?
Thanks in advance. Sorry for my bad english! It's not my native language.
Image Description of the problem:
http://i.stack.imgur.com/4hGfW.jpg