问:
How can I resolve a "Provider load failure" for WMI requests?
I'm using WMI to collect system information.  It works fine on every system I've tested it on, but I have one or two users that are reporting problems.  The debug logs show the WMI code is throwing a "Provider load failure" exception.  I haven't been able to replicate the issue.

The users have verified that the WMI service is running in Automatic mode.

Here's the exception:

```<code>System.Management.ManagementException: Provider load failure
   at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
   at System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()
</code>```

Any thoughts on how to troubleshoot and resolve this issue?

答: You might want to confirm all the dlls are properly registered (see http://msdn.microsoft.com/en-us/library/bb961987.aspx).</p>

OwnerDisplayName: Chris Thompson

ContentLicense: CC BY-SA 2.5

Body:
I'm using WMI to collect system information.  It works fine on every system I've tested it on, but I have one or two users that are reporting problems.  The debug logs show the WMI code is throwing a "Provider load failure" exception.  I haven't been able to replicate the issue.

The users have verified that the WMI service is running in Automatic mode.

Here's the exception:

System.Management.ManagementException: Provider load failure
   at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
   at System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()

Any thoughts on how to troubleshoot and resolve this issue?

OwnerDisplayName: C. Ross


来源: stackexchange

问:
java code corresponding to Newtonsoft.Json.JsonConvert.SerializeObject(Object source,Newtonsoft.Json.JsonSerializerSettings()) in .net?
I have a code in .net that serializes a request to the json format ... The code is something like this.

```<code>  var ops = new Newtonsoft.Json.JsonSerializerSettings();
  ops.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
  ops.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
  ops.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;
  ops.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());

  String strSO = Newtonsoft.Json.JsonConvert.SerializeObject(source,
  bIndent ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None,
  ops);
</code>```

I tried the java code corresponding to this portion but it doesn't work.

答:
From my understanding, the Newtonsoft serializer takes an object with member variables and outputs a json string that represents that object.

So you can do something like:

```<code>Product product = new Product();

product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);
</code>```

And you'll get an output string like:

```<code>{"Name": "Apple",
"Expiry": "\/Date(1230375600000+1300)\/",
"Price": 3.99,
"Sizes": ["Small", "Medium", "Large"]
}
</code>```

Now the bad news is that the BlackBerry library that you're using doesn't use reflection to examine the structure of objects it serialises. It is a formatter rather than a serializer.

The good news is that it is pretty easy to use. The documentation is here:

http://www.blackberry.com/developers/docs/6.0.0api/org/json/me/package-summary.html

In short, to write an object such as the one above, you would do something like:

```<code> myString = new JSONStringer()
 .object()
     .key("Name")
     .value("Apple")
     .key("Expiry")
     .value("Date("+myDate.getTime()+")")
 .endObject()
 .toString();
</code>```

..and so on. Note that you are constructing the JSON structure element by element, rather than having the JSON library assume that your object is the exact structure of the data you wish to output.

Hopefully this will give you some idea of how to proceed.

ContentLicense: CC BY-SA 3.0

Body:
I have a code in .net that serializes a request to the json format ... The code is something like this.

  var ops = new Newtonsoft.Json.JsonSerializerSettings();
  ops.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
  ops.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
  ops.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;
  ops.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());

  String strSO = Newtonsoft.Json.JsonConvert.SerializeObject(source,
  bIndent ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None,
  ops);

I tried the java code corresponding to this portion but it doesn't work.

Body:
From my understanding, the Newtonsoft serializer takes an object with member variables and outputs a json string that represents that object.

So you can do something like:

Product product = new Product();

product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);

And you'll get an output string like:

{"Name": "Apple",
"Expiry": "\/Date(1230375600000+1300)\/",
"Price": 3.99,
"Sizes": ["Small", "Medium", "Large"]
}

Now the bad news is that the BlackBerry library that you're using doesn't use reflection to examine the structure of objects it serialises. It is a formatter rather than a serializer.

The good news is that it is pretty easy to use. The documentation is here:

http://www.blackberry.com/developers/docs/6.0.0api/org/json/me/package-summary.html

In short, to write an object such as the one above, you would do something like:

 myString = new JSONStringer()
 .object()
     .key("Name")
     .value("Apple")
     .key("Expiry")
     .value("Date("+myDate.getTime()+")")
 .endObject()
 .toString();

..and so on. Note that you are constructing the JSON structure element by element, rather than having the JSON library assume that your object is the exact structure of the data you wish to output.

Hopefully this will give you some idea of how to proceed.


问:
Retrieving the last element of a list in Panda Dataframe column
I have this csv file example: (read this as item AAA costs 1000 and item AAA(1) costs 2000)

```<code>ColumnName
AAA (1000)
AAA (1) (2000)
</code>```

I would like to create a pandas dataframe column of all numbers

ie

```<code>Column_cost
1000
2000
</code>```

