问:
Google Guava cache auto remove value of Optional.absent()
Is it possible to auto evict the record with value Optional.absent()? In some applications the Optional.absent() may not be the value for some keys. For example, if an application contains http calls where the key can be some string and the value is response returned from the http call, the http call can return some invalid values (for example null) because of network issues or authentication failures, then the invalid can be saved as Optional.absent() with the key in cache. At a later point, if the network and authentication problems are fixed, the key->invalidValue still remains in the cache. What is the best to fix this problem?</p>

答:
For example, if an application contains http calls where the key can be some string and the value is response returned from the http call, the http call can return some invalid values (for example null) because of network issues or authentication failures

If possible, I would change this behavior to throw an exception when the request fails or the response is invalid - that's what exceptions are for. See Effective Java: Item 57 for more.

then the invalid can be saved as Optional.absent() with the key in cache. At a later point, if the network and authentication problems are fixed, the key->invalidValue still remains in the cache. What is the best to fix this problem?

Is there a reason you need to save the invalid result in the cache? If you don't care about the absent case and simply want it excluded from the cache the easiest option would be to just not cache it in the first place. Throwing an exception on bad results would make that easy.

If you do need to keep the invalid results in the cache temporarily you can clear them once you're ready with a simple for loop:

```<code>ConcurrentMap<K, V> cacheAsMap = cache.asMap();
for (Entry<K, V> e : cacheAsMap .entrySet()) {
  if (!e.getValue().isPresent()) {
    cacheAsMap.remove(e.getKey(), e.getValue());
  }
}
</code>```

By using ConcurrentMap.remove() you avoid a possible race condition where the entry is updated after e.getValue().isPresent() is called but before the entry is actually invalidated.

Body:
For example, if an application contains http calls where the key can be some string and the value is response returned from the http call, the http call can return some invalid values (for example null) because of network issues or authentication failures

If possible, I would change this behavior to throw an exception when the request fails or the response is invalid - that's what exceptions are for. See Effective Java: Item 57 for more.

then the invalid can be saved as Optional.absent() with the key in cache. At a later point, if the network and authentication problems are fixed, the key->invalidValue still remains in the cache. What is the best to fix this problem?

Is there a reason you need to save the invalid result in the cache? If you don't care about the absent case and simply want it excluded from the cache the easiest option would be to just not cache it in the first place. Throwing an exception on bad results would make that easy.

If you do need to keep the invalid results in the cache temporarily you can clear them once you're ready with a simple for loop:

ConcurrentMap<K, V> cacheAsMap = cache.asMap();
for (Entry<K, V> e : cacheAsMap .entrySet()) {
  if (!e.getValue().isPresent()) {
    cacheAsMap.remove(e.getKey(), e.getValue());
  }
}

By using ConcurrentMap.remove() you avoid a possible race condition where the entry is updated after e.getValue().isPresent() is called but before the entry is actually invalidated.


来源: stackexchange

问:
What innerHTML internally does to the DOM?
Consider the snippet-

```<code><html >
    <script>
        function  test(){

            function getPosition(parent, descendant) {
                return parent.compareDocumentPosition(descendant);
            }
            var p = document.getElementById("myPara");
            console.log(getPosition(document, p));          // 20

            console.log(document.body.innerHTML);

            document.body.innerHTML += "<p>It's clobberin' time!</p>";
            console.log(getPosition(document, p));          // 37 WHY?

            console.log(document.getElementById("myPara") === p); // false WHY?
        }

    </script>
    <body>
        <p id="myPara">Its a paragraph</p>
        <button onclick="test()">Press Me!</button>
    </body>
</html>
</code>```

The document.body.innerHTMLbefore the assignation prints

```<code>"
        <p id="myPara">Its a paragraph</p>
        <button onclick="test()">Press Me!</button>

"
</code>```

on the console.

2 questions here-

Why is console.log(getPosition(document, p));          // 37 WHY?
The element
It's clobberin' time!
 was appended to the
innerHTML but why did it messed the position of the element
identified by myPara.

Secondly, console.log(document.getElementById("myPara") === p); //    false, WHY?

答:
This happens because every time you set innerHTML, the HTML document is re-parsed, a DOM is constructed and added to your document. This also invalidates all your existing refferences to your DOM elements.

The right approach is to create a new element and append it to the document body. This way you avoid the whole mess presented above, at least for the browsers that don't do any optimizations for this kind of usage (not sure if any do?)

Replace your append line:

```<code>       document.body.innerHTML += "<p>It's clobberin' time!</p>";
</code>```

with this:

```<code>        var myElement = document.createElement('p');
        myElement.innerHTML = '<p>Its clobbering time</p>';
        document.body.appendChild(myElement);
</code>```

Now you will see that:

```<code>        console.log(getPosition(document, p)); // is still 20
        console.log(document.getElementById("myPara") === p); // is now TRUE
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Consider the snippet-

Its a paragraph

        <button onclick="test()">Press Me!</button>

The document.body.innerHTMLbefore the assignation prints

"

Its a paragraph

        <button onclick="test()">Press Me!</button>

"

on the console.

2 questions here-

Why is console.log(getPosition(document, p));          // 37 WHY?
The element
It's clobberin' time!
 was appended to the
innerHTML but why did it messed the position of the element
identified by myPara.

Secondly, console.log(document.getElementById("myPara") === p); //    false, WHY?

Body:
This happens because every time you set innerHTML, the HTML document is re-parsed, a DOM is constructed and added to your document. This also invalidates all your existing refferences to your DOM elements.

The right approach is to create a new element and append it to the document body. This way you avoid the whole mess presented above, at least for the browsers that don't do any optimizations for this kind of usage (not sure if any do?)

Replace your append line:

       document.body.innerHTML += "<p>It's clobberin' time!</p>";

with this:

        var myElement = document.createElement('p');
        myElement.innerHTML = '<p>Its clobbering time</p>';
        document.body.appendChild(myElement);

Now you will see that:

        console.log(getPosition(document, p)); // is still 20
        console.log(document.getElementById("myPara") === p); // is now TRUE


问:
OData Support in ASP.net core
Is oData supported now in ASP.netcore now that version 1 has been released?

I have searched, but I could not find anything that says one way or the other.

答:
Now at the beginning of December 2017, an official prerelease of OData for ASP.NET Core is available at this MyGet feed: https://www.myget.org/F/webapinetcore/

The releases are currently from nightly builds.

For more information, see this comment on a GitHub issue: https://github.com/OData/WebApi/issues/772#issuecomment-348670747

Still no ETA for beta or stable releases.

EDIT: This issue is better to follow to track progress:
https://github.com/OData/WebApi/issues/939

EDIT 2: Beta1 was released December 22. If used with Swashbuckle, this is a great tip: https://github.com/OData/WebApi/issues/1177#issuecomment-358659774

Title: OData Support in ASP.net core


问:
Cron job to run a PHP script every 90 seconds between 5AM and 10PM?
I am looking for a way to run a PHP script between two set times (probably 5AM and 10PM), every 90 seconds.  I was thinking of just making a bash script to move the file in/out of a directory at different times, but that would be messy and make all sorts of errors.  Is there a better way to go about this?</p>

答:
As from this link and modifying it for the time range

One as: "0 0/3 5-22 * * ?" to fire every third min

  The second as: "30 1/2 5-22 * * ?" This will take care of the 90 second


问:
Is it possible to run ARWorldTracking Session and ARFaceTracking Session at the same time on iPhoneX?
I'm trying to run ARWorldTracking Session and ARFaceTracking Session at the same time on iPhoneX,
 but the first running session stopped after the later session begun to run.

Is is impossible to implement?
This is my ViewController.swift code.

```<code>import UIKit
import ARKit

class ViewController: UIViewController, ARSCNViewDelegate,
ARSessionDelegate {
    @IBOutlet weak var frontView: ARSCNView!
    @IBOutlet weak var backView: ARSCNView!
    override func viewDidLoad() {
       super.viewDidLoad()
       startTracking()
    }

   func startTracking() {
       let backConfiguration = ARWorldTrackingConfiguration()
       backView.session.run(backConfiguration)

       let frontConfiguration = ARFaceTrackingConfiguration()
       frontConfiguration.isLightEstimationEnabled = true
       frontView.session.run(frontConfiguration)
  }
}
</code>```

答:
ARSession is a singleton, so changing the configuration is going to change the state of the shared session.  from the docs:

ARSession
  A shared object that manages the device camera and motion
  processing needed for augmented reality experiences.

Body:
I'm trying to run ARWorldTracking Session and ARFaceTracking Session at the same time on iPhoneX,
 but the first running session stopped after the later session begun to run.

Is is impossible to implement?
This is my ViewController.swift code.

import UIKit
import ARKit

class ViewController: UIViewController, ARSCNViewDelegate,
ARSessionDelegate {
    @IBOutlet weak var frontView: ARSCNView!
    @IBOutlet weak var backView: ARSCNView!
    override func viewDidLoad() {
       super.viewDidLoad()
       startTracking()
    }

   func startTracking() {
       let backConfiguration = ARWorldTrackingConfiguration()
       backView.session.run(backConfiguration)

       let frontConfiguration = ARFaceTrackingConfiguration()
       frontConfiguration.isLightEstimationEnabled = true
       frontView.session.run(frontConfiguration)
  }
}


问:
Get text from option field
I have select form with two options 'first' and 'second' and I would see changes on-time when I change the select option, but this code doesn't work :(

Condition ---

Select value ---

```

答:
You have syntax error in if else statement

Try this

```<code>if (test == "first") {
     var condition = 1
} else if (test == "second") {
     var condition = 0
}
</code>```

Title: Get text from option field

Body:
You have syntax error in if else statement

Try this

if (test == "first") {
     var condition = 1
} else if (test == "second") {
     var condition = 0
}


问:
test results summary in Axo cover Report generator
I am using AxoCover code coverage tool for generating the code coverage report in visual studio. I wanted to include unit test results [pass\fail] in the unit test report summary. Is it possible?

I am using visual studio 2017 Professional.
enter image description here

答: ReportGenerator only reads the coverage results of OpenCover. It does not process the tests results of MSTest/xUnit/nUnit.</p>