I tried to split this by '(' which returns something like the following (because the second item has '(' in the name:

```<code>Result 1
Col_1 Col_2 Col_3

AAA 1000) None

AAA   1)  2000)
</code>```

so the numbers are not in the same column

I then tried creating a columns of lists which gives

```<code>Result 2

ColumnName2

[AAA,1000)]

[AAA,1),2000)]
</code>```

but again, I don't know how to create a column that uses the last element of each list.

I can get it for a particular index, but not for the whole column

```<code>x = df['ColumnName'].str.split('(',expand=True) gives Result 1 above

x = df['ColumnName'].str.split('(') gives Result 2 above
</code>```

From Result 2, I did the following to get the desired result for one particular cell, but I don't know how to do it for the whole column (I can do this for a small dataset, but not for a large one)

retrieves the list of a particular index, gets the last element of the list, splits it by spaces, and then retrieves the new element of the split list

```<code>x[0][-1].split()[0]
x[1][-1].split()[0]
</code>```

答:
Another solution using Series.str.split, str.strip and astype:

```<code>df['Column_cost'] = df.ColumnName.str.split('(').str[-1].str.strip(')').astype(int)
</code>```

[out]

```<code>       ColumnName  Column_cost
0      AAA (1000)         1000
1  AAA (1) (2000)         2000
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this csv file example: (read this as item AAA costs 1000 and item AAA(1) costs 2000)

ColumnName
AAA (1000)
AAA (1) (2000)

I would like to create a pandas dataframe column of all numbers

ie

Column_cost
1000
2000

I tried to split this by '(' which returns something like the following (because the second item has '(' in the name:

Result 1
Col_1 Col_2 Col_3

AAA 1000) None

AAA   1)  2000)

so the numbers are not in the same column

I then tried creating a columns of lists which gives

Result 2

ColumnName2

[AAA,1000)]

[AAA,1),2000)]

but again, I don't know how to create a column that uses the last element of each list.

I can get it for a particular index, but not for the whole column

x = df['ColumnName'].str.split('(',expand=True) gives Result 1 above

x = df['ColumnName'].str.split('(') gives Result 2 above

From Result 2, I did the following to get the desired result for one particular cell, but I don't know how to do it for the whole column (I can do this for a small dataset, but not for a large one)

retrieves the list of a particular index, gets the last element of the list, splits it by spaces, and then retrieves the new element of the split list

x[0][-1].split()[0]
x[1][-1].split()[0]

Body:
Another solution using Series.str.split, str.strip and astype:

df['Column_cost'] = df.ColumnName.str.split('(').str[-1].str.strip(')').astype(int)

[out]

       ColumnName  Column_cost
0      AAA (1000)         1000
1  AAA (1) (2000)         2000


问:
How to access ref of a component through a function in React Native?
I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

```<code>render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent1 = component} />
      <MyComponent ref={component => this.myComponent2 = component} />
      <MyComponent ref={component => this.myComponent3 = component} />
    </View>
  )
}
</code>```

Then, In the same screen file, I've created another function to access the state of my custom component. I wrote it like this.

```<code>myFunction = (ref) => {
  ref.setState({ myState: myValue })
}
</code>```

Then, I want to call that function for those separate components separately like this. (In the screen file)

```<code>this.myFunction(this.myComponent1)
this.myFunction(this.myComponent2)
this.myFunction(this.myComponent3)
</code>```

But, it does not work. It gives me the following error.

null is not an object (evaluating 'ref.setState')

Actually what I need this myFunction to do is,

```<code>this.myComponent1.setState({ myState: myValue })
this.myComponent2.setState({ myState: myValue })
this.myComponent3.setState({ myState: myValue })
</code>```

The state myState is in the component while I want to access it through the myFunction() in my screen file.

Can you please help me to solve this problem?

答:
First make sur that MyComponent is a component and not a stateless Component, then, to change states, try this :

```<code>myFunction = (ref) => {
  ref.current.setState({ myState: myValue }
}
</code>```

and of course , for it to work, your component need to be already mounts, If you try for example to call this in the constructor, it will not work

Body:
I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent1 = component} />
      <MyComponent ref={component => this.myComponent2 = component} />
      <MyComponent ref={component => this.myComponent3 = component} />
    </View>
  )
}

Then, In the same screen file, I've created another function to access the state of my custom component. I wrote it like this.

myFunction = (ref) => {
  ref.setState({ myState: myValue })
}

Then, I want to call that function for those separate components separately like this. (In the screen file)

this.myFunction(this.myComponent1)
this.myFunction(this.myComponent2)
this.myFunction(this.myComponent3)

But, it does not work. It gives me the following error.

null is not an object (evaluating 'ref.setState')

Actually what I need this myFunction to do is,

this.myComponent1.setState({ myState: myValue })
this.myComponent2.setState({ myState: myValue })
this.myComponent3.setState({ myState: myValue })

The state myState is in the component while I want to access it through the myFunction() in my screen file.

Can you please help me to solve this problem?

Body:
First make sur that MyComponent is a component and not a stateless Component, then, to change states, try this :

myFunction = (ref) => {
  ref.current.setState({ myState: myValue }
}

and of course , for it to work, your component need to be already mounts, If you try for example to call this in the constructor, it will not work


问:
How to sort data which mix text and number?
I have a data which will show as the table and using orderBy(lodash) to sort data but it's not working as I want.

Now, I code as
const data = orderBy(realData, ['name'], ['asc'])

Here's my data
input:
[{name: 'A1'},{name:'A2'},{name: 'A21'},{name:'B10'},{name: 'A100'},{name:'A22'},{name: 'B32'},{name:'A3'}]

The issue is 'orderBy' sort data as it text(ASCII sorting)
current output:
[{name: 'A1'},{name: 'A100'},{name:'A2'},{name: 'A21'},{name:'A22'},{name:'A3'},{name:'B10'},{name: 'B32'}]

but I would like the data output like this

[{name: 'A1'},{name:'A2'},{name:'A3'},{name: 'A21'},{name:'A22'},{name: 'A100'},{name:'B10'},{name: 'B32'}]

If anyone have any suggestion, please help.

Thank you.

答:
You can use string#localeCompare callback while sorting an array. To numerically sort the array use numeric property.

let data = [{name: 'A1'},{name: 'A100'},{name:'A2'},{name: 'A21'},{name:'A22'},{name:'A3'},{name:'B10'},{name: 'B32'}];
data.sort((a,b) => a.name.localeCompare(b.name, undefined, {numeric: true}));
console.log(data);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: 100% !important; top: 0;}</code>```

Body:
You can use string#localeCompare callback while sorting an array. To numerically sort the array use numeric property.

let data = [{name: 'A1'},{name: 'A100'},{name:'A2'},{name: 'A21'},{name:'A22'},{name:'A3'},{name:'B10'},{name: 'B32'}];
data.sort((a,b) => a.name.localeCompare(b.name, undefined, {numeric: true}));
console.log(data);

.as-console-wrapper {max-height: 100% !important; top: 0;}


问:
Android Studio 3.0 Preview - Studio does not have write access
I'm using Android Studio 3.0 Canary 1. I'm trying to update it to Android Studio 3.0 Canary 2 but it shows the following error:

Studio does not have write access to /private/var/folders/mk/h5qpw_r11_7ggh9q52n9hhlr0000gn/T/AppTranslocation/1321881E-C41D-4AF7-B207-F31894226D50/d/Android Studio 3.0 Preview.app/Contents. Please run it by a privileged user to update.

I even tried running Android studio with sudo from the command line:

```<code>sudo /Applications/Android\ Studio 3.0 Preview.app/Contents/MacOS/studio
</code>```

But it didn't work. Any help will be much appreciated.

答: In my case on Mac, Android Studio wasn't opened from the Applications folder for some reason. Make sure you open the one that's there and not a copy that's saved elsewhere, otherwise it won't have the privileges. </p>

Body:
I'm using Android Studio 3.0 Canary 1. I'm trying to update it to Android Studio 3.0 Canary 2 but it shows the following error:

Studio does not have write access to /private/var/folders/mk/h5qpw_r11_7ggh9q52n9hhlr0000gn/T/AppTranslocation/1321881E-C41D-4AF7-B207-F31894226D50/d/Android Studio 3.0 Preview.app/Contents. Please run it by a privileged user to update.

I even tried running Android studio with sudo from the command line:

sudo /Applications/Android\ Studio 3.0 Preview.app/Contents/MacOS/studio

But it didn't work. Any help will be much appreciated.


问:
How to find latitude and longitude
I have latitude and longitude of a point.I have to find out the latitude and longitude of another point from a relative distance from the known point.For example point A has some location with latitude and longitude.What is the latitude and longitude after moving 1000m south and 500m west from point A.Is there any direct equation to find this? Thanks in advance</p>

答:
Instead of looking up an equation you can calculate as follows. Let R be the radius of the Earth. Let a be the current latitude and b be the current longitude. Then if you move δx metres east (negative for west) then δy metres south, calculating the new longitude can be done as follows.

Intersecting a horizontal plane with the Earth at the current latitude will give you a circle of radius R*cos(a). So to convert δx to the change in longitude, you get something like

```<code>δlong = δx * 2π / (2π * R * cos(a)) = δx / (R * cos (a))
</code>```

The change in latitude is easier, since it doesn't depend on the current position. You're always moving around a great circle through the two poles. Then δlat = δy / R. (Of course you need to mod out by 2 π at some point).

Title: How to find latitude and longitude

Body:
Instead of looking up an equation you can calculate as follows. Let R be the radius of the Earth. Let a be the current latitude and b be the current longitude. Then if you move δx metres east (negative for west) then δy metres south, calculating the new longitude can be done as follows.

Intersecting a horizontal plane with the Earth at the current latitude will give you a circle of radius R*cos(a). So to convert δx to the change in longitude, you get something like

δlong = δx * 2π / (2π * R * cos(a)) = δx / (R * cos (a))

The change in latitude is easier, since it doesn't depend on the current position. You're always moving around a great circle through the two poles. Then δlat = δy / R. (Of course you need to mod out by 2 π at some point).


问:
Producer does not put messages in default resource file (BusinessLayer.ResX)
My application supports two languages: Dutch and Flemish (which is spoken in Belgium). I want all Dutch messages in the default resource file (BusinessLayer.ResX) and all Flemish messages in the BusinessLayer.nl_BE.ResX file, because the default fallback language must be Dutch if no Flemish message is found. How can I accomplish this?

I tried specifying no culture for the Dutch messages and no project culture, but the BOM producer keeps producing an empty default .ResX file and puts all Dutch messages in the .nl-NL.ResX file. Why does it think that messages must be put into the .nl-NL.ResX file? I don't specify anywhere in my xml project files that the Dutch culture must be used...

答:
Yes you have to specify the Culture property at the model project level.
See complete answer and model/code sample provided to your company by the private support channel on same subject, especially how to provide the related global or property/entity rules specific messages for all cultures.</p>


问:
The SQL command requires a parameter named "@SessionID", which is not found in the parameter mapping
I'm trying to execute a stored procedure via SSIS

Error: 0xC0207014 at PO Header, OLE DB Source [59]: The SQL command
  requires a parameter named "@SessionID", which is not found in the
  parameter mapping.

But as you can see below, the variables are populated, I have mapped the parameters.

So what's going on?

MS SQL 2014

MS Visual Studio 2015

答:
Based on the screenshots, you have mapped variables to parameters. Then just try to delete and recreate the OLE DB Source.

The SQL command requires a parameter, which is not found in the parameter mapping

If it still throwing an error, then use expressions instead of parameters. You can refer to the following link for more information:

Unable to pass a variable value to a stored procedure in ssis


问:
react-transition-group CSSTransition slide in on render
I'm trying to have a component conditionally render in React and slide it when it does render

packages:

```<code>"react": "^16.8.6",
"react-transition-group": "^4.0.1",
</code>```

code snippet:

```<code>{ expanded && (
    <CSSTransition in={expanded} timeout={500} classNames="slide">
        <div className="expandedDiv"></div>
    </CSSTransition>
)}
</code>```

css:

```<code>.slide-enter {
    transform: translateX(-100%);
    transition: .3s linear;
}
.slide-enter-active {
    transform: translateX(0%);
}
.slide-exit {
    transform: translateX(0%);
    transition: .3s linear;
}
.slide-exit-active {
    transform: translateX(-100%);
}
</code>```

structure:

```<code>+------------------------------+
|      |          |  header    |
|      |          |____________+
|      |          |  content   |
|      |          |            |
|      |          |            |
| nav  | expanded |            |
|      |          |            |
|      |          |            |
|      |          |            |
+------------------------------+
</code>```

Expanded should slide in on true, and slide out on false, it is expandedDiv from the code snippet

The div just pops in with no animation. Expected behaviour is a linear transition from left to right

Thanks

答:
```<code>               <CSSTransition
                    in={expanded}
                    timeout={300}
                    classNames="slide"
                    unmountOnExit
                    onEnter={() => this.toggleExpanded(true)}
                    onExited={() => this.toggleExpanded(false)}
                >
                    <div className="expandedDiv">
                    </div>
                </CSSTransition>
            </div>
</code>```

Body:
I'm trying to have a component conditionally render in React and slide it when it does render

packages:

"react": "^16.8.6",
"react-transition-group": "^4.0.1",

code snippet:

{ expanded && (
    <CSSTransition in={expanded} timeout={500} classNames="slide">

    </CSSTransition>
)}

css:

.slide-enter {
    transform: translateX(-100%);
    transition: .3s linear;
}
.slide-enter-active {
    transform: translateX(0%);
}
.slide-exit {
    transform: translateX(0%);
    transition: .3s linear;
}
.slide-exit-active {
    transform: translateX(-100%);
}

structure:

+------------------------------+
|      |          |  header    |
|      |          |____________+
|      |          |  content   |
|      |          |            |
|      |          |            |
| nav  | expanded |            |
|      |          |            |
|      |          |            |
|      |          |            |
+------------------------------+

Expanded should slide in on true, and slide out on false, it is expandedDiv from the code snippet

The div just pops in with no animation. Expected behaviour is a linear transition from left to right

Thanks


问:
What is the java keyevent field for windows icon?
```<code>public static void main(String[] args) throws InterruptedException {
        try {
            Robot robot = new Robot();
            robot.keyPress(KeyEvent.VK_***windowsicon***);
            } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
</code>```

I need to press windows icon key. But I could not find any virtual key command for or (KeyEvent.VK_windowsicon)  some similar command.

Thanks.

答:
I tried using KeyEvent.VK_WINDOWS. It is correct. but it is not suitable with my expected result. so I used this.

```<code>public static void main(String[] args) {
    try {
        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ESCAPE);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_ESCAPE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Body:
public static void main(String[] args) throws InterruptedException {
        try {
            Robot robot = new Robot();
            robot.keyPress(KeyEvent.VK_***windowsicon***);
            } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

I need to press windows icon key. But I could not find any virtual key command for or (KeyEvent.VK_windowsicon)  some similar command.

Thanks.

Body:
I tried using KeyEvent.VK_WINDOWS. It is correct. but it is not suitable with my expected result. so I used this.

public static void main(String[] args) {
    try {
        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ESCAPE);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_ESCAPE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}


问:
What happens when bitwise AND is applied to negative numbers?
I have written and compiled the following code:</p>
```<code>void main()
{
    printf("%d", -10 & 5);
}
</code>```

答:
In C, in the result of the binary &, each bit depends on the two corresponding bits in the operands. If the bit in the same position is set (1) in both operands, it is set in the result. If it is clear (0) in either operand, it is clear in the result. For example, given bits 0011 and 0101, the & operator would produce 0001, because only in the last position is the bit set in both operands.

You likely already know that positive integers are represented with binary. The bit positions are numbered starting from 0 on the “right”, then 1 for the next position, 2, 3, and so on. The bit in position i represents a value of 2i, so bit 0 represents 1, bit 1 represents 2, bit 2 represents 4, bit 3 represents 8, bit 4 represents 16, and so on. The value represented by all the bits is the sum of the values of the bits that are set to 1. So 101 represents 5, because the bits for 22 = 4 and 20 = 1 are set, and 4+1 = 5.

The C standard specifies three rules that a C implementation may use to represent negative numbers (in C 2018 6.2.6.2 2):

One of the bits represents a sign. If the sign bit is 0, the value is the same as above. If the sign bit is 1, the value is negated. So, if the first bit is the sign bit, then 5 is 0101 is 5, and −5 is 1101. This is called sign and magnitude.

One of the bits represents a sign, and, if a number is negative, all of the bits are inverted. So 5 is 0101, and −5 is 1010. This is called one’s complement.

One of the bits represents a sign, and, if the number is negative (let’s call it x), the bits are set in the pattern that would be used for 2N−x, where N is the number of bits. For example, for four bits, 2N = 16, and 5 is 0101, and −5 is represented with the bits for 16−5 = 11, which are 1011. This is called two’s complement.

In early computer hardware and software, all of the above were tried. The last, two’s complement, is overwhelming dominant in modern computing for integers. (Most floating-point uses sign and magnitude.) Nonetheless, the C standard still permits implementations to use any of the methods.

Because of this, the result of -10 & 5 is implementation-dependent. I will illustrate using eight bits, with a space to group them into two sets of four bits for visibility:

With two’s complement:

−10 is represented with 1111 0110 (256 − 10 = 246 = 128+64+32+16+4+2), 5 uses 0000 0101, and −10 & 5 is 0000 0100, which represents 4.

With one’s complement:

−10 is represented with 1111 0101, 5 uses 0000 0101, and −10 & 5 is 0000 0101, which represents 5.

With sign and magnitude:

−10 is represented with 1000 1010, 5 uses 0000 0101, and -10 & 5 is 0000 0000, which represents 0.

Thus, a C implementation that conforms to the C standard could produce 0, 4, or 5 for -10 & 5, but 4 is by far the most common result.

Body:
I have written and compiled the following code:

void main()
{
    printf("%d", -10 & 5);
}


问:
Newbie Q: Is there a best practice for custom "onChange" propname and callback parameters?
When I write my own custom components, I need to call one of the props supplied by the container to signal a change in the value handled by the component. But instead of an e event, I have a newValue handy. So I want to call it like this:

```<code>props.propname(newValue)
</code>```

Now, is there a React convention / best practice for propname?

For DOM inputs, the onChange prop gets called with an event parameter, typically named e. Its as if it gets called like this:

```<code>props.onChange(e)
</code>```

Should I:

Call the prop something other than onChange since it takes different parameters than onChange events for DOM elements. Something like: props.onMyComponentChange(newValue) (or whatever makes sense for the component).

Use the same name and call: props.onChange(newValue). Best practice is that the prop is called onChange, but it may take different parameters, depending on the component.

Create an e event somehow and still call onChange(e) (I haven't seen this in the wild)

I did a quick check for npm react components and saw a variety of 1. and 2. When writing new custom components, is there an established best practice for what to call such a prop?

答:
Think of props as no different than variable names... You should be as explicit with them as possible... Whether you're using classes or hooks under the hood even classes are still functions... Variables are function-scoped so you won't have any conflicts...

However, as your application grows you'll have a whole bunch of onSubmits and handleSubmits all over the place and will spend a bunch of time trying to figure out which one belongs to which component/container

Body:
When I write my own custom components, I need to call one of the props supplied by the container to signal a change in the value handled by the component. But instead of an e event, I have a newValue handy. So I want to call it like this:

props.propname(newValue)

Now, is there a React convention / best practice for propname?

For DOM inputs, the onChange prop gets called with an event parameter, typically named e. Its as if it gets called like this:

props.onChange(e)

Should I:

Call the prop something other than onChange since it takes different parameters than onChange events for DOM elements. Something like: props.onMyComponentChange(newValue) (or whatever makes sense for the component).

Use the same name and call: props.onChange(newValue). Best practice is that the prop is called onChange, but it may take different parameters, depending on the component.

Create an e event somehow and still call onChange(e) (I haven't seen this in the wild)

I did a quick check for npm react components and saw a variety of 1. and 2. When writing new custom components, is there an established best practice for what to call such a prop?


问:
How to solve Notice: Undefined index: id in Undefined index: id in detailsmodal.php on line 3
I have a problem with my PHP code saying that

"Notice: Undefined index"

since I am a beginner i am not getting well what is wrong exactly so please help me.

```<code><?php
    require_once 'core/init.php';
    $id = $_POST['id'];
    $id =(int)$id;

    $sql ="SELECT * FROM products WHERE id = '$id'";
    $result = $db->query($sql);
    $product= mysqli_fetch_assoc($result);

    $brand_id = $product['brand'];
    $sql = "SELECT brand FROM brand WHERE id = '$brand_id'";
    $brand_query = $db->query($sql);
    $brand = mysqli_fetch_assoc($brand_query);
?>
</code>```

//index.php

```<code><?php
      require_once 'core/init.php';
      include 'includes/head.php';
      include 'includes/navigation.php';
      include 'includes/headerfull.php';
      include 'includes/leftbar.php';
      include 'includes/footer.php';
      include 'includes/detailsmodal.php';

      $sql = "SELECT * FROM products WHERE featured = 1";
      $featured = $db->query($sql);
?>
        <!--main content-->
        <div class="col-md-8">
        <div class="row">
        <h2 class="text-center">Feature products</h2>
        <?php while($product = mysqli_fetch_assoc($featured)) : ?>
        <div class="col-md-3 text-center">
            <h4><?= $product['title']; ?> </h4>
            <img src="<?= $product['image']; ?>" alt="<?= $product['title']; ?>" class="img-thumb" />
            <p class="list-price text-danger">List price:<s>$<?= $product['list_price']; ?></s></p>
            <p class="price">Our price :$<?= $product['price']; ?></p>
        <button type="button" class="btn btn-sm btn-success" onclick="detailsmodal(<?= $product['id']; ?>)">Details</button>
        </div>

        <?php endwhile ;?>
        </div>
    <footer class="text-center" id="footer">© copyright 2019</footer>

     </div>

    <?php
        include 'includes/rightsidebar.php';
        include 'includes/footer.php';

    ?>
</code>```

Undefined index: id in
  C:\xampp\htdocs\tutorial\includes\detailsmodal.php on line 3

答:
in detailsmodal.php file index $_POST['id'] is not defined

first check if is set do job ....

```<code>if(isset($_POST['id'])){
   code...
}else{
   code...
}
</code>```

or

```<code>$id = isset($_POST['id']) ? $_POST['id'] : null;
</code>```

Body:
I have a problem with my PHP code saying that

"Notice: Undefined index"

since I am a beginner i am not getting well what is wrong exactly so please help me.

<?php
    require_once 'core/init.php';
    $id = $_POST['id'];
    $id =(int)$id;

    $sql ="SELECT * FROM products WHERE id = '$id'";
    $result = $db->query($sql);
    $product= mysqli_fetch_assoc($result);

    $brand_id = $product['brand'];
    $sql = "SELECT brand FROM brand WHERE id = '$brand_id'";
    $brand_query = $db->query($sql);
    $brand = mysqli_fetch_assoc($brand_query);
?>

//index.php

<?php
      require_once 'core/init.php';
      include 'includes/head.php';
      include 'includes/navigation.php';
      include 'includes/headerfull.php';
      include 'includes/leftbar.php';
      include 'includes/footer.php';
      include 'includes/detailsmodal.php';

      $sql = "SELECT * FROM products WHERE featured = 1";
      $featured = $db->query($sql);
?>

Feature products

        <?php while($product = mysqli_fetch_assoc($featured)) : ?>

<?= $product['title']; ?>

            <img src="<?= $product['image']; ?>" alt="<?= $product['title']; ?>" class="img-thumb" />

List price:<s>$<?= $product['list_price']; ?></s>

Our price :$<?= $product['price']; ?>

        <button type="button" class="btn btn-sm btn-success" onclick="detailsmodal(<?= $product['id']; ?>)">Details</button>

        <?php endwhile ;?>

    © copyright 2019

    <?php
        include 'includes/rightsidebar.php';
        include 'includes/footer.php';

    ?>

Undefined index: id in
  C:\xampp\htdocs\tutorial\includes\detailsmodal.php on line 3

Body:
in detailsmodal.php file index $_POST['id'] is not defined

first check if is set do job ....

if(isset($_POST['id'])){
   code...
}else{
   code...
}

or

$id = isset($_POST['id']) ? $_POST['id'] : null;


问:
Django django_suit : how to create two-level menu?
Django 2.2, django-suit==0.2.26
This is more django_suit question rather then django.

I have a flat menu defined in my settings.py, each item is a link in admin view:

```<code>SUIT_CONFIG = {
    'ADMIN_NAME': 'MyAdminName',
    'MENU': (
        'sites',
        '-',
        {
         'label': 'MenuItem1',
         'url': SCRIPT_NAME + '/some_view1',
        },
        {
         'label': 'MenuItem2',
         'url': SCRIPT_NAME + '/some_view2',
        },
        {
         'label': 'MenuItem3',
         'url': SCRIPT_NAME + '/some_view3',
        }
    }
}
</code>```

I would like to make it work as two level menu that opens on mouseover.

It can be easily done for the application's models like this:

```<code>SUIT_CONFIG = {
    'ADMIN_NAME': 'MyAdminName',
    'MENU': (
        'sites',
        '-',
        {'app': 'MyApp',
         'label': 'MenuLabelTopLevel',
         'models': ('MyModel1', 'MyModel2', 'MyModel3')
        }
    }
}
</code>```

When I position the mouse over MenuLabelTopLevel, I get a dropdown with 'MyModel1', 'MyModel2', 'MyModel3'.

I am looking for the syntax that would allow me to have the same functionality for any arbitrary list of views in my application, something line this:

```<code>SUIT_CONFIG = {
    'ADMIN_NAME': 'MyAdminName',
    'MENU': (
        'sites',
        '-',
        {'app': 'MyApp',
         'label': 'MenuLabelTopLevel',
         'link_list': (SCRIPT_NAME + '/some_view1',SCRIPT_NAME + '/some_view2', SCRIPT_NAME + '/some_view3')
        }
    }
}
</code>```

Does this functionality exist in django_suit? The docs do not have an example for this. If not, maybe some similar django package (that would allow me to do it in my existing admin menu, not to create some new menu at the top of the page)?

Thanks

答:
I found a way to do that. No new keyword is needed, you just stick those into "models" as list of "label and url" key-value dictionaries.

```<code>SUIT_CONFIG = {
    'ADMIN_NAME': 'MyAdminName',
    'MENU': (
        {'label': 'MenuLabelTopLevel',
            'models': [
                {
                    'label': 'SubMenuItem1',
                    'url': SCRIPT_NAME + '/some_view1',
                },
                {
                    'label': 'SubMenuItem1',
                    'url': SCRIPT_NAME + '/some_view1',
                 }
            ]
        }
    )
</code>```

Just one minor inconvenience: separator ( '-' ) is ignored in the list of those second-level items.

Body:
Django 2.2, django-suit==0.2.26
This is more django_suit question rather then django.

I have a flat menu defined in my settings.py, each item is a link in admin view:

SUIT_CONFIG = {
    'ADMIN_NAME': 'MyAdminName',
    'MENU': (
        'sites',
        '-',
        {
         'label': 'MenuItem1',
         'url': SCRIPT_NAME + '/some_view1',
        },
        {
         'label': 'MenuItem2',
         'url': SCRIPT_NAME + '/some_view2',
        },
        {
         'label': 'MenuItem3',
         'url': SCRIPT_NAME + '/some_view3',
        }
    }
}

I would like to make it work as two level menu that opens on mouseover.

It can be easily done for the application's models like this:

SUIT_CONFIG = {
    'ADMIN_NAME': 'MyAdminName',
    'MENU': (
        'sites',
        '-',
        {'app': 'MyApp',
         'label': 'MenuLabelTopLevel',
         'models': ('MyModel1', 'MyModel2', 'MyModel3')
        }
    }
}

When I position the mouse over MenuLabelTopLevel, I get a dropdown with 'MyModel1', 'MyModel2', 'MyModel3'.

I am looking for the syntax that would allow me to have the same functionality for any arbitrary list of views in my application, something line this:

SUIT_CONFIG = {
    'ADMIN_NAME': 'MyAdminName',
    'MENU': (
        'sites',
        '-',
        {'app': 'MyApp',
         'label': 'MenuLabelTopLevel',
         'link_list': (SCRIPT_NAME + '/some_view1',SCRIPT_NAME + '/some_view2', SCRIPT_NAME + '/some_view3')
        }
    }
}

Does this functionality exist in django_suit? The docs do not have an example for this. If not, maybe some similar django package (that would allow me to do it in my existing admin menu, not to create some new menu at the top of the page)?

Thanks

Body:
I found a way to do that. No new keyword is needed, you just stick those into "models" as list of "label and url" key-value dictionaries.

SUIT_CONFIG = {
    'ADMIN_NAME': 'MyAdminName',
    'MENU': (
        {'label': 'MenuLabelTopLevel',
            'models': [
                {
                    'label': 'SubMenuItem1',
                    'url': SCRIPT_NAME + '/some_view1',
                },
                {
                    'label': 'SubMenuItem1',
                    'url': SCRIPT_NAME + '/some_view1',
                 }
            ]
        }
    )

Just one minor inconvenience: separator ( '-' ) is ignored in the list of those second-level items.


问:
return after while loop in python
This loop is supposed to return the sum of even numbers from 0 to 200 inclusive.
I have tried adding tabs but each addition results in some error itself

```<code>i = 0
total = 0

while i >= 0 and i <= 200:
    total = total + i
    i = i + 2

return total
</code>```

IDLE tells me " 'return' outside function".

答:
The while loop changes the variable total itself. So there is no need to return it here.

You can use the following print command to write out your result:

print(total)

Title: return after while loop in python

Body:
This loop is supposed to return the sum of even numbers from 0 to 200 inclusive.
I have tried adding tabs but each addition results in some error itself

i = 0
total = 0

while i >= 0 and i <= 200:
    total = total + i
    i = i + 2

return total

IDLE tells me " 'return' outside function".


问:
How do I bring a PyGTK Button to the front?
I have a gtk.Table to which I've attached a number of gtk.Buttons, some of which overlap others.  I can't figure out how to bring a specific button to the front, however.  How do I do it?</p>

答: You could try to use the Clutter toolkit, I believe this is more suitable for putting widgets on surfaces that you can then animate and move around. It's also built on the same technology as GTK, so it won't be too unfamiliar.</p>


问:
parfeval slower than parfor
I'm comparing execution times between two blocks, one using parfor the other doing the same thing by issuing parfeval and fetching outputs:

```<code>parfor k = 1:N
    a = rand(5000);
    b = inv(a);
end
</code>```

vs.

```<code>for k = 1:N
    a = rand(5000);
    F(k) = parfeval(p,'inv',1,a);
end
for k = 1:N
    [completedIdx,value] = fetchNext(F);
    fprintf(1,'%d   ',completedIdx);
end
</code>```

The parfor is consistently faster. Any insights into why that is the case? My simplistic understanding is parfor essentially runs each loop as a parallel job.

答:
Any difference between the two is likely driven by the fact that you are not parallelizing the inverse in the second case.

For me the following two options take the same amount of time.

Init:

```<code>p = gcp;
N = p.NumWorkers;
</code>```

Option A:

```<code>tic;
b = zeros( N, 1 );
parfor k = 1 : N;
    b( k ) = max( max( abs( inv( rand( 5000 ) ) ) ) );
end;
toc;
</code>```

Option B:

```<code>tic;
F = repmat(parallel.FevalFuture,N,1);
for k = 1:N;
    F(k) = parfeval( p, @() max( max( abs( inv( rand( 5000 ) ) ) ) ), 1 );
end;
b = fetchOutputs( F );
toc;
</code>```

Title: parfeval slower than parfor

Body:
I'm comparing execution times between two blocks, one using parfor the other doing the same thing by issuing parfeval and fetching outputs:

parfor k = 1:N
    a = rand(5000);
    b = inv(a);
end

vs.

for k = 1:N
    a = rand(5000);
    F(k) = parfeval(p,'inv',1,a);
end
for k = 1:N
    [completedIdx,value] = fetchNext(F);
    fprintf(1,'%d   ',completedIdx);
end

The parfor is consistently faster. Any insights into why that is the case? My simplistic understanding is parfor essentially runs each loop as a parallel job.

Body:
Any difference between the two is likely driven by the fact that you are not parallelizing the inverse in the second case.

For me the following two options take the same amount of time.

Init:

p = gcp;
N = p.NumWorkers;

Option A:

tic;
b = zeros( N, 1 );
parfor k = 1 : N;
    b( k ) = max( max( abs( inv( rand( 5000 ) ) ) ) );
end;
toc;

Option B:

tic;
F = repmat(parallel.FevalFuture,N,1);
for k = 1:N;
    F(k) = parfeval( p, @() max( max( abs( inv( rand( 5000 ) ) ) ) ), 1 );
end;
b = fetchOutputs( F );
toc;


问:
jQuery, get ID of a textarea
I've got a form with a text field defined as follow:

```<code><textarea style="height: 60px; width: 100%;" name="F3414" id="F3414" rows="6" cols="80" wrap="virtual" class="frmTxa fckEditor"></textarea>
</code>```

I need, using jQuery, to get the textarea id (in that case, F3414).

I've tried:

```<code>$('textarea .fckEditor').attr('id');
$('.fckEditor').attr('id'); / ... with no luck.
</code>```

Any idea?

Thanks a lot

答:
If you are using the textarea as an editor, it won't be rendered as a textarea once the plugin is applied. It might be an iframe with content editable set to on.

Inspect the page source using firebug and try to find out the HTML structure.

Title: jQuery, get ID of a textarea

Body:
I've got a form with a text field defined as follow:

<textarea style="height: 60px; width: 100%;" name="F3414" id="F3414" rows="6" cols="80" wrap="virtual" class="frmTxa fckEditor"></textarea>

I need, using jQuery, to get the textarea id (in that case, F3414).

I've tried:

$('textarea .fckEditor').attr('id');
$('.fckEditor').attr('id'); / ... with no luck.

Any idea?

Thanks a lot


问:
Change the Return-Path in PHP mail function
Is it possible to change the Return-Path value in emails are sending via mail() function of PHP ?

It's value is 'www-data@mydomain.com' in emails I send in my site and it causes some problems on email delivery failed process. I want to set it to my email address.

Here's the code I have tried:

```<code>$headers = 'MIME-Version: 1.0' . "\n";
$headers .= "Content-type: text/html; charset=utf-8" . "\n";
$headers .= "Return-Path: <adminemail@yahoo.com>"."\n";
$headers .= "Errors-To: <adminemail@yahoo.com>"."\n";
// Additional headers
$headers .= "To: email1@yahoo.com <adminemail@yahoo.com>" . "\n";
$headers .= "From: adminemail@yahoo.com <adminemail@yahoo.com>";
// Mail it
mail('email1@yahoo.com', 'test', 'salam', $headers, "f");
</code>```

答:
Just define Return-Path

$returnPath = "-fadminemail@yahoo.com"; //-f will do the job
mail('email1@yahoo.com', 'test', 'salam', $headers, $returnPath);
```

Body:
Is it possible to change the Return-Path value in emails are sending via mail() function of PHP ?

It's value is 'www-data@mydomain.com' in emails I send in my site and it causes some problems on email delivery failed process. I want to set it to my email address.

Here's the code I have tried:

$headers = 'MIME-Version: 1.0' . "\n";
$headers .= "Content-type: text/html; charset=utf-8" . "\n";
$headers .= "Return-Path: <adminemail@yahoo.com>"."\n";
$headers .= "Errors-To: <adminemail@yahoo.com>"."\n";
// Additional headers
$headers .= "To: email1@yahoo.com <adminemail@yahoo.com>" . "\n";
$headers .= "From: adminemail@yahoo.com <adminemail@yahoo.com>";
// Mail it
mail('email1@yahoo.com', 'test', 'salam', $headers, "f");


问:
React Native android set state array not working
Android Set state array not working.
React-native MapView componentWillMount update state set map position not working. Help me please.

States :

```<code>constructor(props) {
    super(props);
    this.state = {
        loading: '',
        mapRegion: {
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        },
        location: {
          coords: {
            latitude: 37.78825,
            longitude: -122.4324,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }
        }
    };
  }
</code>```

component Will Mount

```<code>async componentWillMount() {
this.setState({
          mapRegion: {
            latitude: responseJson.latitude,
            longitude: responseJson.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          },
          location: {
            coords: {
              latitude: responseJson.latitude,
              longitude: responseJson.longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }
          },
 });
}
</code>```

Return view not change position

```<code><MapView style={{ width: '100%', height: '100%' }}
region={{
     latitude: this.state.location.coords.latitude,
     longitude: this.state.location.coords.longitude,
     latitudeDelta: 3,
      longitudeDelta: 3
 }}
zoomEnabled = {true}>
<MapView.Marker coordinate={this.state.location.coords} title={strings('Location.Buradasiniz')} />
<MapView.Circle center={this.state.location.coords} radius={this.state.radius} strokeColor='red' fillColor="rgba(255, 0, 0, 0.20)"/></MapView>
</code>```

答:
Try this:

```<code>async componentWillMount() {
await this.setState({
          mapRegion: {
            latitude: responseJson.latitude,
            longitude: responseJson.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          },
          location: {
            coords: {
              latitude: responseJson.latitude,
              longitude: responseJson.longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }
          },
 });
}
</code>```

When You use async after that You must write await somewhere, here is the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Or try without async await like this:

```<code>componentWillMount() {
 this.setState({
          mapRegion: {
            latitude: responseJson.latitude,
            longitude: responseJson.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          },
          location: {
            coords: {
              latitude: responseJson.latitude,
              longitude: responseJson.longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }
          },
 });
}
</code>```

Good luck))