问:
genetic python algorithm to make the smallest set of words
I have a course in AI and I have an exercise to write a code producing the shortest possible sentence (in term of number of character) I have a list2D of departure
It's just word list no real english sentence.I do not need to have a correct sentence in English

```<code>data=[["One","Two","He","You","a"],["have","had","make","do"],["red","blue"]]
</code>```

I have to make a sentence of 3 words as small as possible (in number of character), the solution for the example i presented before would be "a do red"

here is what I did in genetic algorithm, I seek the most value patite by modifying each gen 0.05% of the pop.

An individual is a sentence, A population is a phrase set , I try to generate the smallest possible sentence.

the problem is that the value does not change. Thanks in advance for your help.

答:
If you have to pick one word from each list, you could do:

```<code>for sublist in data:
    print(min(sublist, key=len))

Out [4]:
a
do
red
</code>```

Or if you want a single string as result:

```<code>" ".join([min(sublist, key=len) for sublist in data])

Out [2]:
'a do red'
</code>```

Note that this picks the first shortest word from each list, so if there are multiple words with the shortest length you get whichever is first in your list. Rather than print them out you may want to append them to a new list, or do something else dependent on your use case.

Body:
I have a course in AI and I have an exercise to write a code producing the shortest possible sentence (in term of number of character) I have a list2D of departure
It's just word list no real english sentence.I do not need to have a correct sentence in English

data=[["One","Two","He","You","a"],["have","had","make","do"],["red","blue"]]

I have to make a sentence of 3 words as small as possible (in number of character), the solution for the example i presented before would be "a do red"

here is what I did in genetic algorithm, I seek the most value patite by modifying each gen 0.05% of the pop.

An individual is a sentence, A population is a phrase set , I try to generate the smallest possible sentence.

the problem is that the value does not change. Thanks in advance for your help.

Body:
If you have to pick one word from each list, you could do:

for sublist in data:
    print(min(sublist, key=len))

Out [4]:
a
do
red

Or if you want a single string as result:

" ".join([min(sublist, key=len) for sublist in data])

Out [2]:
'a do red'

Note that this picks the first shortest word from each list, so if there are multiple words with the shortest length you get whichever is first in your list. Rather than print them out you may want to append them to a new list, or do something else dependent on your use case.


Title: In python. Use the format of one list to another list

Body:
list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]

list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]

I want the list3 be like this:

list 3 = [[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]

I had already get the index of the list1 like that:

index_list = [[0, 1], [2], [3], [4, 5, 6, 7, 8], [9, 10, 11], [12, 13], [14], [15], [16, 17], [18], [19], [20]]

Body:
Below is a solution that utilizes itertools.accumulate().

from itertools import accumulate

list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]

list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]

# temp to track the starting and ending index positions of the sublists
temp = [0] + list(accumulate(len(x) for x in list1))
# [0, 2, 3, 4, 9, 12, 14, 15, 16, 18, 19, 20, 21]

list3 = [list2[j:temp[i+1]] for i, j in enumerate(temp[:-1])]  # See 1
# >> [[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]

Alternatively, you can use list3 = [list2[i:j] for i, j in zip(temp[:-1], temp[1:])] if you understand it better.


问:
Does Arquillian @Deployment has a URL path?
With @Deployment on Arquillian framework you can deploy a WebArchive file on your container. I want to send HTTP Requests to this container. Does this container have a specific URL? Can I set it to have a specific URL?

I have read about @ArquillianResource, but on the code down below it always returns null.

```<code>@RunWith(Arquillian.class)
public class MyClassTest {

    @ArquillianResource
    private URL baseURL2;

    @ArquillianResource(MyClass.class)
    private URL baseServerURL;

    @Deployment
    public static WebArchive createDeployment() {
        WebArchive w = ShrinkWrap
                .create(WebArchive.class)
                .addPackages(true, "my.package")
                .addClass(MyClass.class);
        System.out.println(w);
        return w;
    }

    @Test @RunAsClient
    public void firstTest(@ArquillianResource(MyClass.class) URL baseURL) {
        System.out.println(baseURL);
        System.out.println(baseURL2);
        Assert.assertTrue(false);
    }
</code>```

output:

```<code>null
null
</code>```

Any help given is appreciated.

答:
You have to set all this:

```<code>String port = System.getProperty("server.port");
if (port == null) {
    RestAssured.port = Integer.valueOf(8080);
} else {
    RestAssured.port = Integer.valueOf(port);
}

String basePath = System.getProperty("server.base");
if (basePath == null) {
    basePath = "/basePath/rest/";
}
RestAssured.basePath = basePath;

String baseHost = System.getProperty("server.host");
if (baseHost == null) {
    baseHost = "http://localhost";
}
RestAssured.baseURI = baseHost;

RestAssured.defaultParser = Parser.JSON;
</code>```

A better approach is to add this code to a parent class and all or your tests to extend this functionality.

So with the above configuration if you have a url like http://localhost:8080/persons/{id}/roles you can call a rest from your test like this:

```<code>List<SecurityRole> personGet = Arrays.asList(given().header("Accept-Language", "en").header("Authorization", getToken()).pathParam("id", person.getId()).when().get("/persons/{id}/roles")
.then().statusCode(200).extract().response().as(SecurityRole[].class));
</code>```

You do not have to worry about the urls just your end point url.

Body:
With @Deployment on Arquillian framework you can deploy a WebArchive file on your container. I want to send HTTP Requests to this container. Does this container have a specific URL? Can I set it to have a specific URL?

I have read about @ArquillianResource, but on the code down below it always returns null.

@RunWith(Arquillian.class)
public class MyClassTest {

    @ArquillianResource
    private URL baseURL2;

    @ArquillianResource(MyClass.class)
    private URL baseServerURL;

    @Deployment
    public static WebArchive createDeployment() {
        WebArchive w = ShrinkWrap
                .create(WebArchive.class)
                .addPackages(true, "my.package")
                .addClass(MyClass.class);
        System.out.println(w);
        return w;
    }