Body:
Android Set state array not working.
React-native MapView componentWillMount update state set map position not working. Help me please.

States :

constructor(props) {
    super(props);
    this.state = {
        loading: '',
        mapRegion: {
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        },
        location: {
          coords: {
            latitude: 37.78825,
            longitude: -122.4324,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }
        }
    };
  }

component Will Mount

async componentWillMount() {
this.setState({
          mapRegion: {
            latitude: responseJson.latitude,
            longitude: responseJson.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          },
          location: {
            coords: {
              latitude: responseJson.latitude,
              longitude: responseJson.longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }
          },
 });
}

Return view not change position

<MapView style={{ width: '100%', height: '100%' }}
region={{
     latitude: this.state.location.coords.latitude,
     longitude: this.state.location.coords.longitude,
     latitudeDelta: 3,
      longitudeDelta: 3
 }}
zoomEnabled = {true}>
<MapView.Marker coordinate={this.state.location.coords} title={strings('Location.Buradasiniz')} />
<MapView.Circle center={this.state.location.coords} radius={this.state.radius} strokeColor='red' fillColor="rgba(255, 0, 0, 0.20)"/></MapView>

Body:
Try this:

async componentWillMount() {
await this.setState({
          mapRegion: {
            latitude: responseJson.latitude,
            longitude: responseJson.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          },
          location: {
            coords: {
              latitude: responseJson.latitude,
              longitude: responseJson.longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }
          },
 });
}

When You use async after that You must write await somewhere, here is the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Or try without async await like this:

componentWillMount() {
 this.setState({
          mapRegion: {
            latitude: responseJson.latitude,
            longitude: responseJson.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          },
          location: {
            coords: {
              latitude: responseJson.latitude,
              longitude: responseJson.longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }
          },
 });
}

Good luck))


问:
Image moving to folder but not saving the row in database
Everything was working fine until i decided to add a new product and nothing works , the picture is uploading to the folder but the problem is coming from the move_uploaded_file function , the thing is the function is working and moving pictures but the code is not moving to the next instruction does anyone have an idea about this error ?</p>

```<code><?php
if ($_POST) {
    $productName   = $_POST['productName'];
    $quantity      = $_POST['quantity'];
    $rate          = $_POST['rate'];
    $brandName     = $_POST['brandName'];
    $categoryName  = $_POST['categoryName'];
    $genderName    = $_POST['genderName'];
    $sizeName      = $_POST['sizeName'];
    $productStatus = $_POST['productStatus'];
    $type = explode('.', $_FILES['productImage']['name']);
    $type = $type[count($type) - 1];
    $url  = '../assests/images/stock/' . uniqid(rand()) . '.' . $type;
    if (in_array($type, ['gif', 'jpg', 'jpeg', 'png', 'JPG', 'GIF', 'JPEG', 'PNG'])) {
        if (is_uploaded_file($_FILES['productImage']['tmp_name'])) {
            if (move_uploaded_file($_FILES['productImage']['tmp_name'], $url)) {
                $sql = "INSERT INTO product (product_name, product_image, brand_id, categories_id, quantity, price, active, status,gender_id,size_id,description,dateadded,discount)
                VALUES ('$productName', '$url', '$brandName', '$categoryName', '$quantity', '$rate', '$productStatus', 1,'$genderName','$sizeName')";
                if ($connect->query($sql) === true) {
                    echo "<SCRIPT type='text/javascript'> //not showing me this
        alert('Product added !');
        window.location.replace(\"http://localhost/stock/product.php\");
        </SCRIPT>";
                } else {
                    $valid['success']  = false;
                    $valid['messages'] = "Error while adding the members";
                }
            } else {
                echo "lool";
            }
        }
    }
    $connect->close();
}
?>
</code>```