    @Test @RunAsClient
    public void firstTest(@ArquillianResource(MyClass.class) URL baseURL) {
        System.out.println(baseURL);
        System.out.println(baseURL2);
        Assert.assertTrue(false);
    }

output:

null
null

Any help given is appreciated.

Body:
You have to set all this:

String port = System.getProperty("server.port");
if (port == null) {
    RestAssured.port = Integer.valueOf(8080);
} else {
    RestAssured.port = Integer.valueOf(port);
}

String basePath = System.getProperty("server.base");
if (basePath == null) {
    basePath = "/basePath/rest/";
}
RestAssured.basePath = basePath;

String baseHost = System.getProperty("server.host");
if (baseHost == null) {
    baseHost = "http://localhost";
}
RestAssured.baseURI = baseHost;

RestAssured.defaultParser = Parser.JSON;

A better approach is to add this code to a parent class and all or your tests to extend this functionality.

So with the above configuration if you have a url like http://localhost:8080/persons/{id}/roles you can call a rest from your test like this:

List<SecurityRole> personGet = Arrays.asList(given().header("Accept-Language", "en").header("Authorization", getToken()).pathParam("id", person.getId()).when().get("/persons/{id}/roles")
.then().statusCode(200).extract().response().as(SecurityRole[].class));

You do not have to worry about the urls just your end point url.


问:
How to add multiple columns using UDF?
Question

I want to add the return values of a UDF to an existing dataframe in seperate columns. How do I achieve this in a resourceful way?

Here's an example of what I have so far.

```<code>from pyspark.sql.functions import udf
from pyspark.sql.types import ArrayType, StructType, StructField, IntegerType

df = spark.createDataFrame([("Alive",4)],["Name","Number"])
df.show(1)

+-----+------+
| Name|Number|
+-----+------+
|Alive|     4|
+-----+------+

def example(n):
        return [[n+2], [n-2]]

#  schema = StructType([
#          StructField("Out1", ArrayType(IntegerType()), False),
#          StructField("Out2", ArrayType(IntegerType()), False)])

example_udf = udf(example)
</code>```

Now I can add a column to the dataframe as follows

```<code>newDF = df.withColumn("Output", example_udf(df["Number"]))
newDF.show(1)
+-----+------+----------+
| Name|Number|Output    |
+-----+------+----------+
|Alive|     4|[[6], [2]]|
+-----+------+----------+
</code>```

However I don't want the two values to be in the same column but rather in separate ones.

Ideally I'd like to split the output column now to avoid calling the example function two times (once for each return value) as explained here and here, however in my situation I'm getting an array of arrays and I can't see how a split would work there (please note that each array will contain multiple values, separated with a ",".

How the result should look like

What I ultimately want is this

```<code>+-----+------+----+----+
| Name|Number|Out1|Out2|
+-----+------+----+----+
|Alive|     4|   6|   2|
+-----+------+----+----+
</code>```

Note that the use of the StructType return type is optional and doesn't necessarily have to be part of the solution.

EDIT: I commented out the use of StructType (and edited the udf assignment) since it's not necessary for the return type of the example function. However it has to be used if the return value would be something like

```<code>return [6,3,2],[4,3,1]
</code>```

答:
To return a StructType, just using Row

```<code>from pyspark.sql.types import StructType,StructField,IntegerType,Row
from pyspark.sql import functions as F

df = spark.createDataFrame([("Alive", 4)], ["Name", "Number"])

def example(n):
    return Row('Out1', 'Out2')(n + 2, n - 2)

schema = StructType([
    StructField("Out1", IntegerType(), False),
    StructField("Out2", IntegerType(), False)])

example_udf = F.UserDefinedFunction(example, schema)

newDF = df.withColumn("Output", example_udf(df["Number"]))
newDF = newDF.select("Name", "Number", "Output.*")

newDF.show(truncate=False)
</code>```

Title: How to add multiple columns using UDF?

Body:
Question

I want to add the return values of a UDF to an existing dataframe in seperate columns. How do I achieve this in a resourceful way?

Here's an example of what I have so far.

from pyspark.sql.functions import udf
from pyspark.sql.types import ArrayType, StructType, StructField, IntegerType

df = spark.createDataFrame([("Alive",4)],["Name","Number"])
df.show(1)

+-----+------+
| Name|Number|
+-----+------+
|Alive|     4|
+-----+------+

def example(n):
        return [[n+2], [n-2]]

#  schema = StructType([
#          StructField("Out1", ArrayType(IntegerType()), False),
#          StructField("Out2", ArrayType(IntegerType()), False)])

example_udf = udf(example)

Now I can add a column to the dataframe as follows

newDF = df.withColumn("Output", example_udf(df["Number"]))
newDF.show(1)
+-----+------+----------+
| Name|Number|Output    |
+-----+------+----------+
|Alive|     4|[[6], [2]]|
+-----+------+----------+

However I don't want the two values to be in the same column but rather in separate ones.

Ideally I'd like to split the output column now to avoid calling the example function two times (once for each return value) as explained here and here, however in my situation I'm getting an array of arrays and I can't see how a split would work there (please note that each array will contain multiple values, separated with a ",".

How the result should look like

What I ultimately want is this

+-----+------+----+----+
| Name|Number|Out1|Out2|
+-----+------+----+----+
|Alive|     4|   6|   2|
+-----+------+----+----+

Note that the use of the StructType return type is optional and doesn't necessarily have to be part of the solution.

EDIT: I commented out the use of StructType (and edited the udf assignment) since it's not necessary for the return type of the example function. However it has to be used if the return value would be something like

return [6,3,2],[4,3,1]

Body:
To return a StructType, just using Row

from pyspark.sql.types import StructType,StructField,IntegerType,Row
from pyspark.sql import functions as F

df = spark.createDataFrame([("Alive", 4)], ["Name", "Number"])

def example(n):
    return Row('Out1', 'Out2')(n + 2, n - 2)

schema = StructType([
    StructField("Out1", IntegerType(), False),
    StructField("Out2", IntegerType(), False)])

example_udf = F.UserDefinedFunction(example, schema)

newDF = df.withColumn("Output", example_udf(df["Number"]))
newDF = newDF.select("Name", "Number", "Output.*")

newDF.show(truncate=False)

ContentLicense: CC BY-SA 4.0


问:
Copy selected file to Project directory
I am new in JavaFx, I wonder how to copy a file already selected by Filechooser to my project folder.</p>

```<code>public void ButtonAction(ActionEvent event) {
    FileChooser fc = new FileChooser();
    fc.setTitle("attach a file");
    File selectedFile = fc.showOpenDialog(null);

    if (selectedFile != null) {
        file1.setText("selectionned file : " + selectedFile.getAbsolutePath());

        //the code to copy the selected file goes here//

    } else{
        file1.setText("no file attached");
    }
</code>```

答:
To make it a bit easier for anyone looking to copy the actual code of this method and having a bit of trouble with the above code (since some of it simply doesn't work):

```<code>private Path to;
private Path from;
private File selectedFile;

private void handleFileLocationSearcher() throws IOException {
    FileChooser fc = new FileChooser();
    fc.setTitle("Attach a file");
    selectedFile = fc.showOpenDialog(null);

    if (selectedFile != null) {
        from = Paths.get(selectedFile.toURI());
        to = Paths.get("Your destination path" + selectedFile.getName());
        Files.copy(from.toFile(), to.toFile());
    }
}
</code>```

You can use selectedFile.toString() or selectedFile.getName() to add it into a Text Field or just in general get the path or name of the file you're attempting to retrieve through File Chooser.

You can also use Files.copy(from.toFile(), to.toFile()); somewhere else in your application if you want it to happen on another button press because the variables can be used anywhere in the class. If you don't need to do this though, just create the local variables in the method.

Title: Copy selected file to Project directory

Body:
I am new in JavaFx, I wonder how to copy a file already selected by Filechooser to my project folder.

public void ButtonAction(ActionEvent event) {
    FileChooser fc = new FileChooser();
    fc.setTitle("attach a file");
    File selectedFile = fc.showOpenDialog(null);

    if (selectedFile != null) {
        file1.setText("selectionned file : " + selectedFile.getAbsolutePath());

        //the code to copy the selected file goes here//

    } else{
        file1.setText("no file attached");
    }

Body:
To make it a bit easier for anyone looking to copy the actual code of this method and having a bit of trouble with the above code (since some of it simply doesn't work):

private Path to;
private Path from;
private File selectedFile;

private void handleFileLocationSearcher() throws IOException {
    FileChooser fc = new FileChooser();
    fc.setTitle("Attach a file");
    selectedFile = fc.showOpenDialog(null);

    if (selectedFile != null) {
        from = Paths.get(selectedFile.toURI());
        to = Paths.get("Your destination path" + selectedFile.getName());
        Files.copy(from.toFile(), to.toFile());
    }
}

You can use selectedFile.toString() or selectedFile.getName() to add it into a Text Field or just in general get the path or name of the file you're attempting to retrieve through File Chooser.

You can also use Files.copy(from.toFile(), to.toFile()); somewhere else in your application if you want it to happen on another button press because the variables can be used anywhere in the class. If you don't need to do this though, just create the local variables in the method.


问:
Why 'debugger' will prevent event(keydown -> onInput) be fired
We know that if we add both input and keyDown listener to one dom, when we type something, it will trigger keyDown, and then trigger input.

But if we add a debugger in the keyDown handler, you will find that it won't trigger the input handler, it will just trigger the keyDown handler (test in Chrome and Safari)

document.getElementById('foo').addEventListener('keydown', function(){
 debugger;

  alert('keyDown')
})

document.getElementById('foo').addEventListener('input', function(){
 debugger;

  alert('input')
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="foo" /></code>```

Could anyone explain this?

答:
Very interesting.

Conversely, if the keydown event is changed to keyup, only the input event (and alert) is triggered.

By adding a few console.log()s I think I have an idea of what's happening. Additional insight is definitely welcomed however.

tldr; The presence of the debugger on the keydown prevents the value from the keydown event from being input, which means the value of the input is never changed, which means the input event is never triggered.

In the example below, the debugger is triggered on the keydown event, which happens before the value is inserted. The debugger pauses the execution, and any resulting events, preventing the value from being inserted. When the debugger is resumed the input is never updated with the new value, hence the input event is never triggered. You can see this on the example below - if you open Dev Tools and try to enter a value into the input, then click Resume on the debugger, you'll see the value is never inserted into to the input. So the input event would never be triggered.

document.getElementById('foo').addEventListener('keydown', function(e) {

  debugger;
  console.log(e.target.value, 'keyDown')

})

document.getElementById('foo').addEventListener('input', function(e) {

  debugger;
  console.log(e.target.value, 'input')
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="foo" /></code>```

Body:
We know that if we add both input and keyDown listener to one dom, when we type something, it will trigger keyDown, and then trigger input.

But if we add a debugger in the keyDown handler, you will find that it won't trigger the input handler, it will just trigger the keyDown handler (test in Chrome and Safari)

document.getElementById('foo').addEventListener('keydown', function(){
 debugger;

  alert('keyDown')
})

document.getElementById('foo').addEventListener('input', function(){
 debugger;

  alert('input')
})

<input id="foo" />

Could anyone explain this?

Body:
Very interesting.

Conversely, if the keydown event is changed to keyup, only the input event (and alert) is triggered.

By adding a few console.log()s I think I have an idea of what's happening. Additional insight is definitely welcomed however.

tldr; The presence of the debugger on the keydown prevents the value from the keydown event from being input, which means the value of the input is never changed, which means the input event is never triggered.

In the example below, the debugger is triggered on the keydown event, which happens before the value is inserted. The debugger pauses the execution, and any resulting events, preventing the value from being inserted. When the debugger is resumed the input is never updated with the new value, hence the input event is never triggered. You can see this on the example below - if you open Dev Tools and try to enter a value into the input, then click Resume on the debugger, you'll see the value is never inserted into to the input. So the input event would never be triggered.

document.getElementById('foo').addEventListener('keydown', function(e) {

  debugger;
  console.log(e.target.value, 'keyDown')

})

document.getElementById('foo').addEventListener('input', function(e) {

  debugger;
  console.log(e.target.value, 'input')
})

<input id="foo" />


问:
Laravel auth::atempt get only hashed password
I've created account's in CRM and hashed password in it.

```<code>$account->password = bcrypt($password);
</code>```

then on my web site I've created some guard and provider:

```<code> 'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
        'business' => [
            'driver' => 'session',
            'provider' => 'business'
        ]
    ],

 'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\Eloquent\Account::class,
        ],
        'business' => [
            'driver' => 'eloquent',
            'model'  => App\Models\Eloquent\BusinessAccounts::class
        ]
    ],
</code>```

and then try to login account with guard business:

```<code>public function login(BusinessLoginRequest $request)
    {
        $orgNumber = $request->input('orgNumber');
        $password = $request->input('password');

        if(Auth::guard('business')->attempt(['orgNumber' => $orgNumber, 'password' => $password ])) {
                var_dump(\auth('business')->user());
        }

    }
</code>```

and my Model looks like:

```<code>class BusinessAccounts extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;

    protected $table = 'business_accounts';

    protected $fillable =
        [
            'orgNumber', 'password'
        ];

    public $timestamps = false;

}
</code>```

but when I'm trying to login and var_dump user with password which was'nt hashed I have blank screen and when I'm trying to put hashed password from my DB I can see business accounts model.
 What is wrong with my code?
How I can understand thad Auth::atempt just check the value from login password with db-password and, of course, there are not same.
I've read many guides and articles but can't find mistake,
I know that can be simple but I don't see that.

答:
You do not need to use bcrypt while using attempt function. As you already store hashed password in database you need to just compare that password which is done by attempt function.

So just remove bcrypt and pass as it is

```<code>$account->password = $password;
</code>```

From docs

If the user is found, the hashed password stored in the database will
  be compared with the password value passed to the method via the
  array. You should not hash the password specified as the password
  value, since the framework will automatically hash the value before
  comparing it to the hashed password in the database.

Body:
I've created account's in CRM and hashed password in it.

$account->password = bcrypt($password);

then on my web site I've created some guard and provider:

 'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
        'business' => [
            'driver' => 'session',
            'provider' => 'business'
        ]
    ],

 'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\Eloquent\Account::class,
        ],
        'business' => [
            'driver' => 'eloquent',
            'model'  => App\Models\Eloquent\BusinessAccounts::class
        ]
    ],

and then try to login account with guard business:

public function login(BusinessLoginRequest $request)
    {
        $orgNumber = $request->input('orgNumber');
        $password = $request->input('password');

        if(Auth::guard('business')->attempt(['orgNumber' => $orgNumber, 'password' => $password ])) {
                var_dump(\auth('business')->user());
        }

    }

and my Model looks like:

class BusinessAccounts extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;

    protected $table = 'business_accounts';

    protected $fillable =
        [
            'orgNumber', 'password'
        ];

    public $timestamps = false;

}

but when I'm trying to login and var_dump user with password which was'nt hashed I have blank screen and when I'm trying to put hashed password from my DB I can see business accounts model.
 What is wrong with my code?
How I can understand thad Auth::atempt just check the value from login password with db-password and, of course, there are not same.
I've read many guides and articles but can't find mistake,
I know that can be simple but I don't see that.

Body:
You do not need to use bcrypt while using attempt function. As you already store hashed password in database you need to just compare that password which is done by attempt function.

So just remove bcrypt and pass as it is

$account->password = $password;

From docs

If the user is found, the hashed password stored in the database will
  be compared with the password value passed to the method via the
  array. You should not hash the password specified as the password
  value, since the framework will automatically hash the value before
  comparing it to the hashed password in the database.


问:
My page scrolls horizontally on mobile
I just found out that my website is scrolling horizontally on mobile. However, I am not able to find out why this is happening.

The containers and body seem to have the correct width when I check it in my browser.

Any idea?

https://www.urban-zweirad.de

Cheers,
Mark

答:
Add the following css to body tag</p>

```<code>.body{
  ..
  ..

  width: calc(100% - 8px);
}
</code>```

Title: My page scrolls horizontally on mobile

Body:
Add the following css to body tag

.body{
  ..
  ..

  width: calc(100% - 8px);
}


问:
Pass File Directory between button click
How can I pass file directory between two button click method?

I'm selecting csv file and put the CSV name to TextBox

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
  OpenFileDialog ofd = new OpenFileDialog();
  ofd.Filter = "CSV|*.csv";
  ofd.ShowDialog();

  csvName.Text = ofd.SafeFileName;
}
</code>```

Second button should start reading CSV file selected into first step

```<code>private void Button_Click_1(object sender, RoutedEventArgs e)
{
    //string path = ;
    StreamReader srd = new StreamReader();
}
</code>```

答:
you can read the text of csvName in the button2_click event.

string path = csvName.Text;

or you can use a variable to save the value of the textbox and use that too.

Body:
How can I pass file directory between two button click method?

I'm selecting csv file and put the CSV name to TextBox

private void Button_Click(object sender, RoutedEventArgs e)
{
  OpenFileDialog ofd = new OpenFileDialog();
  ofd.Filter = "CSV|*.csv";
  ofd.ShowDialog();

  csvName.Text = ofd.SafeFileName;
}

Second button should start reading CSV file selected into first step

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    //string path = ;
    StreamReader srd = new StreamReader();
}


问:
Repartition a USB device using DiskPart
I would like to repartition a USB drive using DiskPart from a C# application. This seems reasonably simple: I collect data about plugged disks using the Win32_DiskDrive class and then use DiskPart to run a script that will change the partitions. Critical point seems to be that of mapping the entry I select from Win32_DiskDrive to a disk number in DiskPart. For instance, this is the output of DiskPart:

```<code>DISKPART> list disk

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
* Disk 0    Online          100 GB      0 B
  Disk 1    Online           14 GB      0 B
</code>```

I need to select the disk by its number. But where do I get that number from data retrieved using Win32_DiskDrive? I guess the answer is using the "DeviceID" field, which returns this "\\.\PHYSICALDRIVE0". The index at the end seems to be the one I need to match the entry from Win32_DiskDrive to the related entry from DiskPart. Is this correct? Critical question is: is there any place in the official docs where this is stated without doubts? I will then format the device so I cannot do anything wrong here.
Thanks.

答:
you need use uint32 Index;

Physical drive number of the given drive. This property is filled by
  the STORAGE_DEVICE_NUMBER structure returned from the
  IOCTL_STORAGE_GET_DEVICE_NUMBER control code. A value of 0xffffffff
  indicates that the given drive does not map to a physical drive.

about DiskPart disk numbers - i not found in documentation clear stating what is disk number mean here. however i look under debugger, how diskpart format line for disk - internal function

```<code>long ListDiskLine(IVdsDisk *)
</code>```

called for this.

it used IVdsDisk interface for get disk properties. the IVdsDisk::GetProperties method called for get VDS_DISK_PROP structure
and then used pwszName member:

pwszName: The null-terminated Unicode name that the operating system uses to identify the disk. If present, a client can use this
  property to determine the disk's PNP device number. This is the number
  obtained from the DeviceNumber member of STORAGE_DEVICE_NUMBER
  (see [MSDN-STRGEDEVNUM]). For a hard disk, this name has the format
  \\?\PhysicalDriveN, where N signifies the device number of the
  disk. For a DVD/CD drive, this name has the format \\?\CdRomN, where
  N signifies the device number of the DVD/CD drive. A client can use this property to identify the disk.

for hard disk used next code for get N:

or if translate this to c/c++

```<code>esi = _wtol(pvdp->pwszName + RTL_NUMBER_OF("\\\\?\\PhysicalDrive") - 1);
</code>```

the 0x22 is 0x11*sizeof(WCHAR) and exactly 0x11 (17) symbols in \\?\PhysicalDrive prefix.

so diskpart retriever N from \\?\PhysicalDriveN and this is the number
obtained from the DeviceNumber member of STORAGE_DEVICE_NUMBER (so equal to Win32_DiskDrive.Index)

and finally esi (where stored N) used as:

```<code>StringCchPrintf(sz, 0x400, L"%s Disk %-3lu  %-13.13s  %7s  %7s   %s    %s\r\n", *, esi, ..);
ConsolePrintf(sz);
</code>```

Title: Repartition a USB device using DiskPart

Body:
I would like to repartition a USB drive using DiskPart from a C# application. This seems reasonably simple: I collect data about plugged disks using the Win32_DiskDrive class and then use DiskPart to run a script that will change the partitions. Critical point seems to be that of mapping the entry I select from Win32_DiskDrive to a disk number in DiskPart. For instance, this is the output of DiskPart:

DISKPART> list disk

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
* Disk 0    Online          100 GB      0 B
  Disk 1    Online           14 GB      0 B

I need to select the disk by its number. But where do I get that number from data retrieved using Win32_DiskDrive? I guess the answer is using the "DeviceID" field, which returns this "\\.\PHYSICALDRIVE0". The index at the end seems to be the one I need to match the entry from Win32_DiskDrive to the related entry from DiskPart. Is this correct? Critical question is: is there any place in the official docs where this is stated without doubts? I will then format the device so I cannot do anything wrong here.
Thanks.

Body:
you need use uint32 Index;

Physical drive number of the given drive. This property is filled by
  the STORAGE_DEVICE_NUMBER structure returned from the
  IOCTL_STORAGE_GET_DEVICE_NUMBER control code. A value of 0xffffffff
  indicates that the given drive does not map to a physical drive.

about DiskPart disk numbers - i not found in documentation clear stating what is disk number mean here. however i look under debugger, how diskpart format line for disk - internal function

long ListDiskLine(IVdsDisk *)

called for this.

it used IVdsDisk interface for get disk properties. the IVdsDisk::GetProperties method called for get VDS_DISK_PROP structure
and then used pwszName member:

pwszName: The null-terminated Unicode name that the operating system uses to identify the disk. If present, a client can use this
  property to determine the disk's PNP device number. This is the number
  obtained from the DeviceNumber member of STORAGE_DEVICE_NUMBER
  (see [MSDN-STRGEDEVNUM]). For a hard disk, this name has the format
  \\?\PhysicalDriveN, where N signifies the device number of the
  disk. For a DVD/CD drive, this name has the format \\?\CdRomN, where
  N signifies the device number of the DVD/CD drive. A client can use this property to identify the disk.

for hard disk used next code for get N:

or if translate this to c/c++

esi = _wtol(pvdp->pwszName + RTL_NUMBER_OF("\\\\?\\PhysicalDrive") - 1);

the 0x22 is 0x11*sizeof(WCHAR) and exactly 0x11 (17) symbols in \\?\PhysicalDrive prefix.

so diskpart retriever N from \\?\PhysicalDriveN and this is the number
obtained from the DeviceNumber member of STORAGE_DEVICE_NUMBER (so equal to Win32_DiskDrive.Index)

and finally esi (where stored N) used as:

StringCchPrintf(sz, 0x400, L"%s Disk %-3lu  %-13.13s  %7s  %7s   %s    %s\r\n", *, esi, ..);
ConsolePrintf(sz);


问:
Iterate through two dimensional array while changing each element
I want to fill a two dimensional array with certain values. I want to get:

```<code>[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]
</code>```

How can I do it?

This is my code:

```<code>game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field
</code>```

Body:
I want to fill a two dimensional array with certain values. I want to get:

[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]

How can I do it?

This is my code:

game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field

Body: 9.times.map{|i| "Num#{i.divmod(3).join}"}.each_slice(3).to_a


问:
jQuery addClass and removeClass not working
currently working on a simple script that displays a nightime background if it's a certain time in the day and a daytime image if it's a different time of day. I am using jQuery to achieve this by adding a class if one is true, and adding a class if the other is true. Issue is... the code simply won't function properly. Curious about any possible solutions... thanks!

$(document).ready(function() {
  var currentTime = new Date().getHours();
  if (7 <= currentTime && currentTime < 20) {
    $("document.body").addClass("day");
    $("document.body").removeClass("night");
  } else {
    $("document.body").addClass("night");
    $("document.body").removeClass("day");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.night {
  background-image: url('images/night.jpg');
  background-position: center;
  background-size: 100%;
  background-repeat: no-repeat;
}</code>```

```

答:
Change:-

```<code>$("document.body").addClass("day");
$("document.body").removeClass("night");
</code>```

to:-

```<code>$("body").addClass("day").removeClass("night");
</code>```

(same for second-one too)

Working demo example:-

$(document).ready(function() {
  var currentTime = new Date().getHours();
  if (7 <= currentTime && currentTime < 20) {
    $("body").addClass("day").removeClass("night");
  } else {
    $("body").addClass("night").removeClass("day");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.night {
  background-color: black;
  background-position: center;
  background-size: 100%;
  background-repeat: no-repeat;
}

.day {
  background-color: grey;
  background-position: center;
  background-size: 100%;
  background-repeat: no-repeat;
}</code>```

<!DOCTYPE html>

<meta charset="utf-8">
<title>APP</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="style.css">

```

Body:
currently working on a simple script that displays a nightime background if it's a certain time in the day and a daytime image if it's a different time of day. I am using jQuery to achieve this by adding a class if one is true, and adding a class if the other is true. Issue is... the code simply won't function properly. Curious about any possible solutions... thanks!

$(document).ready(function() {
  var currentTime = new Date().getHours();
  if (7 <= currentTime && currentTime < 20) {
    $("document.body").addClass("day");
    $("document.body").removeClass("night");
  } else {
    $("document.body").addClass("night");
    $("document.body").removeClass("day");
  }
});

.night {
  background-image: url('images/night.jpg');
  background-position: center;
  background-size: 100%;
  background-repeat: no-repeat;
}

Body:
Change:-

$("document.body").addClass("day");
$("document.body").removeClass("night");

to:-

$("body").addClass("day").removeClass("night");

(same for second-one too)

Working demo example:-

$(document).ready(function() {
  var currentTime = new Date().getHours();
  if (7 <= currentTime && currentTime < 20) {
    $("body").addClass("day").removeClass("night");
  } else {
    $("body").addClass("night").removeClass("day");
  }
});

.night {
  background-color: black;
  background-position: center;
  background-size: 100%;
  background-repeat: no-repeat;
}

.day {
  background-color: grey;
  background-position: center;
  background-size: 100%;
  background-repeat: no-repeat;
}

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>APP</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-
hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous">
</script>
<link rel="stylesheet" href="style.css">
</head>
<body>

<div class="app-wrapper">

  <p id="date"></p>

</div>

</body>
</html>


问:
error in phpmyadmin after updating to PHP 7.2.0
Recently I update my PHP version to 7.2.0 .
When I open my phpmyadmin I have face this warning every time when i open any table in database.

If anyone have know about it, Let me know.
Thanks in advance.

答:
if you have an existing or old version of phpMyAdmin configuration on your computer, always check if you already remove or make sure that the old files/history of the config is fully or successfully deleted/already empty in order for your newly installed/updated config to work properly with no any bugs or errors. After you make sure that the old file configuration is already clean, your existing version of phpMyAdmin will be replaced by the version you've configured.

For more information. See this link: https://docs.phpmyadmin.net/en/latest/setup.html#upgrading-from-an-older-version


问:
Angular Typescript map array into class
I have data that comes from a web api that looks like below. How do I map the product array into the Products, the reason for me doing that is that I need to transform the eating_time to javascript datetime.

My code below for the class where this.products = product will only store the array and the the list of product.

//Data from API

```<code>[ {datetime: "2017-06-25T07:45:00+08:00", name: "Apple", unit: 1, product: [{eating_time: "2017-06-25T07:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T17:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T23:55:00+08:00", qtytaken: 1, chart_bar=1 } ]
]
</code>```

// Class

```<code>class Product {
    eating_time: Date;
    qtytaken: number;
    chart_bar = 1;

    constructor({eating_time, qtytaken, chart_bar })  {
            this.eating_time = new Date(eating_time);
            this.qtytaken = dosage;
            this.chart_bar = chart_bar;
    }
}

export class ProductTaken {
    datetime: Date;
    name: string;
    unit: number;
    products: Product[];

    constructor({datetime, name, unit, product} )  {
        this.datetime = new Date(datetime) ;
        this.name = name;
        this.unit = unit;
        this.products = product ;
        }
}
</code>```

答:
I have sort of found a solution but does anyone know if there is a better way then using forEach.</p>

```<code>class Product {
    eating_time: Date;
    qtytaken: number;
    chart_bar = 1;

    constructor(eating_time, qtytaken, chart_bar )  {
            this.eating_time = new Date(eating_time);
            this.qtytaken = dosage;
            this.chart_bar = chart_bar;
    }
}

export class ProductTaken {
    datetime: Date;
    name: string;
    unit: number;
    products: Product[];

    constructor({datetime, name, unit, product} )  {
        this.datetime = new Date(datetime) ;
        this.name = name;
        this.unit = unit;
        let prodarray = [];
        product.forEach(function(element) {
          prodarray.push(new Product(element.eating_time, element.qtytaken, element.chart_bar));
        this.products = prodarray ;
        }
}
</code>```

Title: Angular Typescript map array into class

Body:
I have data that comes from a web api that looks like below. How do I map the product array into the Products, the reason for me doing that is that I need to transform the eating_time to javascript datetime.

My code below for the class where this.products = product will only store the array and the the list of product.

//Data from API

[ {datetime: "2017-06-25T07:45:00+08:00", name: "Apple", unit: 1, product: [{eating_time: "2017-06-25T07:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T17:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T23:55:00+08:00", qtytaken: 1, chart_bar=1 } ]
]

// Class

class Product {
    eating_time: Date;
    qtytaken: number;
    chart_bar = 1;

    constructor({eating_time, qtytaken, chart_bar })  {
            this.eating_time = new Date(eating_time);
            this.qtytaken = dosage;
            this.chart_bar = chart_bar;
    }
}

export class ProductTaken {
    datetime: Date;
    name: string;
    unit: number;
    products: Product[];

    constructor({datetime, name, unit, product} )  {
        this.datetime = new Date(datetime) ;
        this.name = name;
        this.unit = unit;
        this.products = product ;
        }
}

Body:
I have sort of found a solution but does anyone know if there is a better way then using forEach.

class Product {
    eating_time: Date;
    qtytaken: number;
    chart_bar = 1;

    constructor(eating_time, qtytaken, chart_bar )  {
            this.eating_time = new Date(eating_time);
            this.qtytaken = dosage;
            this.chart_bar = chart_bar;
    }
}

export class ProductTaken {
    datetime: Date;
    name: string;
    unit: number;
    products: Product[];

    constructor({datetime, name, unit, product} )  {
        this.datetime = new Date(datetime) ;
        this.name = name;
        this.unit = unit;
        let prodarray = [];
        product.forEach(function(element) {
          prodarray.push(new Product(element.eating_time, element.qtytaken, element.chart_bar));
        this.products = prodarray ;
        }
}


问:
Cannot resume downloads bigger than 300M
I am working on a program with php to download files.
the script request is like: http://localhost/download.php?file=abc.zip
I use some script mentioned in Resumable downloads when using PHP to send the file?

it definitely works for files under 300M, either multithread or single-thread download, but, when i try to download a file >300M, I get a problem in single-thread downloading, I downloaded only about 250M data, then it seems like the http connection is broken. it doesnot break in the break-point ..Why?
debugging the script, I pinpointed where it broke:

```<code>$max_bf_size = 10240;
$pf = fopen("$file_path", "rb");
fseek($pf, $offset);
while(1)
{
    $rd_length = $length < $max_bf_size? $length:$max_bf_size;
    $data = fread($pf, $rd_length);
    print $data;
    $length = $length - $rd_length;
    if( $length <= 0 )
    {
        //__break-point__
        break;
    }

}
</code>```

this seems like every requested document can only get 250M data buffer to echo or print..But it works when i use a multi-thread to download a file

答:
fread() will read up to the number of bytes you ask for, so you are doing some unnecessary work calculating the number of bytes to read. I don't know what you mean by single-thread and multi-thread downloading. Do you know about readfile() to just dump an entire file? I assume you need to read a portion of the file starting at $offset up to $length bytes, correct?

I'd also check my web server (Apache?) configuration and ISP limits if applicable; your maximum response size or time may be throttled.

Try this:

```<code>define(MAX_BUF_SIZE, 10240);
$pf = fopen($file_path, 'rb');
fseek($pf, $offset);
while (!feof($pf)) {
    $data = fread($pf, MAX_BUF_SIZE);
    if ($data === false)
        break;
    print $data;
}
fclose($pf);
</code>```

Body:
I am working on a program with php to download files.
the script request is like: http://localhost/download.php?file=abc.zip
I use some script mentioned in Resumable downloads when using PHP to send the file?

it definitely works for files under 300M, either multithread or single-thread download, but, when i try to download a file >300M, I get a problem in single-thread downloading, I downloaded only about 250M data, then it seems like the http connection is broken. it doesnot break in the break-point ..Why?
debugging the script, I pinpointed where it broke:

$max_bf_size = 10240;
$pf = fopen("$file_path", "rb");
fseek($pf, $offset);
while(1)
{
    $rd_length = $length < $max_bf_size? $length:$max_bf_size;
    $data = fread($pf, $rd_length);
    print $data;
    $length = $length - $rd_length;
    if( $length <= 0 )
    {
        //__break-point__
        break;
    }

}

this seems like every requested document can only get 250M data buffer to echo or print..But it works when i use a multi-thread to download a file

Body:
fread() will read up to the number of bytes you ask for, so you are doing some unnecessary work calculating the number of bytes to read. I don't know what you mean by single-thread and multi-thread downloading. Do you know about readfile() to just dump an entire file? I assume you need to read a portion of the file starting at $offset up to $length bytes, correct?

I'd also check my web server (Apache?) configuration and ISP limits if applicable; your maximum response size or time may be throttled.

Try this:

define(MAX_BUF_SIZE, 10240);
$pf = fopen($file_path, 'rb');
fseek($pf, $offset);
while (!feof($pf)) {
    $data = fread($pf, MAX_BUF_SIZE);
    if ($data === false)
        break;
    print $data;
}
fclose($pf);

ContentLicense: CC BY-SA 2.5


问:
codeanywhere.com Python doesn't see virtualenv
I use codeanywhere.com try to create application with Python werkzeug and jinja2.
I install those library utilize virtualenv. Now I face the problem
Traceback (most recent call last):
    File "manage.py", line 4, in
    from werkzeug import Request
    ImportError: No module named 'werkzeug'

virtualenv activated but nothing is works.
Does anybody has experience with codeanywhere.com?

答:
Oh I solve this problem. In the container config file add instruction "source venv3/bin/activate" as shown on a picture add path to python as well.

enter image description here


问:
Which thread does Runnable run on?
I want to update UI every 100ms. After searching in StackOverflow, I found a solution using Runnable and Handler like this

```<code>final Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        //update UI here

        handler.postDelayed(this, 100);
    }
};
runnable.run();
</code>```

It works! But I have some questions:

Which thread does this Runnable run on? MainThread or another thread? Here is the docs about postDelay

Handler is attached MainThread, so is Runnable running on MainThread?

If Runnable is running on MainThread, why needs Handler? According to my knowledge, Handler is used to send messages between two threads

答:
Which thread does this Runnable run on?

```<code>Runnable runnable = new Runnable() {
    @Override
    public void run() {
        //update UI here

        handler.postDelayed(this, 100);
    }
};
runnable.run()
</code>```

This Runnable runs on the current thread, i.e. the thread that invokes this code. It doesn't magically create, or constitute, another thread. Runnable.run() is only a method call.

The subsequent executions of this thread, by the Handler, in whatever thread the Handler runs in, do essentially nothing except reschedule themselves. It's hard to believe this is a solution to anything.

Title: Which thread does Runnable run on?

Body:
I want to update UI every 100ms. After searching in StackOverflow, I found a solution using Runnable and Handler like this

final Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        //update UI here

        handler.postDelayed(this, 100);
    }
};
runnable.run();

It works! But I have some questions:

Which thread does this Runnable run on? MainThread or another thread? Here is the docs about postDelay

Handler is attached MainThread, so is Runnable running on MainThread?

If Runnable is running on MainThread, why needs Handler? According to my knowledge, Handler is used to send messages between two threads

Body:
Which thread does this Runnable run on?

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        //update UI here

        handler.postDelayed(this, 100);
    }
};
runnable.run()

This Runnable runs on the current thread, i.e. the thread that invokes this code. It doesn't magically create, or constitute, another thread. Runnable.run() is only a method call.

The subsequent executions of this thread, by the Handler, in whatever thread the Handler runs in, do essentially nothing except reschedule themselves. It's hard to believe this is a solution to anything.


问:
Reset time to expire in a Guava Cache
I'm using a Guava Cache Loader and picking up the time to expire from a config file.

I'm wondering if there is a way to programmatically reset the time to expire value for a given cache. In my case this is desirable in the action of a listener that picks up the change to the configured value.

答:
No, there's no way to change the expiration time for a whole cache (short of constructing a new cache and copying the contents of the old cache over). If you're asking about resetting a single entry in the cache that can be done simply by re-putting the value:

```<code>public static void <K, V> resetExpiration(Cache<K, V> cache, K key) {
  V value = cache.getIfPresent(key);
  if (value != null) {
    cache.put(key, value); // basically a no-op, but key's expiration is reset
  }
}
</code>```

Or for an expire-on-access cache just call .get() or .getIfPresent() and that will reset the access expriration.

Title: Reset time to expire in a Guava Cache

Body:
No, there's no way to change the expiration time for a whole cache (short of constructing a new cache and copying the contents of the old cache over). If you're asking about resetting a single entry in the cache that can be done simply by re-putting the value:

public static void <K, V> resetExpiration(Cache<K, V> cache, K key) {
  V value = cache.getIfPresent(key);
  if (value != null) {
    cache.put(key, value); // basically a no-op, but key's expiration is reset
  }
}

Or for an expire-on-access cache just call .get() or .getIfPresent() and that will reset the access expriration.


问:
Javascript executing when jQuery not ready
The following scenario is a problem I am having. I came to the conclusion that jQuery must not be ready when Javascript is executing by observing this scenario.

Scenario:

I have a Java application which injects Javascript script tags into the currently loaded DOM page. The following Java code runs inline Javascript which inserts jquery.js and myCode.js. myCode.js holds my Javascript codes.

```<code> browser.executeJavaScript("var head= document.getElementsByTagName('head')[0];" +
                                "var script= document.createElement('script');script.type= 'text/javascript';script.src= 'jquery.js';head.appendChild(script);" +
                                "var script4= document.createElement('script');script4.type= 'text/javascript';script4.src= 'http://myCode.js';head.appendChild(script4);");
</code>```

In this Java application, I also have a buttonListener that fires a function in myCode.js in ActionPerformed();

```<code>executedJS = browser.executeJavaScript("replaceAllLinks()");
</code>```

The problem that is encountered is nullPointerException at the above line when button is clicked. Accomodating for null case results in endless loop without any changes.

```<code>while(executedJS == null) browser.executeJavaScript("replaceAllLinks()");
</code>```

The cause of the problem was pinpointed down to when jQuery functions, methods are present inside replaceAllLinks(); javascript function. when jQuery, methods were absent, no problems could be observed. There was not one instance of nullPointerException raised.

The only possible underlying issue would be that somehow jQuery library is not fully loaded while replaceAllLinks(); is being executed. If jQuery methods and functions were not in use, it doesn't matter and everything runs okay.

My question is then, how can I make sure that jQuery is fully loaded and available for use?

答:
Every script relying on jQuery should be contained inside a DOM ready function. Such a function normally takes this form:

```<code>$(document).ready(function() {
    /* code here */
});
</code>```

and a shortcut to achieve the same thing would be:

```<code>$(function() {
    /* code here */
});
</code>```

Here's the documentation for further information on the ready method:
http://api.jquery.com/ready/

Body:
The following scenario is a problem I am having. I came to the conclusion that jQuery must not be ready when Javascript is executing by observing this scenario.

Scenario:

I have a Java application which injects Javascript script tags into the currently loaded DOM page. The following Java code runs inline Javascript which inserts jquery.js and myCode.js. myCode.js holds my Javascript codes.

 browser.executeJavaScript("var head= document.getElementsByTagName('head')[0];" +
                                "var script= document.createElement('script');script.type= 'text/javascript';script.src= 'jquery.js';head.appendChild(script);" +
                                "var script4= document.createElement('script');script4.type= 'text/javascript';script4.src= 'http://myCode.js';head.appendChild(script4);");

In this Java application, I also have a buttonListener that fires a function in myCode.js in ActionPerformed();

executedJS = browser.executeJavaScript("replaceAllLinks()");

The problem that is encountered is nullPointerException at the above line when button is clicked. Accomodating for null case results in endless loop without any changes.

while(executedJS == null) browser.executeJavaScript("replaceAllLinks()");

The cause of the problem was pinpointed down to when jQuery functions, methods are present inside replaceAllLinks(); javascript function. when jQuery, methods were absent, no problems could be observed. There was not one instance of nullPointerException raised.

The only possible underlying issue would be that somehow jQuery library is not fully loaded while replaceAllLinks(); is being executed. If jQuery methods and functions were not in use, it doesn't matter and everything runs okay.

My question is then, how can I make sure that jQuery is fully loaded and available for use?

Body:
Every script relying on jQuery should be contained inside a DOM ready function. Such a function normally takes this form:

$(document).ready(function() {
    /* code here */
});

and a shortcut to achieve the same thing would be:

$(function() {
    /* code here */
});

Here's the documentation for further information on the ready method:
http://api.jquery.com/ready/


问:
Load a hidden div with jquery - detect which div
I have a page with some hidden divs and they will show only when their links are clicked.

It will start with this blank summary page

And when About is click it will load about content

And so on.. however, my script right now is not as dynamic as I want it to be. How can I hide which ever div that's currently showing and load the div that is being clicked by user? As for now the script is as if each link is  going to be first clicked by user when page is loaded...

$(function() {
  $.ajaxSetup({
    cache: false
  });

  var ajax_load = "";

  $("#abt-ctrl").click(function() {
    $('#content-services a').removeClass('active');
    $(this).addClass('active');

    $("#service-content").fadeOut('fast', function() {
      $("#service-content").html(ajax_load);
      $("#service-content").fadeIn('slow', function() {
        $("#loader").hide();
        $('#about-content').fadeIn();
      });
    });
  });

  $("#more").click(function() {
    $('#content-services a').removeClass('active');
    $(this).addClass('active');
    $("#service-content").fadeOut('fast', function() {
      $("#service-content").html(ajax_load);
      $("#service-content").fadeIn('slow', function() {
        $("#loader").hide();
        $('#more-content').fadeIn();
      });
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper wrapper-content content-bg content-left-padding">
  <div id="service-content" class="row">
    <h2 style="margin-top: 22px; margin-left: 40px;max-width: 700px;margin-right: 50px;">Summary</h2>
    <p style="margin-left: 40px;max-width: 700px;margin-right: 50px;"></p>

  </div>
  <div id="about-content" class="hideme row">
    <div class="col-lg-12">
      <h2 style="margin-top: 22px; margin-left: 40px;max-width: 700px;margin-right: 50px;">About </h2>
      <p style="margin-top: 41px; margin-left: 40px;max-width: 700px;margin-right: 50px;">
        Gummi bears chocolate caramels biscuit bonbon. Candy donut apple pie. Bear claw apple pie sugar plum tiramisu jelly donut. Liquorice marzipan biscuit gummi bears dragée marshmallow. Jelly-o marshmallow candy pie gummi bears jujubes candy canes pie. Pastry
        gummi bears gummies cheesecake biscuit fruitcake candy canes soufflé soufflé. Chocolate bar apple pie jelly. Jelly croissant chocolate bar icing tart apple pie candy bonbon jelly beans. Chocolate lollipop soufflé tiramisu carrot cake danish sesame
        snaps soufflé.

      </p>
    </div>
  </div>
  <div id="more-content" class="hideme row">
    <div class="col-lg-12">
      <h2 style="margin-top: 22px; margin-left: 40px;max-width: 700px;margin-right: 50px;">More</h2>
      <p style="margin-top: 41px; margin-left: 40px;max-width: 700px;margin-right: 50px;">
        Croissant tart donut bear claw soufflé halvah. Brownie croissant chocolate. Pudding fruitcake gingerbread biscuit chocolate croissant gummi bears. Jujubes powder sugar plum tootsie roll caramels carrot cake tart icing. Cake oat cake chocolate cake gummies
        carrot cake jujubes carrot cake. Sweet cake chocolate cake fruitcake cookie pie gingerbread cupcake cookie. Marshmallow tiramisu wafer croissant tootsie roll. Wafer sweet roll cupcake chocolate cake apple pie croissant marshmallow muffin.
      </p>
    </div>
  </div>
</div></code>```

答:
Just need to implement the toggle functionality.

$('.top').on('click', function() {
 $parent_box = $(this).closest('.box');
 $parent_box.siblings().find('.bottom').hide();
 $parent_box.find('.bottom').toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container .box {
  float: left;
  width: 150px;
  margin: 20px;
}

.container .box .top {
  padding: 12px;
  background-color: #3e1231;
  color: white;
  cursor: pointer;
}

.container .box .bottom {
  padding: 12px;
  background-color: red;
  color: white;
  display: none;
}</code>```

      About

      ABout Me

     Service

      all Services

      Clients

      All Clients

```

Body:
I have a page with some hidden divs and they will show only when their links are clicked.

It will start with this blank summary page

And when About is click it will load about content

And so on.. however, my script right now is not as dynamic as I want it to be. How can I hide which ever div that's currently showing and load the div that is being clicked by user? As for now the script is as if each link is  going to be first clicked by user when page is loaded...

$(function() {
  $.ajaxSetup({
    cache: false
  });

  var ajax_load = "";

  $("#abt-ctrl").click(function() {
    $('#content-services a').removeClass('active');
    $(this).addClass('active');

    $("#service-content").fadeOut('fast', function() {
      $("#service-content").html(ajax_load);
      $("#service-content").fadeIn('slow', function() {
        $("#loader").hide();
        $('#about-content').fadeIn();
      });
    });
  });

  $("#more").click(function() {
    $('#content-services a').removeClass('active');
    $(this).addClass('active');
    $("#service-content").fadeOut('fast', function() {
      $("#service-content").html(ajax_load);
      $("#service-content").fadeIn('slow', function() {
        $("#loader").hide();
        $('#more-content').fadeIn();
      });
    });
  });
});

Summary

About

        Gummi bears chocolate caramels biscuit bonbon. Candy donut apple pie. Bear claw apple pie sugar plum tiramisu jelly donut. Liquorice marzipan biscuit gummi bears dragée marshmallow. Jelly-o marshmallow candy pie gummi bears jujubes candy canes pie. Pastry
        gummi bears gummies cheesecake biscuit fruitcake candy canes soufflé soufflé. Chocolate bar apple pie jelly. Jelly croissant chocolate bar icing tart apple pie candy bonbon jelly beans. Chocolate lollipop soufflé tiramisu carrot cake danish sesame
        snaps soufflé.

More

        Croissant tart donut bear claw soufflé halvah. Brownie croissant chocolate. Pudding fruitcake gingerbread biscuit chocolate croissant gummi bears. Jujubes powder sugar plum tootsie roll caramels carrot cake tart icing. Cake oat cake chocolate cake gummies
        carrot cake jujubes carrot cake. Sweet cake chocolate cake fruitcake cookie pie gingerbread cupcake cookie. Marshmallow tiramisu wafer croissant tootsie roll. Wafer sweet roll cupcake chocolate cake apple pie croissant marshmallow muffin.

Body:
Just need to implement the toggle functionality.

$('.top').on('click', function() {
 $parent_box = $(this).closest('.box');
 $parent_box.siblings().find('.bottom').hide();
 $parent_box.find('.bottom').toggle();
});

.container .box {
  float: left;
  width: 150px;
  margin: 20px;
}

.container .box .top {
  padding: 12px;
  background-color: #3e1231;
  color: white;
  cursor: pointer;
}

.container .box .bottom {
  padding: 12px;
  background-color: red;
  color: white;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="box">
    <div class="top">
      About
    </div>
    <div class="bottom">
      ABout Me
    </div>
  </div>
  <div class="box">
    <div class="top">
     Service
    </div>
    <div class="bottom">
      all Services
    </div>
  </div>
  <div class="box">
    <div class="top">
      Clients
    </div>
    <div class="bottom">
      All Clients
    </div>
  </div>
</div>


问:
ef core select records from tableA with matching fields in tableB
I'm trying to translate a query from raw sql to linq statement in EF Core 2

Query is something like this

```<code>SELECT * FROM TableA
WHERE FieldA = ConditionA
AND FieldB IN (SELECT FieldC FROM TableB WHERE FieldD = ConditionB)
</code>```

FieldA and FieldB are from TableA, FieldC and FieldD are from TableB

I need all fields from TableA and none from TableB returned, so it should be something like

```<code>return Context.TableA
    .Where(x => x.FieldA == ConditionA)
    .[ some code here ]
    .ToList()
</code>```

my current solution is to get two distinct result sets and join them in code, something like this

```<code>var listA = Context.TableA
    .Where(x => x.FieldA == ConditionA).ToList();
var listB = Context.TableB
    .Where(x => x.FieldD == ConditionB).Select(x => x.FieldC).ToList();
listA.RemoveAll(x => !listB.Contains(x.FieldB);
return listA;
</code>```

i hope it works, i still have to run tests on it, but i'm looking for a better solution (if anything exists)

答:
You can simply use Contains function in query like this :

```<code>var ids = Context.TableB
     .Where(p => p.FieldD == conditionD)
     .Select(p => p.FieldC);
var result = Context.TableA
     .Where(p => ids.Contains(p.FieldB))
     .ToList();
</code>```

Body:
I'm trying to translate a query from raw sql to linq statement in EF Core 2

Query is something like this

SELECT * FROM TableA
WHERE FieldA = ConditionA
AND FieldB IN (SELECT FieldC FROM TableB WHERE FieldD = ConditionB)

FieldA and FieldB are from TableA, FieldC and FieldD are from TableB

I need all fields from TableA and none from TableB returned, so it should be something like

return Context.TableA
    .Where(x => x.FieldA == ConditionA)
    .[ some code here ]
    .ToList()

my current solution is to get two distinct result sets and join them in code, something like this

var listA = Context.TableA
    .Where(x => x.FieldA == ConditionA).ToList();
var listB = Context.TableB
    .Where(x => x.FieldD == ConditionB).Select(x => x.FieldC).ToList();
listA.RemoveAll(x => !listB.Contains(x.FieldB);
return listA;

i hope it works, i still have to run tests on it, but i'm looking for a better solution (if anything exists)

Body:
You can simply use Contains function in query like this :

var ids = Context.TableB
     .Where(p => p.FieldD == conditionD)
     .Select(p => p.FieldC);
var result = Context.TableA
     .Where(p => ids.Contains(p.FieldB))
     .ToList();


问:
How to position the legend to the right of the donut chart
Here is my plunkr code, in this position of the legend is at center, how do I position it to the right of the donut chart?

```<code>var svg = d3.select('#chart')
    .append('svg')
    .attr('width', width)
    .attr('height', height)
    .append('g')
    .attr('transform', 'translate(' + (width / 2 - radius) +
        ',' + (height / 2 - radius) + ')');
</code>```

I tried with the above code but it's not working.

答:
Checkout this version of your jsfiddle. I have corrected some calculation to show legend on right side. highlighted code change below.</p>

```<code>// For increasing horizontal space
var width = 600;

// For arranging chart in full space
var svg = d3.select('#chart')
      .append('svg')
      .attr('width', width)
      .attr('height', height)
      .append('g')
      .attr('transform', 'translate(' + (width / 4) +
        ',' + (height / 2) + ')');

// For moving legend to right
var legend = svg.selectAll('.legend')
  .data(color.domain())
  .enter()
  .append('g')
  .attr('class', 'legend')
  .attr('transform', function(d, i) {
     var height = legendRectSize + legendSpacing;
     var offset =  height * color.domain().length / 2;
     var horz = 7 * legendRectSize;
</code>```

Body:
Here is my plunkr code, in this position of the legend is at center, how do I position it to the right of the donut chart?

var svg = d3.select('#chart')
    .append('svg')
    .attr('width', width)
    .attr('height', height)
    .append('g')
    .attr('transform', 'translate(' + (width / 2 - radius) +
        ',' + (height / 2 - radius) + ')');

I tried with the above code but it's not working.

Body:
Checkout this version of your jsfiddle. I have corrected some calculation to show legend on right side. highlighted code change below.

// For increasing horizontal space
var width = 600;

// For arranging chart in full space
var svg = d3.select('#chart')
      .append('svg')
      .attr('width', width)
      .attr('height', height)
      .append('g')
      .attr('transform', 'translate(' + (width / 4) +
        ',' + (height / 2) + ')');

// For moving legend to right
var legend = svg.selectAll('.legend')
  .data(color.domain())
  .enter()
  .append('g')
  .attr('class', 'legend')
  .attr('transform', function(d, i) {
     var height = legendRectSize + legendSpacing;
     var offset =  height * color.domain().length / 2;
     var horz = 7 * legendRectSize;


问:
Android gradle sync issue
This app was running perfectly OK without any issue. Suddenly i saw this gradle sync problems.I'm really stuck and need help. What to do now? I've uninstalled and reinstalled android support repository from SDK manager.

```<code>C:\Users\DELL\AndroidStudioProjects\Prokriti\app\build.gradle
    Error:Error:Failed to resolve: com.android.support:support-annotations:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:appcompat-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:customtabs:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:cardview-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-v4:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-core-utils:27.0.1
Install Repository and sync project
</code>```

build.gradle  (app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.avtro.prokriti.prokriti"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-core-utils:25.3.1'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-messaging:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-ads:11.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.survivingwithandroid:weatherlib:1.6.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.firebase:firebase-storage:11.0.2'
    androidTestCompile 'junit:junit:4.12'
    compile 'javax.inject:javax.inject:1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

build.gradle  (project)

```<code>buildscript {
    repositories {
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

i didnt update android studio or gradle. Android support repository is installed.

答:
```<code>Its work for me
Its work for me
Update Android SDK Build -Tools and SDK platforms
Changed in project build file.
buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
changed in app build file
compileSdkVersion 26
buildToolsVersion "26.0.2"
Disable dependencies inspection.
compile 'com.android.support:design:25.3.1
</code>```

Title: Android gradle sync issue

Body:
This app was running perfectly OK without any issue. Suddenly i saw this gradle sync problems.I'm really stuck and need help. What to do now? I've uninstalled and reinstalled android support repository from SDK manager.

C:\Users\DELL\AndroidStudioProjects\Prokriti\app\build.gradle
    Error:Error:Failed to resolve: com.android.support:support-annotations:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:appcompat-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:customtabs:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:cardview-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-v4:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-core-utils:27.0.1
Install Repository and sync project

build.gradle  (app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.avtro.prokriti.prokriti"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-core-utils:25.3.1'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-messaging:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-ads:11.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.survivingwithandroid:weatherlib:1.6.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.firebase:firebase-storage:11.0.2'
    androidTestCompile 'junit:junit:4.12'
    compile 'javax.inject:javax.inject:1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
}
apply plugin: 'com.google.gms.google-services'

build.gradle  (project)

buildscript {
    repositories {
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

i didnt update android studio or gradle. Android support repository is installed.


问:
SQL select hours from two time fields but between a range
I am using SQL Server 2014 and I have tried several things before asking here.

What I need to accomplish is this:
I have a table which stores two time columns, which have values for example like 9:00 or 2:34 etc etc.

I need to calculate the daily hours and the night hours of works.
The daily hours have to be counted from 8:00 to 20:00 and the night ones from 20:00 to 8:00

If I have two time fields there can be values as

4:00 and 12:00

12:00 and 20:00

22:00 and 6:00

What I want to do is to retrieve two decimal values that correspond to the daily hours and the night hours, maybe there's a SQL function i don't know which passing two values and a range do this task for me, or maybe it's the case to build one on my own

答:
I think you can use an auxiliary table

```<code>CREATE TABLE HourInfo(
  h time NOT NULL,
  isNight bit NOT NULL
CONSTRAINT PK_HourInfo PRIMARY KEY(h)
)
GO

INSERT HourInfo(h,isNight)VALUES
('00:00',1),('01:00',1),('02:00',1),('03:00',1),('04:00',1),('05:00',1),('06:00',1),('07:00',1),('08:00',1),
('09:00',0),('10:00',0),('11:00',0),('12:00',0),('13:00',0),('14:00',0),('15:00',0),('16:00',0),('17:00',0),('18:00',0),('19:00',0),
('20:00',1),('21:00',1),('22:00',1),('23:00',1)
GO

CREATE TABLE MinuteInfo(
  m time NOT NULL,
  isNight bit NOT NULL
CONSTRAINT PK_MinuteInfo PRIMARY KEY(m)
)
GO

INSERT MinuteInfo(m,isNight)
SELECT DATEADD(MINUTE,m.m,h.h) m,h.isNight
FROM HourInfo h
CROSS JOIN
  (
    SELECT i*10+j AS m
    FROM (VALUES(0),(1),(2),(3),(4),(5)) n1(i)
    CROSS JOIN (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) n2(j)
  ) m
GO
</code>```

And use the following query

```<code>SELECT CAST('04:00' AS time) t1,CAST('12:00' AS time) t2 INTO #TestData
UNION ALL
SELECT CAST('12:00' AS time) t1,CAST('20:00' AS time) t2
UNION ALL
SELECT CAST('22:00' AS time) t1,CAST('06:00' AS time) t2
UNION ALL
SELECT CAST('00:00' AS time) t1,CAST('05:15' AS time) t2

/*
SELECT
  d.t1,
  d.t2,
  COUNT(CASE WHEN h.isNight=1 THEN 1 END) [night hours],
  COUNT(CASE WHEN h.isNight=0 THEN 1 END) [daily hours]
FROM #TestData d
JOIN HourInfo h
ON
     (d.t1>d.t2 AND ((h.h>=d.t1 AND h.h<=CAST('23:00' AS time)) OR (h.h>=CAST('00:00' AS time) AND h.h<d.t2)))
  OR (d.t1<=d.t2 AND h.h>=d.t1 AND h.h<=d.t2)
GROUP BY d.t1,d.t2
*/

SELECT
  d.t1,
  d.t2,
  COUNT(CASE WHEN m.isNight=1 THEN 1 END)/60. [night hours],
  COUNT(CASE WHEN m.isNight=0 THEN 1 END)/60. [daily hours]
FROM #TestData d
JOIN MinuteInfo m
ON
     (d.t1>d.t2 AND ((m.m>=d.t1 AND m.m<=CAST('23:59' AS time)) OR (m.m>=CAST('00:00' AS time) AND m.m<d.t2)))
  OR (d.t1<=d.t2 AND m.m>=d.t1 AND m.m<d.t2)
GROUP BY d.t1,d.t2

DROP TABLE #TestData
</code>```

Body:
I think you can use an auxiliary table

CREATE TABLE HourInfo(
  h time NOT NULL,
  isNight bit NOT NULL
CONSTRAINT PK_HourInfo PRIMARY KEY(h)
)
GO

INSERT HourInfo(h,isNight)VALUES
('00:00',1),('01:00',1),('02:00',1),('03:00',1),('04:00',1),('05:00',1),('06:00',1),('07:00',1),('08:00',1),
('09:00',0),('10:00',0),('11:00',0),('12:00',0),('13:00',0),('14:00',0),('15:00',0),('16:00',0),('17:00',0),('18:00',0),('19:00',0),
('20:00',1),('21:00',1),('22:00',1),('23:00',1)
GO

CREATE TABLE MinuteInfo(
  m time NOT NULL,
  isNight bit NOT NULL
CONSTRAINT PK_MinuteInfo PRIMARY KEY(m)
)
GO

INSERT MinuteInfo(m,isNight)
SELECT DATEADD(MINUTE,m.m,h.h) m,h.isNight
FROM HourInfo h
CROSS JOIN
  (
    SELECT i*10+j AS m
    FROM (VALUES(0),(1),(2),(3),(4),(5)) n1(i)
    CROSS JOIN (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) n2(j)
  ) m
GO

And use the following query

SELECT CAST('04:00' AS time) t1,CAST('12:00' AS time) t2 INTO #TestData
UNION ALL
SELECT CAST('12:00' AS time) t1,CAST('20:00' AS time) t2
UNION ALL
SELECT CAST('22:00' AS time) t1,CAST('06:00' AS time) t2
UNION ALL
SELECT CAST('00:00' AS time) t1,CAST('05:15' AS time) t2

/*
SELECT
  d.t1,
  d.t2,
  COUNT(CASE WHEN h.isNight=1 THEN 1 END) [night hours],
  COUNT(CASE WHEN h.isNight=0 THEN 1 END) [daily hours]
FROM #TestData d
JOIN HourInfo h
ON
     (d.t1>d.t2 AND ((h.h>=d.t1 AND h.h<=CAST('23:00' AS time)) OR (h.h>=CAST('00:00' AS time) AND h.h<d.t2)))
  OR (d.t1<=d.t2 AND h.h>=d.t1 AND h.h<=d.t2)
GROUP BY d.t1,d.t2
*/

SELECT
  d.t1,
  d.t2,
  COUNT(CASE WHEN m.isNight=1 THEN 1 END)/60. [night hours],
  COUNT(CASE WHEN m.isNight=0 THEN 1 END)/60. [daily hours]
FROM #TestData d
JOIN MinuteInfo m
ON
     (d.t1>d.t2 AND ((m.m>=d.t1 AND m.m<=CAST('23:59' AS time)) OR (m.m>=CAST('00:00' AS time) AND m.m<d.t2)))
  OR (d.t1<=d.t2 AND m.m>=d.t1 AND m.m<d.t2)
GROUP BY d.t1,d.t2

DROP TABLE #TestData


问:
Is there a better way to design the Message model?
Is there a better way to design the Message model ?

I have a Message model:

```<code>class Message(models.Model):
    """
    message
    """
    title = models.CharField(max_length=64, help_text="title")
    content = models.CharField(max_length=1024, help_text="content")

    is_read = models.BooleanField(default=False, help_text="whether message is read")

    create_user = models.ForeignKey(User, related_name="messages",help_text="creator")
    receive_user = models.CharField(max_length=1024, help_text="receive users' id")

    def __str__(self):
        return self.title
    def __unicode__(self):
        return self.title
</code>```

You see, I use models.CharField to store the users' id, so I can know the users who should receive this row message.

I don't know whether this design type is good. or is there a better way to do that?

I have considered use ManyToMany Field, but I think if user is too many, the admin create one message will create as many as users count, so I think this is not a good idea.

答:
I would definitely use ManyToManyField for your receive_user.  You're going to find that keeping a CharField updated and sanitised with user_ids is going to be a nightmare that will involve re-implementing vast swathes of existing Django functionality.

I'm not sure if I understand your potential issue to using ManyToManyField, users of the admin will be able to select which users are to be recipients of the message, it doesn't automatically a message for each user.

e: Also, depending on which version of python you're using (2 or 3) you only need one of either __str__ or __unicode__

__unicode__ is the method to use for python2, __str__ for python3: See this answer for more details

Body:
Is there a better way to design the Message model ?

I have a Message model:

class Message(models.Model):
    """
    message
    """
    title = models.CharField(max_length=64, help_text="title")
    content = models.CharField(max_length=1024, help_text="content")

    is_read = models.BooleanField(default=False, help_text="whether message is read")

    create_user = models.ForeignKey(User, related_name="messages",help_text="creator")
    receive_user = models.CharField(max_length=1024, help_text="receive users' id")

    def __str__(self):
        return self.title
    def __unicode__(self):
        return self.title

You see, I use models.CharField to store the users' id, so I can know the users who should receive this row message.

I don't know whether this design type is good. or is there a better way to do that?

I have considered use ManyToMany Field, but I think if user is too many, the admin create one message will create as many as users count, so I think this is not a good idea.