答:
I don't see the variable $connect declared anywhere in your code. It is possible that you have error reporting disabled and the script dies on

```<code>if ($connect->query($sql) === true) {
</code>```

because $connect is undefined?

Body:
Everything was working fine until i decided to add a new product and nothing works , the picture is uploading to the folder but the problem is coming from the move_uploaded_file function , the thing is the function is working and moving pictures but the code is not moving to the next instruction does anyone have an idea about this error ?

<?php
if ($_POST) {
    $productName   = $_POST['productName'];
    $quantity      = $_POST['quantity'];
    $rate          = $_POST['rate'];
    $brandName     = $_POST['brandName'];
    $categoryName  = $_POST['categoryName'];
    $genderName    = $_POST['genderName'];
    $sizeName      = $_POST['sizeName'];
    $productStatus = $_POST['productStatus'];
    $type = explode('.', $_FILES['productImage']['name']);
    $type = $type[count($type) - 1];
    $url  = '../assests/images/stock/' . uniqid(rand()) . '.' . $type;
    if (in_array($type, ['gif', 'jpg', 'jpeg', 'png', 'JPG', 'GIF', 'JPEG', 'PNG'])) {
        if (is_uploaded_file($_FILES['productImage']['tmp_name'])) {
            if (move_uploaded_file($_FILES['productImage']['tmp_name'], $url)) {
                $sql = "INSERT INTO product (product_name, product_image, brand_id, categories_id, quantity, price, active, status,gender_id,size_id,description,dateadded,discount)
                VALUES ('$productName', '$url', '$brandName', '$categoryName', '$quantity', '$rate', '$productStatus', 1,'$genderName','$sizeName')";
                if ($connect->query($sql) === true) {
                    echo "";
                } else {
                    $valid['success']  = false;
                    $valid['messages'] = "Error while adding the members";
                }
            } else {
                echo "lool";
            }
        }
    }
    $connect->close();
}
?>

Body:
I don't see the variable $connect declared anywhere in your code. It is possible that you have error reporting disabled and the script dies on

if ($connect->query($sql) === true) {

because $connect is undefined?


问:
jquery stop event bubbling with live
I have this code

```<code> var input = $("form input[name='name'].dhxlist_txt_textarea");

 $(input).live('click', function () {

       ShowLookupGrid();
 });
</code>```

Then I've putted a second live binding before the first get executed

```<code>  $('#Id').live('click', function () {

       return false;
 });
</code>```

But the return false statement isn't stoping bubbling up the event to the second binding.

答:
This should stop any other events of the same type being fired on that element as long as it is the first event handler that is run.

```<code>$('#Id').live('click', function (event) {
   event.stopImmediatePropagation()
});
</code>```

JSFiddle Example

Title: jquery stop event bubbling with live

Body:
I have this code

 var input = $("form input[name='name'].dhxlist_txt_textarea");

 $(input).live('click', function () {

       ShowLookupGrid();
 });

Then I've putted a second live binding before the first get executed

  $('#Id').live('click', function () {

       return false;
 });

But the return false statement isn't stoping bubbling up the event to the second binding.

Body:
This should stop any other events of the same type being fired on that element as long as it is the first event handler that is run.

$('#Id').live('click', function (event) {
   event.stopImmediatePropagation()
});

JSFiddle Example


问:
SELECT with JOIN -> I want to combine these tables with JOIN
I have 4 tables:

```<code>1) tw_Towar: -> tw_Id, tw_Nazwa,tw_SklepInternet
2) tw_Cena: -> tc_Id, tc_CenaNetto1
3) tw_Stan: -> st_TowId, st_Stan
4) tw_ZdjecieTw: -> zd_IdTowar, zd_Glowne
</code>```

I want to combine these tables with JOIN:

First column is part ID , others are properties of part.

I need to get out(SELECT): tw_Nazwa, tc_CenaNetto1, st_Stan, zd_Glowne

Thanks

答:
As above, you should try to do it first, then come back with the error/exception you encountered. Do you use any framework? You will want to set JOIN on something:
w3schools
Tutotorial for php join</p>

Body:
I have 4 tables:

1) tw_Towar: -> tw_Id, tw_Nazwa,tw_SklepInternet
2) tw_Cena: -> tc_Id, tc_CenaNetto1
3) tw_Stan: -> st_TowId, st_Stan
4) tw_ZdjecieTw: -> zd_IdTowar, zd_Glowne

I want to combine these tables with JOIN:

First column is part ID , others are properties of part.

I need to get out(SELECT): tw_Nazwa, tc_CenaNetto1, st_Stan, zd_Glowne

Thanks


问:
C# How to use one method for two classes with Generic type?
I need to merge two different print method into one. I have two generic classes and my own generic list class.
Let's say I have

```<code>static void Print(string fv, MyListClass<Module> A,
            string top)
 and static void Print2(string fv, MyListClass<Student> A,
            string top)
</code>```

Inside of the method is the same, but how to make them to be one method and in Main class I choose in parameters which one class list am I printing, Module either Student. My data is in:

```<code>MyListClass<Student> Stud;
MyListClass<Module> Mod;
</code>```

答: To do that, you simply create a base class, derive both Module and Student class from it, and then use the base class in the signature of the single method.</p>

Body:
I need to merge two different print method into one. I have two generic classes and my own generic list class.
Let's say I have

static void Print(string fv, MyListClass<Module> A,
            string top)
 and static void Print2(string fv, MyListClass<Student> A,
            string top)

Inside of the method is the same, but how to make them to be one method and in Main class I choose in parameters which one class list am I printing, Module either Student. My data is in:

MyListClass<Student> Stud;
MyListClass<Module> Mod;


问:
"cors header ‘access-control-allow-origin’ missing" denies request, even though origin is allowed
I want to a send POST request from my angular app to my server (written with spring-boot). The request gets denied with the message "cors header ‘access-control-allow-origin’ missing".

I enabled the origin of my angular app "http://localhost:4200" like I did for my other RestControllers (Which work). The only difference as far as I can tell is that I handel POST requests in my not working controller.

Controller

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class Controller {

    @Autowired
    private ReqRepository reqRepository;

    @PostMapping("/reqs")
    public Req saveReq (@Valid @RequestBody Req req) {
        return reqRepository.save(req);
    }
}
```

<h3>Repository</h3>

<pre class="lang-java prettyprint-override"><code>@Repository
public interface ReqRepository extends JpaRepository<Req, Long> {
}
</code>```

Angular Service

@Injectable()
export class ReqService {

  private httpOptions = {
    headers: new HttpHeaders({
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json'
    })
};

  constructor(private http: HttpClient) {}

  sendReq(req: Req): Observable<Req> {
    return this.http.post<Req>('http://localhost:8080/reqs', req, this.httpOptions);
  }
}
```

<p>I thought allowing the origin would be enough so the request is possible but it get's blocked. It seems like I am missing something to enable POST requests.</p>

<h3>Update</h3>

<p>I further tested the controller and it works for GET requests.
I just change the the method, so it seems like the problem lies in the POST request.
Below ist the controller with a GET test endpoint instead of a POST endpoint</p>

<pre class="lang-java prettyprint-override"><code>@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class Controller {

    @Autowired
    private ReqRepository reqRepository;

    @GetMapping("/reqs")
    public Page<Req> testCall (Pageable pageable) {
        System.out.println("Geeting request");
        return reqRepository.findAll(pageable);
    }
}
</code>```

答:
The problem was my spring security configuration.
I had to disable csrf because it is enabled by default.
I got the solution from this post: How to Solve 403 Error in Spring Boot Post Request

My solution looks like this:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //Override basic security settings so no login page is needed to access the RestEndpoints
    @Override
    protected void configure(HttpSecurity security) throws Exception
    {
        security.httpBasic().disable();
        security.csrf().disable();
    }
}
```

Body:
I want to a send POST request from my angular app to my server (written with spring-boot). The request gets denied with the message "cors header ‘access-control-allow-origin’ missing".

I enabled the origin of my angular app "http://localhost:4200" like I did for my other RestControllers (Which work). The only difference as far as I can tell is that I handel POST requests in my not working controller.

Controller

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class Controller {

    @Autowired
    private ReqRepository reqRepository;

    @PostMapping("/reqs")
    public Req saveReq (@Valid @RequestBody Req req) {
        return reqRepository.save(req);
    }
}

Repository

@Repository
public interface ReqRepository extends JpaRepository<Req, Long> {
}

Angular Service

@Injectable()
export class ReqService {

  private httpOptions = {
    headers: new HttpHeaders({
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json'
    })
};

  constructor(private http: HttpClient) {}

  sendReq(req: Req): Observable<Req> {
    return this.http.post<Req>('http://localhost:8080/reqs', req, this.httpOptions);
  }
}

I thought allowing the origin would be enough so the request is possible but it get's blocked. It seems like I am missing something to enable POST requests.

Update

I further tested the controller and it works for GET requests.
I just change the the method, so it seems like the problem lies in the POST request.
Below ist the controller with a GET test endpoint instead of a POST endpoint

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class Controller {

    @Autowired
    private ReqRepository reqRepository;

    @GetMapping("/reqs")
    public Page<Req> testCall (Pageable pageable) {
        System.out.println("Geeting request");
        return reqRepository.findAll(pageable);
    }
}


问:
Is CrudRepository.save(Iterable<S>) is atomic?
I am saving multiple objects using CrudRepository.save(Iterable<S>).

is this operation behaviour is atomic?

What will happen if I save 10 entities and it fails for 6th one?

答:
Yes, It is atomic. SimpleJpaRepository is the default implementation for the interface CrudRepository. The save method is annotated with Transactional at the implementation. So in case of any error, everything will be rolled back.

```<code>@Transactional
public <S extends T> List<S> save(Iterable<S> entities) {
    List<S> result = new ArrayList();
    if (entities == null) {
        return result;
    } else {
        Iterator var3 = entities.iterator();

        while(var3.hasNext()) {
            S entity = var3.next();
            result.add(this.save(entity));
        }

        return result;
    }
}
</code>```

Body:
Yes, It is atomic. SimpleJpaRepository is the default implementation for the interface CrudRepository. The save method is annotated with Transactional at the implementation. So in case of any error, everything will be rolled back.

@Transactional
public <S extends T> List<S> save(Iterable<S> entities) {
    List<S> result = new ArrayList();
    if (entities == null) {
        return result;
    } else {
        Iterator var3 = entities.iterator();

        while(var3.hasNext()) {
            S entity = var3.next();
            result.add(this.save(entity));
        }

        return result;
    }
}


答:
I have two generic classes and my own generic list class.

Why do you have your own list class? You generally shouldn't. Assuming it implements IEnumerable<T>:

Let both Module and Student implement a common interface with the properties you want to print, say IPrintable:

```<code>public interface IPrintable
{
    string Name { get; }
    string Description { get; }
}

public class Module : IPrintable { ... }
public class Student : IPrintable { ... }
</code>```

Now create a method with a generic parameter:

```<code>void Print<T>(string fv, IEnumerable<T> A, string top)
    where T : IPrintable
{
    foreach (var item in A)
    {
        Console.WriteLine(item.Name + ": " + item.Description);
    }
}
</code>```

Title: C# How to use one method for two classes with Generic type?

Body:
I have two generic classes and my own generic list class.

Why do you have your own list class? You generally shouldn't. Assuming it implements IEnumerable<T>:

Let both Module and Student implement a common interface with the properties you want to print, say IPrintable:

public interface IPrintable
{
    string Name { get; }
    string Description { get; }
}

public class Module : IPrintable { ... }
public class Student : IPrintable { ... }

Now create a method with a generic parameter:

void Print<T>(string fv, IEnumerable<T> A, string top)
    where T : IPrintable
{
    foreach (var item in A)
    {
        Console.WriteLine(item.Name + ": " + item.Description);
    }
}


问:
How can I use testcafe to intercept and mock websocket requests
I am trying to override some websockets requests for functional testing purposes.

I have tried using intercepts and mocking as advised here https://devexpress.github.io/testcafe/documentation/test-api/intercepting-http-requests/ however this only seems straightforward for HTTP and can only update status code in WSS. The messages in the WSS is in JSON which I need to override.

```<code>import { RequestMock } from 'testcafe';
import { debug } from 'util';

const mockStream = new RegExp('test\/socket.io\/v2\/.?');

const ipUrl = 'https://example.com';
const mockedResponse = Buffer.from([0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01]);

const mock = RequestMock()
    .onRequestTo(mockStream)
    .respond(mockedResponse, 101, {
        'access-control-allow-credentials': true,
    });

fixture `Fixture`
    .page(ipUrl)
    .requestHooks(mock);
test('Mocking', async t => {
    await t
    .debug()
        .click('#button')
        .wait(5000)
        .debug();
});
</code>```

答:
At present, it's not possible to intercept WebSocket requests.
I've created an issue for this case in the TestCafe repository.
Track it to be informed about our progress with implementing this feature.</p>

Body:
I am trying to override some websockets requests for functional testing purposes.

I have tried using intercepts and mocking as advised here https://devexpress.github.io/testcafe/documentation/test-api/intercepting-http-requests/ however this only seems straightforward for HTTP and can only update status code in WSS. The messages in the WSS is in JSON which I need to override.

import { RequestMock } from 'testcafe';
import { debug } from 'util';

const mockStream = new RegExp('test\/socket.io\/v2\/.?');

const ipUrl = 'https://example.com';
const mockedResponse = Buffer.from([0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01]);

const mock = RequestMock()
    .onRequestTo(mockStream)
    .respond(mockedResponse, 101, {
        'access-control-allow-credentials': true,
    });

fixture `Fixture`
    .page(ipUrl)
    .requestHooks(mock);
test('Mocking', async t => {
    await t
    .debug()
        .click('#button')
        .wait(5000)
        .debug();
});


问:
How can I change Apollo Server WS path?
Is there any way to change path of Apollo Server WS (server.subscriptionsPath)?

Default path is '/graphql'. How can I set other route, e.g. 'ws://localhost:3000/api'?

import express from 'express'
import http from 'http'
import { ApolloServer } from 'apollo-server-express'

const app = express()

// ...

const server = new ApolloServer({
  typeDefs,
  resolvers,
})

const httpServer = http.createServer(app)
server.installSubscriptionHandlers(httpServer)

console.log('server.graphqlPath', server.graphqlPath)
console.log('server.subscriptionsPath', server.subscriptionsPath)

httpServer.listen({ port:300 })
```

答:
You can include a subscriptions object in your ApolloServer config with the following properties:

path:

keepAlive:

onConnect:

onDisconnect:

subscriptions may also just be a string, in which case it's used just to define the path, or you can pass in false to disable subscriptions altogether.

See the docs for all the configuration options.

Title: How can I change Apollo Server WS path?


问:
How to pass an array from an api as props to another component
I am making an api call which returns me an array of Usernames. I am calling the api in a Navbar component and am sending the data returned by the api to another component as props. When I console.log(this.state.Name) in Navbar it gives the whole array having usernames in the console, but when i receive the array in the other SearchedUser componenet and console.log() the recieved prop it gives me undefined in the console. Can Anyone tell whats wrong.

----------------------------------Navbar Component----------------------------

```<code>     class Navbar extends Component{

     constructor(props){
    super(props);
    this.state={
        name:'',
        Name:[],
    }
     this.GetUserData=this.GetUserData.bind(this);
}

    GetUserData=()=>{
fetch(`http://localhost:4000/data/searchuser?Name=${this.state.name}`)
.then(response => response.json())
.then(data=> this.setState({Name:data.datad}))
.catch(err=>console.log(err));}

        render()
{
    console.log(this.state.Name);
    return(
        <Router>
          <Link to={'/SearchedUser'}>
                <button type="submit" onClick={this.GetUserData}><i className="fa fa-search"></i></button>
         </Link>
            <Switch>
                <Route exact path='/' component={HomeContent} />
                <Route path='/Profile' component={Profile}/>
                <Route path='/SearchedUser' render={(props)=> <SearchedUser {...props} UserName={ [this.state.Name]}/>}/>
            </Switch>
        </Router>)  }}
</code>```

--------------------------------SearchedUser Component------------------------

```<code>    import React from 'react'
class SearchedUser extends React.Component{
constructor(props){
super(props);
this.state={
    Name: props.UserName
}
    }

    render(){
console.log(this.state.Name);
return(
    <div>
    </div>
     )
    }
    }
export default SearchedUser;
</code>```

答:
Can you try with 2 changes like:

[this.state.Name] > this.state.Name as the first one outputs an array with single entry like ['sara']:

```<code><SearchedUser {...props} UserName={this.state.Name}/>}
</code>```

Another thing, in the constructor of NavBar component:

```<code> this.state={
        name:'',
        Name:'',
    }
</code>```

Body:
I am making an api call which returns me an array of Usernames. I am calling the api in a Navbar component and am sending the data returned by the api to another component as props. When I console.log(this.state.Name) in Navbar it gives the whole array having usernames in the console, but when i receive the array in the other SearchedUser componenet and console.log() the recieved prop it gives me undefined in the console. Can Anyone tell whats wrong.

----------------------------------Navbar Component----------------------------

     class Navbar extends Component{

     constructor(props){
    super(props);
    this.state={
        name:'',
        Name:[],
    }
     this.GetUserData=this.GetUserData.bind(this);
}

    GetUserData=()=>{
fetch(`http://localhost:4000/data/searchuser?Name=${this.state.name}`)
.then(response => response.json())
.then(data=> this.setState({Name:data.datad}))
.catch(err=>console.log(err));}

        render()
{
    console.log(this.state.Name);
    return(
        <Router>
          <Link to={'/SearchedUser'}>
                <button type="submit" onClick={this.GetUserData}></button>
         </Link>
            <Switch>
                <Route exact path='/' component={HomeContent} />
                <Route path='/Profile' component={Profile}/>
                <Route path='/SearchedUser' render={(props)=> <SearchedUser {...props} UserName={ [this.state.Name]}/>}/>
            </Switch>
        </Router>)  }}

--------------------------------SearchedUser Component------------------------

    import React from 'react'
class SearchedUser extends React.Component{
constructor(props){
super(props);
this.state={
    Name: props.UserName
}
    }

    render(){
console.log(this.state.Name);
return(

     )
    }
    }
export default SearchedUser;

Body:
Can you try with 2 changes like:

[this.state.Name] > this.state.Name as the first one outputs an array with single entry like ['sara']:

<SearchedUser {...props} UserName={this.state.Name}/>}

Another thing, in the constructor of NavBar component:

 this.state={
        name:'',
        Name:'',
    }


问:
Python split by multiple separators, including space?
Input:

```<code>Some Text here: Java, PHP, JS, HTML 5, CSS, Web, C#, SQL, databases, AJAX, etc.
</code>```

Code:

```<code>import re

input_words = list(re.split('\s+', input()))
print(input_words)
</code>```

Works perfect and returns me:

```<code>['Some', 'Text', 'here:', 'Java,', 'PHP,', 'JS,', 'HTML', '5,', 'CSS,', 'Web,', 'C#,', 'SQL,', 'databases,', 'AJAX,', 'etc.']
</code>```

But when add some other separators, like this:

```<code>import re

input_words = list(re.split('\s+ , ; : . ! ( ) " \' \ / [ ] ', input()))
print(input_words)
</code>```

It doesn't split by spaces anymore, where am I wrong?

Expected outpus would be:

```<code>['Some', 'Text', 'here', 'Java', 'PHP', 'JS', 'HTML', '5', 'CSS', 'Web', 'C#', 'SQL', 'databases', 'AJAX', 'etc']
</code>```

答:
You should be splitting on a regex alternation containing all those symbols:

```<code>input_words = re.split('[\s,;:.!()"\'\\\[\]]', input())
print(input_words)
</code>```

This is a literal answer to your question.  The actual solution you might want to use would be to split on the symbols with optional whitespace on either end, e.g

```<code>input = "A B ; C.D   ! E[F] G"
input_words = re.split('\s*[,;:.!()"\'\\\[\]]?\s*', input)
print(input_words)
</code>```

Prints:

```<code>['A', 'B', 'C', 'D', 'E', 'F', 'G']
</code>```

Body:
Input:

Some Text here: Java, PHP, JS, HTML 5, CSS, Web, C#, SQL, databases, AJAX, etc.

Code:

import re

input_words = list(re.split('\s+', input()))
print(input_words)

Works perfect and returns me:

['Some', 'Text', 'here:', 'Java,', 'PHP,', 'JS,', 'HTML', '5,', 'CSS,', 'Web,', 'C#,', 'SQL,', 'databases,', 'AJAX,', 'etc.']

But when add some other separators, like this:

import re

input_words = list(re.split('\s+ , ; : . ! ( ) " \' \ / [ ] ', input()))
print(input_words)

It doesn't split by spaces anymore, where am I wrong?

Expected outpus would be:

['Some', 'Text', 'here', 'Java', 'PHP', 'JS', 'HTML', '5', 'CSS', 'Web', 'C#', 'SQL', 'databases', 'AJAX', 'etc']

Body:
You should be splitting on a regex alternation containing all those symbols:

input_words = re.split('[\s,;:.!()"\'\\\[\]]', input())
print(input_words)

This is a literal answer to your question.  The actual solution you might want to use would be to split on the symbols with optional whitespace on either end, e.g

input = "A B ; C.D   ! E[F] G"
input_words = re.split('\s*[,;:.!()"\'\\\[\]]?\s*', input)
print(input_words)

Prints:

['A', 'B', 'C', 'D', 'E', 'F', 'G']


问:
How to read an .RTF file using .NET 4.0
I have seen samples using Word 9.0 object library. But I have Office 2010 Beta and .NET 4.0 in VS2010. Any tips on how to go with the new Word Dlls?

So I just wanted to get the functionality of RTF to TEXT with .NET3.5 or later.

答:
If anyone needs a solution to ASP.NET, I found this perfect solution:

Add a reference to System.Windows.Forms or download the DLL itself and reference to it.

Next you can extract the text by creating a temporary RichTextBox:

```<code>RichTextBox box = new RichTextBox();
box.Rtf = File.ReadAllText(Path);
string text = box.Text;
</code>```

Title: How to read an .RTF file using .NET 4.0

Body:
If anyone needs a solution to ASP.NET, I found this perfect solution:

Add a reference to System.Windows.Forms or download the DLL itself and reference to it.

Next you can extract the text by creating a temporary RichTextBox:

RichTextBox box = new RichTextBox();
box.Rtf = File.ReadAllText(Path);
string text = box.Text;


问:
in laravel Upload image in two different folder at same time

This Code save image in only one "folder-one". I want to upload the
  image at the same time in two different folders, now it saving in folder-one

example

"folder-one"

and

"folder-two"

```<code><?php

namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Mail;
use Illuminate\Auth\Events\Registered;

class RegisterController extends Controller
{

use RegistersUsers;

protected $redirectTo = '/home';

public function __construct()
{
    $this->middleware('guest');
}

protected function validator(array $data)
{
    return Validator::make($data, [
       'photo_jpeg' => 'required|image|mimes:jpeg,png,jpg|max:2048',
    ]);
}

protected function create(array $data)
{
    $photo_jpeg= time() . '.' . $data['photo_jpeg']->getClientOriginalExtension();
    $data['photo_jpeg']->move(base_path() . 'public/folder-one', $photo_jpeg);

    return user::create([
        'photo_jpeg' => $photo_jpeg,
    ]);

}
</code>```

答:
Use method copy() to make a copy of the file at the new destination.

```<code>$request->file('photo')->move($destination_path, $file_name); //original
copy($destination_path.$file_name, $new_path.$file_name); //backup
</code>```

Body:
This Code save image in only one "folder-one". I want to upload the
  image at the same time in two different folders, now it saving in folder-one

example

"folder-one"

and

"folder-two"

<?php

namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Mail;
use Illuminate\Auth\Events\Registered;

class RegisterController extends Controller
{

use RegistersUsers;

protected $redirectTo = '/home';

public function __construct()
{
    $this->middleware('guest');
}

protected function validator(array $data)
{
    return Validator::make($data, [
       'photo_jpeg' => 'required|image|mimes:jpeg,png,jpg|max:2048',
    ]);
}

protected function create(array $data)
{
    $photo_jpeg= time() . '.' . $data['photo_jpeg']->getClientOriginalExtension();
    $data['photo_jpeg']->move(base_path() . 'public/folder-one', $photo_jpeg);

    return user::create([
        'photo_jpeg' => $photo_jpeg,
    ]);

}

Body:
Use method copy() to make a copy of the file at the new destination.

$request->file('photo')->move($destination_path, $file_name); //original
copy($destination_path.$file_name, $new_path.$file_name); //backup


问:
What's the value of variable when setTimeout assigned to it?
I am trying to know what is the value of the variable when setTimeout get called and assigned to it. Unexpected value get logged, so being curious how this happening.

I tried to look some related question on stack and also look out on web but didn't get the exact answer.

Update - I am seeking help to understand how the unique id which assigne d to variable get calculated ?

let a = setTimeout( () => {
  console.log('something will happen')
}, 2000)

let b = setTimeout( () => {
  console.log('something will happen')
}, 3000)

let c = setTimeout( () => {
  console.log('something will happen')
}, 4000)

console.log(a, b, c)```

答:
There is documentation on what type of values to expect.

Quote:

The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.

It may be helpful to be aware that setTimeout() and setInterval() share the same pool of IDs, and that clearTimeout() and clearInterval() can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code.

It is guaranteed that a timeout ID will never be reused by a subsequent call to setTimeout() or setInterval() on the same object (a window or a worker). However, different objects use separate pools of IDs.


问:
SQL add conditional query
In a table in my database I have 12 columns, month_1 .... month_12.

I want to add conditional to my SQL query, if @m = 1 will do

```<code>CREATE PROCEDURE XemDiem_Top5Month1
    @m INT
AS
BEGIN
    SELECT *
    FROM XemDiem
    WHERE (month_1 IN (SELECT TOP (5) month_1
                       FROM XemDiem
                       GROUP BY month_1
                       ORDER BY month_1DESC))
END
</code>```

if @m = 2 will do

```<code>CREATE PROCEDURE XemDiem_Top5Month1
    @m INT
AS
BEGIN
    SELECT *
    FROM XemDiem
    WHERE (month_2 IN (SELECT TOP (5) month_2
                       FROM XemDiem
                       GROUP BY month_2
                       ORDER BY month_2 DESC))
END
</code>```

and so on ....

I don't want to write too many queries, so please help

答:
```<code>declare @ishistoric varchar(100) ='month_1'
(SELECT *
FROM XemDiem
WHERE
(
 CASE @ishistoric
                  WHEN 'month_1' THEN month_1
                  WHEN 'month_2' THEN month_2
                  ...
                  WHEN 'month_12' THEN month_12
             END  IN
(
SELECT TOP (5) CASE @ishistoric
                  WHEN 'month_1' THEN month_1
                  WHEN 'month_2' THEN month_2
                  ...
                  WHEN 'month_12' THEN month_12
             END
FROM OSUSR_KIA_PRINTSTICKER
GROUP BY  CASE @ishistoric
                  WHEN 'month_1' THEN month_1
                  WHEN 'month_2' THEN month_2
                  ...
                  WHEN 'month_12' THEN month_12
             END
ORDER BY CASE @ishistoric
                  WHEN 'month_1' THEN month_1
                  WHEN 'month_2' THEN month_2
                  ...
                  WHEN 'month_12' THEN month_12
             END DESC
)
))
</code>```

Make your remain query just like that and query is based on the provided columns & it will the return respective records for specific column which are passed into the parameter.

Title: SQL add conditional query

Body:
In a table in my database I have 12 columns, month_1 .... month_12.

I want to add conditional to my SQL query, if @m = 1 will do

CREATE PROCEDURE XemDiem_Top5Month1
    @m INT
AS
BEGIN
    SELECT *
    FROM XemDiem
    WHERE (month_1 IN (SELECT TOP (5) month_1
                       FROM XemDiem
                       GROUP BY month_1
                       ORDER BY month_1DESC))
END

if @m = 2 will do

CREATE PROCEDURE XemDiem_Top5Month1
    @m INT
AS
BEGIN
    SELECT *
    FROM XemDiem
    WHERE (month_2 IN (SELECT TOP (5) month_2
                       FROM XemDiem
                       GROUP BY month_2
                       ORDER BY month_2 DESC))
END

and so on ....

I don't want to write too many queries, so please help

Body:
declare @ishistoric varchar(100) ='month_1'
(SELECT *
FROM XemDiem
WHERE
(
 CASE @ishistoric
                  WHEN 'month_1' THEN month_1
                  WHEN 'month_2' THEN month_2
                  ...
                  WHEN 'month_12' THEN month_12
             END  IN
(
SELECT TOP (5) CASE @ishistoric
                  WHEN 'month_1' THEN month_1
                  WHEN 'month_2' THEN month_2
                  ...
                  WHEN 'month_12' THEN month_12
             END
FROM OSUSR_KIA_PRINTSTICKER
GROUP BY  CASE @ishistoric
                  WHEN 'month_1' THEN month_1
                  WHEN 'month_2' THEN month_2
                  ...
                  WHEN 'month_12' THEN month_12
             END
ORDER BY CASE @ishistoric
                  WHEN 'month_1' THEN month_1
                  WHEN 'month_2' THEN month_2
                  ...
                  WHEN 'month_12' THEN month_12
             END DESC
)
))

Make your remain query just like that and query is based on the provided columns & it will the return respective records for specific column which are passed into the parameter.


答:
According to documentation that's how saveAll looks like:

```<code>@Transactional
public <S extends T> List<S> saveAll(Iterable<S> entities)
</code>```

But, to be sure it will work as single atomic transaction you need:

1) Ensure transactions support work for you

2) Ensure autocommit is set to false (optional, in case if will not work)

Title: Is CrudRepository.save(Iterable<S>) is atomic?

Body:
I am saving multiple objects using CrudRepository.save(Iterable<S>).

is this operation behaviour is atomic?

What will happen if I save 10 entities and it fails for 6th one?

Body:
According to documentation that's how saveAll looks like:

@Transactional
public <S extends T> List<S> saveAll(Iterable<S> entities)

But, to be sure it will work as single atomic transaction you need:

1) Ensure transactions support work for you

2) Ensure autocommit is set to false (optional, in case if will not work)


问:
Need help in rendering HTML Code to px-data-column with type="html"
I have written a table in polymer 1.0 using px-data-table and I want one of the column in this table to present a checkbox option.

I am having trouble in writing filterFunctionName and how to render html code in the particular column.

'''
<px-data-table id="mytable" filterable selectable table-data="{{minidata}}">
   <px-data-table-column name="first" filterable sortable editable>
    </px-data-table-column>
    <px-data-table-column name="last" editable sortable>
    </px-data-table-column>
    <px-data-table-column name="Checkbox" type="html" filterable
     filter-function-name="myTableCustomFunctions.Rendercheckbox()">
     </px-data-table-column>
 </px-data-table>
'''
```

In the table I need to see a check box in the last column. I have tried in many ways to render that small piece of html code by using DOM or using filter function name. Can anyone help me in understanding how to actually add html code here.

Thanks.

答:
data.Checkbox="<input type='checkbox' id="checkbox1" name="checkbox1" class='selectAll'/>"; ```

I will add this snippet in my page where i am inserting data into table. so when this snippet is inserted into the same column with type="html" it will show me a checkbox.

Body:
I have written a table in polymer 1.0 using px-data-table and I want one of the column in this table to present a checkbox option.

I am having trouble in writing filterFunctionName and how to render html code in the particular column.

'''
<px-data-table id="mytable" filterable selectable table-data="{{minidata}}">
   <px-data-table-column name="first" filterable sortable editable>
    </px-data-table-column>
    <px-data-table-column name="last" editable sortable>
    </px-data-table-column>
    <px-data-table-column name="Checkbox" type="html" filterable
     filter-function-name="myTableCustomFunctions.Rendercheckbox()">
     </px-data-table-column>
 </px-data-table>
'''

In the table I need to see a check box in the last column. I have tried in many ways to render that small piece of html code by using DOM or using filter function name. Can anyone help me in understanding how to actually add html code here.

Thanks.

Body:
data.Checkbox="<input type='checkbox' id="checkbox1" name="checkbox1" class='selectAll'/>";

I will add this snippet in my page where i am inserting data into table. so when this snippet is inserted into the same column with type="html" it will show me a checkbox.


Title: group Timeseries by hourly count in python pandas

Body:
df['data'] = df['data'].dropna()
df['data'] = df['data'].str.strip("'(), ")
df['data'] = pd.to_datetime(df['data'], format='%Y-%m-%d %H:%M:%S.%f')
df['data'] = df['data'].dropna()

This is my data set header

0   2019-05-26 00:00:00.326000+00:00
1   2019-05-26 00:00:00.690000+00:00
2   2019-05-26 00:00:02.850000+00:00
3   2019-05-26 00:00:02.971000+00:00
4   2019-05-26 00:00:03.432000+00:00
Name: data, dtype: datetime64[ns, UTC]

I need to count hourly basis.
required output

time interval  :  Total

0 - 1 : 5 times
1 - 2 : 10 times
..
..
23 - 24: 4 times

df[data].head()

Body:
Use pandas.Series.dt.hour.

Given df:

                     data
0 2019-05-26 01:00:00.326
1 2019-05-26 02:00:00.690
2 2019-05-26 02:00:02.850
3 2019-05-26 03:00:02.971
4 2019-05-26 05:00:03.432

Using df['data'].dt.hour with pd.DataFrame.groupby.count:

import pandas as pd

df.groupby(df['data'].dt.hour).count()

Output:

      data
data
1        1
2        2
3        1
5        1


问:
How to make my wpf app wait for 3 minutes before re-loading data?
I am using VS2010 - WPF - C#

in my application I fetch data from a web server and view it on my interface
the problem is that I want to keep fetching data and keep refreshing my interface every 3 minutes but I don't know how to do that...

I tried (Thread.Sleep(18000)) and it didn't work because my interface wouldn't show at all

I don't know how to use the Timer for such reason and I couldn't find what I'm looking for elsewhere

Please can you help me with it ?

Best Regards

答:
Use a dispatch timer like this

Delcare it

```<code>public System.Windows.Threading.DispatcherTimer timer1;
</code>```

In the constructor

```<code>timer1 = new System.Windows.Threading.DispatcherTimer();
timer1.Interval = TimeSpan.FromSeconds(180); // 3 mintues interval
timer1.Tick += TimerTicked; // Event for handling the fetching data
</code>```

Do your job

```<code> private void TimerTicked(object sender, EventArgs args)
 {
//Fetch the data
 }
</code>```

timer1.start(); // Whereever you want to start the timer

Body:
Use a dispatch timer like this

Delcare it

public System.Windows.Threading.DispatcherTimer timer1;

In the constructor

timer1 = new System.Windows.Threading.DispatcherTimer();
timer1.Interval = TimeSpan.FromSeconds(180); // 3 mintues interval
timer1.Tick += TimerTicked; // Event for handling the fetching data

Do your job

 private void TimerTicked(object sender, EventArgs args)
 {
//Fetch the data
 }

timer1.start(); // Whereever you want to start the timer


问:
Selenium waitForElement
How do I write the function for Selenium to wait for a table with just a class identifier in Python? I'm having a devil of a time learning to use Selenium's Python webdriver functions.</p>

答:
I found an easier way to build this using a custom function, which is recursive in nature

from selenium import webdriver
import time

def wait_element_by_id(id_value):
    try:
        elem = driver.find_element_by_id(id_value)
    except:
        time.sleep(2)
        print 'Waiting for id '+id_value
        wait_element_by_id(id_value)
```

You can replace find_element_by_id with find_element_by_name or find_element_by_tag_name based on your requirement

Title: Selenium waitForElement

Body:
I found an easier way to build this using a custom function, which is recursive in nature

from selenium import webdriver
import time

def wait_element_by_id(id_value):
    try:
        elem = driver.find_element_by_id(id_value)
    except:
        time.sleep(2)
        print 'Waiting for id '+id_value
        wait_element_by_id(id_value)

You can replace find_element_by_id with find_element_by_name or find_element_by_tag_name based on your requirement


问:
Specific case for 'no match for ‘operator<<’'
I am facing a problem whereby I have already done my operator << but it doesn't work for some reason. I tried countless ways and the one below made the most sense to me. But still failed. Can anyone show me the proper way to overload (*this)[index] in this specific instance(Refer to class VisiblePolygon)? Class Polygon will consist of the operator << to the class VisiblePolygon. Can't find a solution for this specific case. Hence I'm here. Thanks!

Compile error:

```<code>In function ‘std::ostream& operator<<(std::ostream&, const Polygon&)’:

polygon.h:103:8: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘Object::PointType’)

     os <<p.mpt[i];
     ~~~^~~~~~~~~~
</code>```

My code:

```<code>#include <iostream>
#include <algorithm>
#include <functional>
#include <list>
#include <cmath>

class Polygon : public Point
{
  private:
    Object::PointType *mpt; //An array of points
    int msize;

  public:
    PointType& operator[](int index)  const
    {
      return mpt[index];
    }

    Polygon(const PointType* points, int npoints);

    Polygon(PointType* points, int npoints, float depth) //constructor
      : Point(*points,depth),
      mpt{new Object::PointType[npoints]},
      msize(npoints)
    {
       for(int i = 0; i < msize; ++i)
       {
         mpt[i]  = points[i];
       }
    }

    Polygon center()
    {
      //..
    }

    float x()
    {
      //...
    }

    float y()
    {
      //...
    }

    int size() const
    {
      return msize;
    }

    virtual void render() const
    {}

    friend std::ostream& operator<<(std::ostream& os, const Polygon& p)
    {
      for (int i = 0; i < p.msize; ++i)
      {
        os <<p.mpt[i];
        return os;
      }
    }
};

class VisiblePolygon : public Polygon
{
  public:
    VisiblePolygon(const Object::PointType* points, int size) :
      Polygon(points, size)
    {
    }

    void render() const override
    {
        std::cout << "Polygon with vertices: ";
        for (int index = 0; index < size(); ++index)
        {
            std::cout << (*this)[index] << " ";
        }
        std::cout << std::endl;
    }
};
</code>```

答:
The error

In function ‘std::ostream& operator<<(std::ostream&, const Polygon&)’: polygon.h:103:8: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘Object::PointType’)

basically says "OK you have operator << for Polygon, now you need one for PointType as well".

Unrelated, but return os; should probably be outside the loop.

Body:
I am facing a problem whereby I have already done my operator << but it doesn't work for some reason. I tried countless ways and the one below made the most sense to me. But still failed. Can anyone show me the proper way to overload (*this)[index] in this specific instance(Refer to class VisiblePolygon)? Class Polygon will consist of the operator << to the class VisiblePolygon. Can't find a solution for this specific case. Hence I'm here. Thanks!

Compile error:

In function ‘std::ostream& operator<<(std::ostream&, const Polygon&)’:

polygon.h:103:8: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘Object::PointType’)

     os <<p.mpt[i];
     ~~~^~~~~~~~~~

My code:

#include <iostream>
#include <algorithm>
#include <functional>
#include <list>
#include <cmath>

class Polygon : public Point
{
  private:
    Object::PointType *mpt; //An array of points
    int msize;

  public:
    PointType& operator[](int index)  const
    {
      return mpt[index];
    }

    Polygon(const PointType* points, int npoints);

    Polygon(PointType* points, int npoints, float depth) //constructor
      : Point(*points,depth),
      mpt{new Object::PointType[npoints]},
      msize(npoints)
    {
       for(int i = 0; i < msize; ++i)
       {
         mpt[i]  = points[i];
       }
    }

    Polygon center()
    {
      //..
    }

    float x()
    {
      //...
    }

    float y()
    {
      //...
    }

    int size() const
    {
      return msize;
    }

    virtual void render() const
    {}

    friend std::ostream& operator<<(std::ostream& os, const Polygon& p)
    {
      for (int i = 0; i < p.msize; ++i)
      {
        os <<p.mpt[i];
        return os;
      }
    }
};

class VisiblePolygon : public Polygon
{
  public:
    VisiblePolygon(const Object::PointType* points, int size) :
      Polygon(points, size)
    {
    }

    void render() const override
    {
        std::cout << "Polygon with vertices: ";
        for (int index = 0; index < size(); ++index)
        {
            std::cout << (*this)[index] << " ";
        }
        std::cout << std::endl;
    }
};