问:
looping through a textfile and adding certain strings to a dictionary
So I have a file morsecode.txt that contains

```<code>A2.-B4-...C4-.-.D3-..E1.F4..-.G3--.H4....I2..J4.---K3-.-L4.-..M2--N2-.O3---P4.--.Q4--.-R3.-.S3...T1- all the way to Z.
</code>```

what it does is state the letter "A" has 2 symbols ".-" as its morse equivalent,
the rest of the textfile follows the same order. "B" has 4 symbols "-..." etc...

What I want to do is create a morse dictionary, that stores the alphabetical letter with its morse equivalent.

What I have so far:

```<code>morse_dict=dict()
letter = 1
number = 1
with open('...morse.txt') as f:
    read_letter = f.read(1)
    code_length = f.read(1)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code
</code>```

this returns {'A': '.-'} just as I want it to.

this works for additional letters if you rerun it, i.e:

```<code>with open('...morse.txt') as f:
    read_letter = f.read(1)
    code_length = f.read(1)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code
    read_letter = f.read(1)
    code_length = f.read(1)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code
    read_letter = f.read(1)
    code_length = f.read(1)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code
    read_letter = f.read(1)
    code_length = f.read(1)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code
</code>```

which returns {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..'}.

Now for the problem: I want to create a loop that runs this on the entire textfile.

What i've tried:

```<code>with open('...morse.txt') as f:
while True :
    read_letter = f.read(letter)
    code_length = f.read(number)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code
    if read_letter == '':
        break
</code>```

however, this returns read_code = f.read(int(code_length))
ValueError: invalid literal for int() with base 10: ''

I tried using a for loop and im getting the same error.
in my mind the loop works as following:

```<code>1)reads the letter with f.read(1)
2)reads the number of symbols of the morse equivalent of the letter above with f.read(1)
3) calls the integer given above with f.read(integer) and returns the morse equivalent of the letter
4) stores the given letter with given morse equivalent in a dictionary
5) reruns this entire loop above until it reaches the string '', then it breaks.
</code>```

Im still very new to programming overall, there's probably a much better way of doing this, but i'd very much like some input on how to implement it using steps 1)-4). Any directions are greatly appreciated.

答:
The error messages generally tell you what the problem is, once you get used to them, and it will make debugging much easier.

When it reads the code_length from the file, it expects to find a string that it can convert to an integer. That was not the case. Therefore something is wrong with code_length, because it is an empty string. Looking at the code, I see you detect end of file by looking for that empty string, but you do so AFTER you try to convert it to an integer.

In general, you should check the result of all IO functions. Also, you should expect and handle errors if there is a bad "morse.txt" file, and maybe even make your own exception. But in this case, the file was good, and you just didn't check the read to detect the normal end condition.

```<code>morse_dict = {}
letter = 1
number = 1

with open('morse.txt') as f:
    while True :
        read_letter = f.read(letter)
        if read_letter == '':
            # detect normal end of file, stop reading
            break

        # here is your bug. It can still crash on a bad data file if you don't check code_length here.
        code_length = f.read(number)
        read_code = f.read(int(code_length))
        morse_dict[read_letter] = read_code

import pprint
pprint.pprint(morse_dict)
</code>```

There are also a lot of stack overflow questions for converting a string to integer without raising an exception. Python: Check if a string represents an int, Without using Try/Except? But you want to check it, not just "succeed" at converting it to int(0)

Body:
So I have a file morsecode.txt that contains

A2.-B4-...C4-.-.D3-..E1.F4..-.G3--.H4....I2..J4.---K3-.-L4.-..M2--N2-.O3---P4.--.Q4--.-R3.-.S3...T1- all the way to Z.

what it does is state the letter "A" has 2 symbols ".-" as its morse equivalent,
the rest of the textfile follows the same order. "B" has 4 symbols "-..." etc...

What I want to do is create a morse dictionary, that stores the alphabetical letter with its morse equivalent.

What I have so far:

morse_dict=dict()
letter = 1
number = 1
with open('...morse.txt') as f:
    read_letter = f.read(1)
    code_length = f.read(1)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code

this returns {'A': '.-'} just as I want it to.

this works for additional letters if you rerun it, i.e:

with open('...morse.txt') as f:
    read_letter = f.read(1)
    code_length = f.read(1)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code
    read_letter = f.read(1)
    code_length = f.read(1)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code
    read_letter = f.read(1)
    code_length = f.read(1)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code
    read_letter = f.read(1)
    code_length = f.read(1)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code

which returns {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..'}.

Now for the problem: I want to create a loop that runs this on the entire textfile.

What i've tried:

with open('...morse.txt') as f:
while True :
    read_letter = f.read(letter)
    code_length = f.read(number)
    read_code = f.read(int(code_length))
    morse_dict[read_letter] = read_code
    if read_letter == '':
        break

however, this returns read_code = f.read(int(code_length))
ValueError: invalid literal for int() with base 10: ''

I tried using a for loop and im getting the same error.
in my mind the loop works as following:

1)reads the letter with f.read(1)
2)reads the number of symbols of the morse equivalent of the letter above with f.read(1)
3) calls the integer given above with f.read(integer) and returns the morse equivalent of the letter
4) stores the given letter with given morse equivalent in a dictionary
5) reruns this entire loop above until it reaches the string '', then it breaks.

Im still very new to programming overall, there's probably a much better way of doing this, but i'd very much like some input on how to implement it using steps 1)-4). Any directions are greatly appreciated.

Body:
The error messages generally tell you what the problem is, once you get used to them, and it will make debugging much easier.

When it reads the code_length from the file, it expects to find a string that it can convert to an integer. That was not the case. Therefore something is wrong with code_length, because it is an empty string. Looking at the code, I see you detect end of file by looking for that empty string, but you do so AFTER you try to convert it to an integer.

In general, you should check the result of all IO functions. Also, you should expect and handle errors if there is a bad "morse.txt" file, and maybe even make your own exception. But in this case, the file was good, and you just didn't check the read to detect the normal end condition.

morse_dict = {}
letter = 1
number = 1

with open('morse.txt') as f:
    while True :
        read_letter = f.read(letter)
        if read_letter == '':
            # detect normal end of file, stop reading
            break

        # here is your bug. It can still crash on a bad data file if you don't check code_length here.
        code_length = f.read(number)
        read_code = f.read(int(code_length))
        morse_dict[read_letter] = read_code

import pprint
pprint.pprint(morse_dict)

There are also a lot of stack overflow questions for converting a string to integer without raising an exception. Python: Check if a string represents an int, Without using Try/Except? But you want to check it, not just "succeed" at converting it to int(0)


来源: stackexchange

问:
Unable to access query string params inside AWS Api Gateway
I have configured a resource with a GET method on AWS API Gateway. Integration type is configured as HTTP, but it seems that I cannot access Url Query string parameters without Lambda Functions.

For example
I have api endpoint https://api.domain.com/v1/object/500?param_id=305 and I would like to integrate it with an existing http such as http://somedomain.com/object/500?param_id=305

When I define endpoint URL such as http://somedomain.com/object/{id}?param_id={param_id} I am not able to define param_id as url query string parameter

I am getting a following error:

```<code>Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression parameter specified: method.request.querystring.param_id
</code>```

How can I access query string params without using Lambda functions?

答:
You can use body mapping template in the integration request section and get request body and query strings. Construct a new JSON at body mapping template, which will have data from request body and query string. As we are adding body mapping template your business logic will get the JSON we have constructed at body mapping template.

Inside body mapping template to get query string please do ,

$input.params('querystringkey')

For example inside body mapping template,

#set($inputRoot = $input.path('$'))
{
"firstName" : "$input.path('$.firstName')", //This is to get path variable
"lastName" : "$input.path('$.lastName')"
"language" : "$input.params('$.language')" //This is to get query string
}```

Please read https://aws.amazon.com/blogs/compute/tag/mapping-templates/ for more details on body mapping template

ContentLicense: CC BY-SA 3.0

Body:
I have configured a resource with a GET method on AWS API Gateway. Integration type is configured as HTTP, but it seems that I cannot access Url Query string parameters without Lambda Functions.

For example
I have api endpoint https://api.domain.com/v1/object/500?param_id=305 and I would like to integrate it with an existing http such as http://somedomain.com/object/500?param_id=305

When I define endpoint URL such as http://somedomain.com/object/{id}?param_id={param_id} I am not able to define param_id as url query string parameter

I am getting a following error:

Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression parameter specified: method.request.querystring.param_id

How can I access query string params without using Lambda functions?

Body:
You can use body mapping template in the integration request section and get request body and query strings. Construct a new JSON at body mapping template, which will have data from request body and query string. As we are adding body mapping template your business logic will get the JSON we have constructed at body mapping template.

Inside body mapping template to get query string please do ,

$input.params('querystringkey')

For example inside body mapping template,

#set($inputRoot = $input.path('$'))
{
"firstName" : "$input.path('$.firstName')", //This is to get path variable
"lastName" : "$input.path('$.lastName')"
"language" : "$input.params('$.language')" //This is to get query string
}

Please read https://aws.amazon.com/blogs/compute/tag/mapping-templates/ for more details on body mapping template


问:
How to specify uniqueness for a tuple of field in a Django model
Is there a way to specify a Model in Django such that is ensures that pair of fields in unique in the table, in a way similar to the "unique=True" attribute for similar field?

Or do I need to check this constraint in the clean() method?

答:
There is a META option called unique_together. For example:

```<code>class MyModel(models.Model):
    field1 = models.BlahField()
    field2 = models.FooField()
    field3 = models.BazField()

    class Meta:
        unique_together = ("field1", "field2")
</code>```

More info on the Django documentation page.

OwnerDisplayName: Ber

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Fabian Steeg

Body:
There is a META option called unique_together. For example:

class MyModel(models.Model):
    field1 = models.BlahField()
    field2 = models.FooField()
    field3 = models.BazField()

    class Meta:
        unique_together = ("field1", "field2")

More info on the Django documentation page.

OwnerDisplayName: Baishampayan Ghose

LastEditorDisplayName: Baishampayan Ghose


问:
Rails ActiveRecord update_attributes problems
I am trying to run the update_attributes for a particular object, but everytime I try to run my script, I get the following error: TypeError (can't convert String into Integer):

Here is the code I am working with

```<code>media = Media.find(params[:media_id])
media.update_attributes({:started_encode => false, :encode_success => false, :akamai => false})
</code>```

Any idea why this keeps throwing that error?

答:
You are passing a string to a parameter that is expecting an integer, most likely in `params[:media_id]'. Try:</p>

```<code>media = Media.find(params[:media_id].to_i)
...
</code>```

Body:
I am trying to run the update_attributes for a particular object, but everytime I try to run my script, I get the following error: TypeError (can't convert String into Integer):

Here is the code I am working with

media = Media.find(params[:media_id])
media.update_attributes({:started_encode => false, :encode_success => false, :akamai => false})

Any idea why this keeps throwing that error?

Body:
You are passing a string to a parameter that is expecting an integer, most likely in `params[:media_id]'. Try:

media = Media.find(params[:media_id].to_i)
...


问:
How to add a set on numbers on a two dimensional array based on the results of first row in javascript
I have a two dimensional array:

```<code>var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]];
</code>```

How can I make a new array where in the result would be something like this.

```<code>newArray = [["Alex", 30], ["Sam", 25], ["Rob", 20]];
</code>```

So basically what I want is to get the sum of the numbers for a particular individual.

Any help would be appreciated. I don't know if I have been able to explain the problem properly.

答:
You could take a hash table for same name reference and update the value if a hash exists.

var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]],
    hash = Object.create(null),
    result = array.reduce(function (r, a) {
        if (!hash[a[0]]) {
            hash[a[0]] = a;
            r.push(a);
            return r;
        }
        hash[a[0]][1] += a[1];
        return r;
    }, []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a two dimensional array:

var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]];

How can I make a new array where in the result would be something like this.

newArray = [["Alex", 30], ["Sam", 25], ["Rob", 20]];

So basically what I want is to get the sum of the numbers for a particular individual.

Any help would be appreciated. I don't know if I have been able to explain the problem properly.

Body:
You could take a hash table for same name reference and update the value if a hash exists.

var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]],
    hash = Object.create(null),
    result = array.reduce(function (r, a) {
        if (!hash[a[0]]) {
            hash[a[0]] = a;
            r.push(a);
            return r;
        }
        hash[a[0]][1] += a[1];
        return r;
    }, []);

console.log(result);

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


问:
Convert Map<String, List<Object>> to ArrayList<DataBaseModel>
I am doing batchLoadItem from DynamoDB it comes back in the form:

```<code>Map<String, List<Object>>
</code>```

To test it is coming back correctly i did an iteration over the returned data like this:

```<code>for(Map.Entry<String, List<Object>> entry : individualAlarmsReturnedFromDatabase.entrySet()){
                            List<Object> value = entry.getValue();
                            System.out.println("HASH " + value);
                        }
</code>```

and it returned this in the log:

```<code>HASH [com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@ab28829, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@c36a7ae, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@8f0994f, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@f4188dc, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@cc27de5]
</code>```

This is returning correctly and as you can see the data is in the form of DataBaseModel.

I have tried all the ways I could find on stackoverflow but I don't know how to get it into an ArrayList<DatabaseModel> because it comes back as Map<String, List<Object>>

Thanks

答:
Lino's answer is great. If you can't use Java 8 streams, you can make a simple change to your existing code:</p>

```<code>List<DatabaseModel> models = new ArrayList<DatabaseModel>();
for(Map.Entry<String, List<Object>> entry : individualAlarmsReturnedFromDatabase.entrySet()){
                        List<Object> value = entry.getValue();
                        for(Object valueObj : value)
                            models.add((DatabaseModel)valueObj);
                    }
</code>```

Body:
I am doing batchLoadItem from DynamoDB it comes back in the form:

Map<String, List<Object>>

To test it is coming back correctly i did an iteration over the returned data like this:

for(Map.Entry<String, List<Object>> entry : individualAlarmsReturnedFromDatabase.entrySet()){
                            List<Object> value = entry.getValue();
                            System.out.println("HASH " + value);
                        }

and it returned this in the log:

HASH [com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@ab28829, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@c36a7ae, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@8f0994f, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@f4188dc, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@cc27de5]

This is returning correctly and as you can see the data is in the form of DataBaseModel.

I have tried all the ways I could find on stackoverflow but I don't know how to get it into an ArrayList<DatabaseModel> because it comes back as Map<String, List<Object>>

Thanks

Body:
Lino's answer is great. If you can't use Java 8 streams, you can make a simple change to your existing code:

List<DatabaseModel> models = new ArrayList<DatabaseModel>();
for(Map.Entry<String, List<Object>> entry : individualAlarmsReturnedFromDatabase.entrySet()){
                        List<Object> value = entry.getValue();
                        for(Object valueObj : value)
                            models.add((DatabaseModel)valueObj);
                    }


问:
Using variables in Gradle build script
I am using Gradle in my project. I have a task for doing some extra configuration with my war. I need to build a string to use in my task like, lets say I have:

```<code>task extraStuff{
    doStuff 'org.springframework:spring-web:3.0.6.RELEASE@war'
}
</code>```

This works fine. What I need to do is define version (actually already defined in properties file) and use this in the task like:

```<code>springVersion=3.0.6.RELEASE

task extraStuff{
    doStuff 'org.springframework:spring-web:${springVersion}@war'
}
</code>```

My problem is spring version is not recognised as variable. So how can I pass it inside the string?

答:
If you're developing an Android application using Gradle, you can declare a variable (i.e holding a dependency version) thanks to the keyword def like below:

```<code>def version = '1.2'

dependencies {
  compile "groupId:artifactId:${version}"
}
</code>```

Title: Using variables in Gradle build script

Body:
I am using Gradle in my project. I have a task for doing some extra configuration with my war. I need to build a string to use in my task like, lets say I have:

task extraStuff{
    doStuff 'org.springframework:spring-web:3.0.6.RELEASE@war'
}

This works fine. What I need to do is define version (actually already defined in properties file) and use this in the task like:

springVersion=3.0.6.RELEASE

task extraStuff{
    doStuff 'org.springframework:spring-web:${springVersion}@war'
}

My problem is spring version is not recognised as variable. So how can I pass it inside the string?

Body:
If you're developing an Android application using Gradle, you can declare a variable (i.e holding a dependency version) thanks to the keyword def like below:

def version = '1.2'

dependencies {
  compile "groupId:artifactId:${version}"
}

ContentLicense: CC BY-SA 4.0


问:
How do I read CSV file row by row and update Python script?
I have the following Python 2.7 script:

```<code>import urllib as ul
tracking_id = "abcde=="
encodedtrackingid = ul.quote(tracking_id)
mcid = "123456"

URL = "https://example.com/id?abcd&d_mid="+mcid+"&=124"+encodedtrackingid+"%011"
print URL

from mechanize import Browser
br = Browser()
br.set_handle_robots(False)
response = br.open(URL)
print response.read()

import requests

url = "https://example.net/rest/v1/mbox/4513452615415"

querystring = {"client":"example"}

payload = "{\r\n              \"mbox\" : \"example\",\r\n\"CloudVisitorId\":\""+mcid+"\",\r\n              \"thirdPartyId\": \""+tracking_id+"\",\r\n              \"contentAsJson\": \"true\",\r\n                             \"mboxParameters\": \r\n                             {        \r\n                             \"mboxMCGLH\": \"6\"     \r\n                             }\r\n}\r\n"
headers = {
    'content-type': "application/json",
    'cache-control': "no-cache",
    'postman-token': "289879f645d-1543-e6df-87fb-1cef88f55110c5"
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

print(response.text)
</code>```

What I want to do is the following:

a) Repeat this script by updating the tracking_id and the mcid variable from a CSV file.

The CSV file has no headers and has the following columns:

Column: A - tracking_id
Column: B - mcid

I need the script to read the CSV file run the script for row 1, then repeat the same process for row2, row3, row4 etc. Each time the script runs the tracking_id and the mcid variable updates, and the output of the response variable is stored into a CSV file.

The end result would be a CSV file  that would have the following:
Column A - tracking_id
Column B - mcid
Column C - response

Any help is much appreciated.

Thanks

答:
```<code>import csv

#traceroute
traceroute_output = """
185.86.232.2     0.512 ms    0.453 ms    0.414 ms
188.95.232.58    0.795 ms    0.765 ms    0.731 ms
188.95.232.67    1.493 ms    1.463 ms    1.560 ms
188.1.239.85     1.853 ms    1.827 ms    2.001 ms
"""
reader = csv.reader(traceroute_output.splitlines(), delimiter=' ', skipinitialspace=True)

for row in reader:
    if len(row)< 7:
        #neglecting invalid values
        continue
    key_value = row.pop(0)
</code>```

Here is some sample code which wrote some time ago to parse the CSV file separated by spaces, You can modify according to your requirements. I hope this will be useful.

Body:
I have the following Python 2.7 script:

import urllib as ul
tracking_id = "abcde=="
encodedtrackingid = ul.quote(tracking_id)
mcid = "123456"

URL = "https://example.com/id?abcd&d_mid="+mcid+"&=124"+encodedtrackingid+"%011"
print URL

from mechanize import Browser
br = Browser()
br.set_handle_robots(False)
response = br.open(URL)
print response.read()

import requests

url = "https://example.net/rest/v1/mbox/4513452615415"

querystring = {"client":"example"}

payload = "{\r\n              \"mbox\" : \"example\",\r\n\"CloudVisitorId\":\""+mcid+"\",\r\n              \"thirdPartyId\": \""+tracking_id+"\",\r\n              \"contentAsJson\": \"true\",\r\n                             \"mboxParameters\": \r\n                             {        \r\n                             \"mboxMCGLH\": \"6\"     \r\n                             }\r\n}\r\n"
headers = {
    'content-type': "application/json",
    'cache-control': "no-cache",
    'postman-token': "289879f645d-1543-e6df-87fb-1cef88f55110c5"
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

print(response.text)

What I want to do is the following:

a) Repeat this script by updating the tracking_id and the mcid variable from a CSV file.

The CSV file has no headers and has the following columns:

Column: A - tracking_id
Column: B - mcid

I need the script to read the CSV file run the script for row 1, then repeat the same process for row2, row3, row4 etc. Each time the script runs the tracking_id and the mcid variable updates, and the output of the response variable is stored into a CSV file.

The end result would be a CSV file  that would have the following:
Column A - tracking_id
Column B - mcid
Column C - response

Any help is much appreciated.

Thanks

Body:
import csv

#traceroute
traceroute_output = """
185.86.232.2     0.512 ms    0.453 ms    0.414 ms
188.95.232.58    0.795 ms    0.765 ms    0.731 ms
188.95.232.67    1.493 ms    1.463 ms    1.560 ms
188.1.239.85     1.853 ms    1.827 ms    2.001 ms
"""
reader = csv.reader(traceroute_output.splitlines(), delimiter=' ', skipinitialspace=True)

for row in reader:
    if len(row)< 7:
        #neglecting invalid values
        continue
    key_value = row.pop(0)

Here is some sample code which wrote some time ago to parse the CSV file separated by spaces, You can modify according to your requirements. I hope this will be useful.


问:
Entity Framework Timeouts
I am getting timeouts using the Entity Framework (EF) when using a function import that takes over 30 seconds to complete. I tried the following and have not been able to resolve this issue:

I added Default Command Timeout=300000 to the connection string in the App.Config file in the project that has the EDMX file as suggested here.

This is what my connection string looks like:

<add
    name="MyEntityConnectionString"
    connectionString="metadata=res://*/MyEntities.csdl|res://*/MyEntities.ssdl|
       res://*/MyEntities.msl;
       provider=System.Data.SqlClient;provider connection string="
       Data Source=trekdevbox;Initial Catalog=StarTrekDatabase;
       Persist Security Info=True;User ID=JamesTKirk;Password=IsFriendsWithSpock;
       MultipleActiveResultSets=True;Default Command Timeout=300000;""
    providerName="System.Data.EntityClient" />
```

<p>I tried setting the CommandTimeout in my repository directly like so:</p>

```private TrekEntities context = new TrekEntities();

public IEnumerable<TrekMatches> GetKirksFriends()
{
    this.context.CommandTimeout = 180;
    return this.context.GetKirksFriends();
}
```

<p>What else can I do to get the EF from timing out? This only happens for very large datasets. Everything works fine with small datasets.</p>

<p>Here is one of the errors I'm getting:</p>

<blockquote>
  <p>System.Data.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.</p>
</blockquote>

<hr>

<p>OK - I got this working and it's silly what happened. I had both the connection string with <code>Default Command Timeout=300000</code> and the CommandTimeout set to 180. When I removed the <code>Default Command Timeout</code> from the connection string, it worked. So the answer is to manually set the CommandTimeout in your repository on your context object like so:</p>

```this.context.CommandTimeout = 180;
```

Apparently setting the timeout settings in the connection string has no effect on it.

答:
I know this is very old thread running, but still EF has not fixed this. For people using auto-generated DbContext can use the following code to set the timeout manually.

```<code>public partial class SampleContext : DbContext
{
    public SampleContext()
        : base("name=SampleContext")
    {
        this.SetCommandTimeOut(180);
    }

    public void SetCommandTimeOut(int Timeout)
    {
        var objectContext = (this as IObjectContextAdapter).ObjectContext;
        objectContext.CommandTimeout = Timeout;
    }
}
</code>```

Title: Entity Framework Timeouts

Body:
I am getting timeouts using the Entity Framework (EF) when using a function import that takes over 30 seconds to complete. I tried the following and have not been able to resolve this issue:

I added Default Command Timeout=300000 to the connection string in the App.Config file in the project that has the EDMX file as suggested here.

This is what my connection string looks like:

<add
    name="MyEntityConnectionString"
    connectionString="metadata=res://*/MyEntities.csdl|res://*/MyEntities.ssdl|
       res://*/MyEntities.msl;
       provider=System.Data.SqlClient;provider connection string="
       Data Source=trekdevbox;Initial Catalog=StarTrekDatabase;
       Persist Security Info=True;User ID=JamesTKirk;Password=IsFriendsWithSpock;
       MultipleActiveResultSets=True;Default Command Timeout=300000;""
    providerName="System.Data.EntityClient" />

I tried setting the CommandTimeout in my repository directly like so:

private TrekEntities context = new TrekEntities();

public IEnumerable<TrekMatches> GetKirksFriends()
{
    this.context.CommandTimeout = 180;
    return this.context.GetKirksFriends();
}

What else can I do to get the EF from timing out? This only happens for very large datasets. Everything works fine with small datasets.

Here is one of the errors I'm getting:

System.Data.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

OK - I got this working and it's silly what happened. I had both the connection string with Default Command Timeout=300000 and the CommandTimeout set to 180. When I removed the Default Command Timeout from the connection string, it worked. So the answer is to manually set the CommandTimeout in your repository on your context object like so:

this.context.CommandTimeout = 180;

Apparently setting the timeout settings in the connection string has no effect on it.

Body:
I know this is very old thread running, but still EF has not fixed this. For people using auto-generated DbContext can use the following code to set the timeout manually.

public partial class SampleContext : DbContext
{
    public SampleContext()
        : base("name=SampleContext")
    {
        this.SetCommandTimeOut(180);
    }

    public void SetCommandTimeOut(int Timeout)
    {
        var objectContext = (this as IObjectContextAdapter).ObjectContext;
        objectContext.CommandTimeout = Timeout;
    }
}


问:
How to execute a db2 query with a where condition using runqry command in CL/400
I was trying to execute a IBM DB2 query using runqry command of CLLE, but was unable to do it as it contained a where condition and I was unable to define a host variable in the runqry command. Can this be done by using the runqry command without using qryslt.

Please help me out.

答:
RUNQRY does not support variables.

You can define variables in the Query/400 query, but you must use the Start Query Management Query (STRQMQRY) command to run the query.

Be sure to specify:

```<code>Allow information from QRYDFN  . ALWQRYDFN  *YES`
</code>```

Here's an IBM document that shows how to do it.

```<code>                        Select Records
   Type comparisons, press Enter.  Specify OR to start each new group.
     Tests: EQ, NE, LE, GE, LT, GT, RANGE, LIST, LIKE, IS, ISNOT...

   AND/OR  Field      Test    Value (Field, Number, 'Characters', or ...)
          GLCOMP     EQ      :COMPANY
   AND    GLBRAN     EQ      :BRANCH
   AND    GLACC      EQ      :ACCOUNT
  -----------------------------------------------------------------------
</code>```

```<code>STRQMQRY QMQRY(library/qry-name) ALWQRYDFN(*YES) +
QMFORM(*QMQRY) SETVAR((COMPANY 1) (BRANCH 1) (ACCOUNT 12000))
</code>```

Body:
RUNQRY does not support variables.

You can define variables in the Query/400 query, but you must use the Start Query Management Query (STRQMQRY) command to run the query.

Be sure to specify:

Allow information from QRYDFN  . ALWQRYDFN  *YES`

Here's an IBM document that shows how to do it.

                        Select Records
   Type comparisons, press Enter.  Specify OR to start each new group.
     Tests: EQ, NE, LE, GE, LT, GT, RANGE, LIST, LIKE, IS, ISNOT...

   AND/OR  Field      Test    Value (Field, Number, 'Characters', or ...)
          GLCOMP     EQ      :COMPANY
   AND    GLBRAN     EQ      :BRANCH
   AND    GLACC      EQ      :ACCOUNT
  -----------------------------------------------------------------------

STRQMQRY QMQRY(library/qry-name) ALWQRYDFN(*YES) +
QMFORM(*QMQRY) SETVAR((COMPANY 1) (BRANCH 1) (ACCOUNT 12000))


问:
Why doesn't action fire in my react\redux app?
Currently, I'm working on a small application that utilizes modals. I don't want to use 'ready-to-use' packages like react-modal and instead decided to try to do it on my own.

1) A reducer in src/reducers/modalReducer.js

```<code>const modalReducer = (state = {
  show: true,
}, action) => {
  switch (action.type) {
    case 'TOGGLE_MODAL':
      console.log('reducer worked out')
      state = {...state, show: !state.show }
      break
    default:
        return state
  }
}

export default modalReducer
</code>```

My reducers/index.js

```<code>import { combineReducers } from 'redux'
import modalReducer from './modalReducer'

const reducers = combineReducers({
  modal: modalReducer
})

export default reducers
</code>```

2) A store in src/store.js

```<code>import { createStore } from 'redux'
import reducer from './reducers/index'

export default createStore(reducer)
</code>```

3) A Modal component in src/components/Modal.js. I want this component to be reusable and contain input forms which I'll add later.

```<code>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { toggleModal } from '../actions/index'
import { bindActionCreators } from 'redux'

import '../css/Modal.css'

class Modal extends Component {

  render () {
    if(!this.props.show) {
      return (<h1>FUC YOU</h1>)
    }
    console.log('HELLLO' + this.props.show)

    return (
      <div className='backdrop'>
        <div className='my-modal'>
          <div className='footer'>
            <button className='close-btn' onClick={ () => toggleModal }>
              X
            </button>
          </div>
          <h1>{ this.props.title }</h1>
          <hr/>
          <div>
            { this.props.contents }
          </div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return { show: state.modal.show }
}

const mapDispatchToProps = (dispatch) => {
  return {
    toggleModal: () => dispatch(toggleModal())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Modal)
</code>```

My problem is that when I'm pressing the button x, in my modal nothing happens. It means that I did something wrong when was dispatching actions, but I have no idea what I missed...

At this point I just want my empty modal to be closed when the x button is pressed.

In my index.js I have the following structure:

```<code>import React from 'react'
import ReactDOM from 'react-dom'
import registerServiceWorker from './registerServiceWorker'

import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import store from './store.js'

import App from './components/App'
ReactDOM.render(
  <Provider store = {store} >
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>
  , document.getElementById('root'))
registerServiceWorker()
</code>```

My Modal component is within App

答:
You're not actually calling the toggleModal() action creator.  In addition, you're referencing the imported function, not the function you're getting as props:

```<code>onClick={ () => toggleModal }
</code>```

The immediate fix would be:  onClick={ () => this.props.toggleModal() }.

Having said that, there's two other ways you can improve this code.

First, you can pass toggleModal directly as the handler for onClick, like:

```<code>onClick={this.props.toggleModal}
</code>```

Second, you can replace the mapDispatch function by using the "object shorthand" syntax supported by connect:

```<code>import {toggleModal} from "../actions";

const actions = {toggleModal};

export default connect(mapState, actions)(Modal);
</code>```

Beyond that, I'd encourage you to read my post Practical Redux, Part 10: Managing Modals and Context Menus, which specifically shows how to implement modal dialogs using React and Redux, and points to additional resources on the topic.

Body:
Currently, I'm working on a small application that utilizes modals. I don't want to use 'ready-to-use' packages like react-modal and instead decided to try to do it on my own.

1) A reducer in src/reducers/modalReducer.js

const modalReducer = (state = {
  show: true,
}, action) => {
  switch (action.type) {
    case 'TOGGLE_MODAL':
      console.log('reducer worked out')
      state = {...state, show: !state.show }
      break
    default:
        return state
  }
}

export default modalReducer

My reducers/index.js

import { combineReducers } from 'redux'
import modalReducer from './modalReducer'

const reducers = combineReducers({
  modal: modalReducer
})

export default reducers

2) A store in src/store.js

import { createStore } from 'redux'
import reducer from './reducers/index'

export default createStore(reducer)

3) A Modal component in src/components/Modal.js. I want this component to be reusable and contain input forms which I'll add later.

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { toggleModal } from '../actions/index'
import { bindActionCreators } from 'redux'

import '../css/Modal.css'

class Modal extends Component {

  render () {
    if(!this.props.show) {
      return (
FUC YOU
)
    }
    console.log('HELLLO' + this.props.show)

    return (

            <button className='close-btn' onClick={ () => toggleModal }>
              X
            </button>

{ this.props.title }

            { this.props.contents }

    )
  }
}

const mapStateToProps = (state) => {
  return { show: state.modal.show }
}

const mapDispatchToProps = (dispatch) => {
  return {
    toggleModal: () => dispatch(toggleModal())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Modal)

My problem is that when I'm pressing the button x, in my modal nothing happens. It means that I did something wrong when was dispatching actions, but I have no idea what I missed...

At this point I just want my empty modal to be closed when the x button is pressed.

In my index.js I have the following structure:

import React from 'react'
import ReactDOM from 'react-dom'
import registerServiceWorker from './registerServiceWorker'

import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import store from './store.js'

import App from './components/App'
ReactDOM.render(
  <Provider store = {store} >
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>
  , document.getElementById('root'))
registerServiceWorker()

My Modal component is within App

Body:
You're not actually calling the toggleModal() action creator.  In addition, you're referencing the imported function, not the function you're getting as props:

onClick={ () => toggleModal }

The immediate fix would be:  onClick={ () => this.props.toggleModal() }.

Having said that, there's two other ways you can improve this code.

First, you can pass toggleModal directly as the handler for onClick, like:

onClick={this.props.toggleModal}

Second, you can replace the mapDispatch function by using the "object shorthand" syntax supported by connect:

import {toggleModal} from "../actions";

const actions = {toggleModal};

export default connect(mapState, actions)(Modal);

Beyond that, I'd encourage you to read my post Practical Redux, Part 10: Managing Modals and Context Menus, which specifically shows how to implement modal dialogs using React and Redux, and points to additional resources on the topic.


问:
Visual Studio unable to use debugger (AccessViolationException). Code executing in random order
As of today I can no longer debug any c# code using Visual Studio. If I use the debugger, breakpoints can be hit, but as soon as execution has paused the trouble begins. Pressing Step Into, or Continue will normally generate an AccessViolationException saying the memory is corrupt and kill the current request. If I then run a further web request I will instead get an SEHException (occurred in Unknown Module).

It gets even more odd, in that if the AccessViolationException doesn't trigger, the program counter that shows the next statement jumps randomly. Code is then executed in random order! (until it crashes).

If no breakpoints are hit then the app will run in debug mode just fine (even with the debugger attached).

I am confident it's not a code issue. I can actually reproduce the access violations with a new project and the following code:

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello world");
        Console.WriteLine("Access violation"); // This will throw if breakpoint set
    }
}
</code>```

Have deleted VS cache, deleted .suo, cleaned, and tried safe mode. The one possible suspect is that this is on a Windows 10 preview machine, and there was an update last week. I am not really sure where else to go with this to confirm it, or fix it without reimaging the machine.

答:
This exception appeared to start out of nowhere and certainly caused me some headache, but I was able to resolve my issue by doing the following:

Go into the properties of the affected Projects

Go to the Debug Tab

Uncheck "Enable native code debugging"

Body:
As of today I can no longer debug any c# code using Visual Studio. If I use the debugger, breakpoints can be hit, but as soon as execution has paused the trouble begins. Pressing Step Into, or Continue will normally generate an AccessViolationException saying the memory is corrupt and kill the current request. If I then run a further web request I will instead get an SEHException (occurred in Unknown Module).

It gets even more odd, in that if the AccessViolationException doesn't trigger, the program counter that shows the next statement jumps randomly. Code is then executed in random order! (until it crashes).

If no breakpoints are hit then the app will run in debug mode just fine (even with the debugger attached).

I am confident it's not a code issue. I can actually reproduce the access violations with a new project and the following code:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello world");
        Console.WriteLine("Access violation"); // This will throw if breakpoint set
    }
}

Have deleted VS cache, deleted .suo, cleaned, and tried safe mode. The one possible suspect is that this is on a Windows 10 preview machine, and there was an update last week. I am not really sure where else to go with this to confirm it, or fix it without reimaging the machine.


问:
connect ETIMEDOUT Node.js
I am using a create hook in my Auth0 Delegated Administration Extension.

I am getting this error when trigger the create hook:

```<code>Error: connect ETIMEDOUT xxx.xxx.xxx.xxx:8081
    at Object.exports._errnoException (util.js:1020:11)
    at exports._exceptionWithHostPort (util.js:1043:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
</code>```

Create Hook function is:

```<code>function(ctx, callback) {

    var request = require('request');

    // Perform any asynchronous actions
    var API_URL = "https://example.com:8081/api/saveData";

    var empFirstName = 'Jhone';
    var empId = '123';

    request.post({
            url: API_URL,
            json: {
                firstName: empFirstName,
                userId: empId
            }
        },
        function(error, response, body) {
            if (error) {
                ctx.log('Create failed to '+API_URL+':', error);
                return callback(new Error('Something went wrong. Please try again.'));
            }
            ctx.log('Create successful!  Server responded with:', body);
            return callback(null, {
                /*some data here*/
            });
        });
}
</code>```

I have tried with postman and it works as expected. But with the create hook, I am getting above error.

What could be the issue?

答:
It seems your endpoint is unavailable or not responding.

Are you sure this endpoint handle content-type: application/json ? otherwise try to send it as x-form-www-urlencoded.

```<code>request.post({
    url: MY_URL,
    form: {
        firstName: empFirstName,
        userId: empId
    }
</code>```

Title: connect ETIMEDOUT Node.js

Body:
I am using a create hook in my Auth0 Delegated Administration Extension.

I am getting this error when trigger the create hook:

Error: connect ETIMEDOUT xxx.xxx.xxx.xxx:8081
    at Object.exports._errnoException (util.js:1020:11)
    at exports._exceptionWithHostPort (util.js:1043:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)

Create Hook function is:

function(ctx, callback) {

    var request = require('request');

    // Perform any asynchronous actions
    var API_URL = "https://example.com:8081/api/saveData";

    var empFirstName = 'Jhone';
    var empId = '123';

    request.post({
            url: API_URL,
            json: {
                firstName: empFirstName,
                userId: empId
            }
        },
        function(error, response, body) {
            if (error) {
                ctx.log('Create failed to '+API_URL+':', error);
                return callback(new Error('Something went wrong. Please try again.'));
            }
            ctx.log('Create successful!  Server responded with:', body);
            return callback(null, {
                /*some data here*/
            });
        });
}

I have tried with postman and it works as expected. But with the create hook, I am getting above error.

What could be the issue?

Body:
It seems your endpoint is unavailable or not responding.

Are you sure this endpoint handle content-type: application/json ? otherwise try to send it as x-form-www-urlencoded.

request.post({
    url: MY_URL,
    form: {
        firstName: empFirstName,
        userId: empId
    }


问:
WPF Dependency Property
I'm struggling to get my head around dependency properties in WPF, maybe because the use case I'm looking for is very specific and not well documented.

What I have is a custom control that looks like this (please do ignore all the terrible code, it is temporary!):

```<code><UserControl x:Class="HydroAccessory.Controls.FillGraph"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:HydroAccessory.Controls"
         mc:Ignorable="d"
         SizeChanged="FillGraph_SizeChanged"
         d:DesignHeight="200" d:DesignWidth="300">
<Grid>

    <TextBlock x:Name="PercentageTB" Text="Fill Percentage: 0%" />

</Grid>
</code>```

I call it inside my main window like this:

```<code><controls:FillGraph x:Name="HydroModel" />
</code>```

and the code inside the control is as follows:

```<code>using System;
using System.Windows;
using System.Windows.Controls;

namespace HydroAccessory.Controls
{
public partial class FillGraph : UserControl
{
    private float percentage;
    public float Percentage
    {
        get
        {
            return percentage;
        }
        set
        {
            percentage = value;
            PercentageTB.Text = String.Format("Fill Percentage: {0}", percentage.ToString() + "%");
        }
    }

    public FillGraph()
    {
        InitializeComponent();
    }
}
}
</code>```

All that I want to be able to do is say in my custom control call in the main window:

```<code><controls:FillGraph x:Name="HydroModel" Percentage="{Binding FillPercentage}" />
</code>```

(Where FillPercentage is something in another script that you don't need to worry about).
The control will be expanded, so it needs to stay as a custom control.
I understand I may need dependency properties, but after trying many different ways I cannot figure out how to do this seemingly simple task. Help is appreciated.

答:
There isn't a dependency property in your code.

This is a dependency property:

```<code>public partial class FillGraph : UserControl
{
    public FillGraph()
    {
        InitializeComponent();
    }

    public float Percentage
    {
        get { return (float)GetValue(PercentageProperty); }
        set { SetValue(PercentageProperty, value); }
    }

    //  Using a DependencyProperty as the backing store for Percentage.  This
    //  enables animation, styling, binding, etc...
    public static readonly DependencyProperty PercentageProperty =
        DependencyProperty.Register("Percentage", typeof(float),
                typeof(FillGraph), new PropertyMetadata(0.0f));
}
</code>```

As  Ayyappan Subramanian suggests, the propdp snippet in Visual Studio will help create the boilerplate. Just be careful with the parameters you pass to DependencyProperty.Register(), and make sure the default value you pass to new PropertyMetadata() is the correct type. 0.0f is a float. If you pass integer 0 for a float property, it'll throw an exception at runtime.

The regular property public float Percentage here is optional. It's just there for your code to use. XAML won't ever touch it at all (put breakpoints in the getter and setter if you doubt me). That's part of what's special about dependency properties.

And here's how to use it in your usercontrol XAML. Note the StringFormat parameter to the binding.

```<code><Grid>
    <TextBlock
        Text="{Binding Percentage, RelativeSource={RelativeSource AncestorType=UserControl}, StringFormat='Fill Percentage: {0:#.##}%'}"
        />
</Grid>
</code>```

Note: If your percentage is expressed in the range 0 to 1 rather than 0 to 100, use the p percent format instead. We'll use p2 for two digits after the decimal point. We omit the % because the format string provides that.

```<code>    <TextBlock
        Text="{Binding Percentage, StringFormat='Fill Percentage: {0:p2}', RelativeSource={RelativeSource AncestorType=UserControl}}"
        />
</code>```

This XAML from your question is fine just as it is, assuming that the viewmodel has a FillPercentage property and correctly implements INotifyPropertyChanged:

```<code><controls:FillGraph x:Name="HydroModel" Percentage="{Binding FillPercentage}" />
</code>```

Title: WPF Dependency Property

Body:
I'm struggling to get my head around dependency properties in WPF, maybe because the use case I'm looking for is very specific and not well documented.

What I have is a custom control that looks like this (please do ignore all the terrible code, it is temporary!):

<UserControl x:Class="HydroAccessory.Controls.FillGraph"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:HydroAccessory.Controls"
         mc:Ignorable="d"
         SizeChanged="FillGraph_SizeChanged"
         d:DesignHeight="200" d:DesignWidth="300">
<Grid>

    <TextBlock x:Name="PercentageTB" Text="Fill Percentage: 0%" />

</Grid>

I call it inside my main window like this:

<controls:FillGraph x:Name="HydroModel" />

and the code inside the control is as follows:

using System;
using System.Windows;
using System.Windows.Controls;

namespace HydroAccessory.Controls
{
public partial class FillGraph : UserControl
{
    private float percentage;
    public float Percentage
    {
        get
        {
            return percentage;
        }
        set
        {
            percentage = value;
            PercentageTB.Text = String.Format("Fill Percentage: {0}", percentage.ToString() + "%");
        }
    }

    public FillGraph()
    {
        InitializeComponent();
    }
}
}

All that I want to be able to do is say in my custom control call in the main window:

<controls:FillGraph x:Name="HydroModel" Percentage="{Binding FillPercentage}" />

(Where FillPercentage is something in another script that you don't need to worry about).
The control will be expanded, so it needs to stay as a custom control.
I understand I may need dependency properties, but after trying many different ways I cannot figure out how to do this seemingly simple task. Help is appreciated.

Body:
There isn't a dependency property in your code.

This is a dependency property:

public partial class FillGraph : UserControl
{
    public FillGraph()
    {
        InitializeComponent();
    }

    public float Percentage
    {
        get { return (float)GetValue(PercentageProperty); }
        set { SetValue(PercentageProperty, value); }
    }

    //  Using a DependencyProperty as the backing store for Percentage.  This
    //  enables animation, styling, binding, etc...
    public static readonly DependencyProperty PercentageProperty =
        DependencyProperty.Register("Percentage", typeof(float),
                typeof(FillGraph), new PropertyMetadata(0.0f));
}

As  Ayyappan Subramanian suggests, the propdp snippet in Visual Studio will help create the boilerplate. Just be careful with the parameters you pass to DependencyProperty.Register(), and make sure the default value you pass to new PropertyMetadata() is the correct type. 0.0f is a float. If you pass integer 0 for a float property, it'll throw an exception at runtime.

The regular property public float Percentage here is optional. It's just there for your code to use. XAML won't ever touch it at all (put breakpoints in the getter and setter if you doubt me). That's part of what's special about dependency properties.

And here's how to use it in your usercontrol XAML. Note the StringFormat parameter to the binding.

<Grid>
    <TextBlock
        Text="{Binding Percentage, RelativeSource={RelativeSource AncestorType=UserControl}, StringFormat='Fill Percentage: {0:#.##}%'}"
        />
</Grid>

Note: If your percentage is expressed in the range 0 to 1 rather than 0 to 100, use the p percent format instead. We'll use p2 for two digits after the decimal point. We omit the % because the format string provides that.

    <TextBlock
        Text="{Binding Percentage, StringFormat='Fill Percentage: {0:p2}', RelativeSource={RelativeSource AncestorType=UserControl}}"
        />

This XAML from your question is fine just as it is, assuming that the viewmodel has a FillPercentage property and correctly implements INotifyPropertyChanged:

<controls:FillGraph x:Name="HydroModel" Percentage="{Binding FillPercentage}" />


问:
How to toggle
 in a nested list?
I'm trying to be able to toggle these sub menus one at a time, I'm getting lost in nests and cant quite figure out how to target the correct list item,

I found that I should be using find() instead of children() as it can go deeper in the nest but still no luck in getting it working.

```<code>    <ul>
      <li>Profile</li>
      <li>Edit</li>
      <li class="drop-nav"> <a href="#"> See your products</a>
        <ul>
          <li class="drop-nav"> <a href="#"> Mens </a>
            <ul>
              <li>  <a href="#"> jumpers </a> </li>
              <li>  <a href="#"> t shirts </a> </li>
            </ul>
          </li>
          <li class="drop-nav"> <a href="#">Womens</a>
            <ul>
              <li> <a href="#"> hoodies </a> </li>
              <li> <a href="#"> leggings </a> </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>

 $(".drop-nav").on("click", function(e){
   e.preventDefault();

   });

 li ul{
 display: none;
  }
</code>```

答:
You haven't described about how you activate each sub-menu, so I will describe solution little bit abstractly. Solution is based on your HTML structure an will work if you wouldn't change it.</p>

```<code>$('.drop-nav a').on('click', function() {
  // This next method returns next element in DOM that is after clicked a link.
  // Based on your HTML it would be ul that holds your sub-menu.
  var subMenu = $(this).next();

  // Here using subMenu selector to make something with sub-menu...
  // Example: adding CSS inline to sub. In your situation it may be something else...
  $(subMenu).css({ 'display' : 'block' });
});
</code>```

Title: How to toggle <li> in a nested list?

Body:
I'm trying to be able to toggle these sub menus one at a time, I'm getting lost in nests and cant quite figure out how to target the correct list item,

I found that I should be using find() instead of children() as it can go deeper in the nest but still no luck in getting it working.

Profile

Edit

  See your products

  Mens

   jumpers

   t shirts

 Womens

  hoodies

  leggings

 $(".drop-nav").on("click", function(e){
   e.preventDefault();

   });

 li ul{
 display: none;
  }

Body:
You haven't described about how you activate each sub-menu, so I will describe solution little bit abstractly. Solution is based on your HTML structure an will work if you wouldn't change it.

$('.drop-nav a').on('click', function() {
  // This next method returns next element in DOM that is after clicked a link.
  // Based on your HTML it would be ul that holds your sub-menu.
  var subMenu = $(this).next();

  // Here using subMenu selector to make something with sub-menu...
  // Example: adding CSS inline to sub. In your situation it may be something else...
  $(subMenu).css({ 'display' : 'block' });
});


问:
WebApi Controller is returning class name, not Json. How can I debug this?
Trying to figure out my serialization problem.

When I make a post request to my LoadById method I can't get to serialize my User class, obtaining a MyNamespace.User response instead of a JSON serialized User payload. Other methods work without any issues.

This is Web.Api ApiController..

```<code>public class UserServiceController : System.Web.Http.ApiController
{
  [HttpPost]
  public User LoadById(String id)
  {
     using (UserManager mng = new UserManager())
     {
        user = mng.LoadById(String id);

        //string json = JsonConvert.SerializeObject(user, new JsonSerializerSettings { TraceWriter = traceWriter });
        //Console.WriteLine(traceWriter);
     }
     return user;
  }
}
</code>```

This is the trace for the serialization:

```<code>2017-11-13T15:55:58.237 Info Started serializing MyNamespace.User. Path ''.
2017-11-13T15:55:58.237 Info Finished serializing MyNamespace.User. Path ''.
2017-11-13T15:55:58.237 Verbose Serialized JSON: "MyNamespace.User"
</code>```

Json as string:

```<code> "MyNamespace.User"
</code>```

User class:

```<code>The user class is quite complex, i only have access to the metadata that
doesn't show much.
</code>```

how can I get more info to understand what's happening?

答:
Seemingly, NewtonSoft JsonConvert is unable to serialize your Users class for some reason, and instead of providing Json, is simply returning the name of the class, which would be consistent with the default .ToString() behaviour  (i.e. no override) of a reference type.

As an alternative, it is generally a good idea to provide clean, dedicated ViewModel classes, or even anonymous class projections, when returning data from your WebApi.

This way, the separation of concerns between Domain objects (such as the User object used with the AspNet Identity UserManager) is encapsulated from the payload that clients of your WebApi would be coupled to - this way you can control exactly which fields are exposed on the Api.

```<code>[HttpPost]
public IHttpActionResult LoadById(String id)
{
   using (var mng = new UserManager())
   {
      var domainUser = mng.LoadById(String id);

      var apiUser = new MyUserViewModel
      {
          // Map visible properties ...
          Name = domainUser.UserName,
          // Change the shape
          Address = domainUser.Address.Postal,
          ...
          // Hide fields that shouldn't be externally accessed
      };
      return Ok(apiUser);
   }
}
</code>```

Other Causes

This commonly happens if inherit your Controller from System.Web.MvcController instead of WebApi's System.Web.Http.ApiController. By Example:

```<code>public class Foo
{
    public string Name { get; set; }
}

public class MyController : System.Web.MvcController.Controller
{
    [HttpGet]
    public Foo Index()
    {
        return new Foo{Name = "Bob"};
    }
}
</code>```

GET on /MyController returns the default ToString() of the class (which will default to the name of the type)

```<code>`MyNameSpace.Foo`
</code>```

What you need to do of course is:

```<code>public class MyController : **ApiController**
{
    [HttpGet]
    public Foo Index()
    {
        return new Foo{Name = "Bob"};
    }
}
</code>```

Will give the required

```<code>{
   Name: "Bob"
}
</code>```

Body:
Trying to figure out my serialization problem.

When I make a post request to my LoadById method I can't get to serialize my User class, obtaining a MyNamespace.User response instead of a JSON serialized User payload. Other methods work without any issues.

This is Web.Api ApiController..

public class UserServiceController : System.Web.Http.ApiController
{
  [HttpPost]
  public User LoadById(String id)
  {
     using (UserManager mng = new UserManager())
     {
        user = mng.LoadById(String id);

        //string json = JsonConvert.SerializeObject(user, new JsonSerializerSettings { TraceWriter = traceWriter });
        //Console.WriteLine(traceWriter);
     }
     return user;
  }
}

This is the trace for the serialization:

2017-11-13T15:55:58.237 Info Started serializing MyNamespace.User. Path ''.
2017-11-13T15:55:58.237 Info Finished serializing MyNamespace.User. Path ''.
2017-11-13T15:55:58.237 Verbose Serialized JSON: "MyNamespace.User"

Json as string:

 "MyNamespace.User"

User class:

The user class is quite complex, i only have access to the metadata that
doesn't show much.

how can I get more info to understand what's happening?

Body:
Seemingly, NewtonSoft JsonConvert is unable to serialize your Users class for some reason, and instead of providing Json, is simply returning the name of the class, which would be consistent with the default .ToString() behaviour  (i.e. no override) of a reference type.

As an alternative, it is generally a good idea to provide clean, dedicated ViewModel classes, or even anonymous class projections, when returning data from your WebApi.

This way, the separation of concerns between Domain objects (such as the User object used with the AspNet Identity UserManager) is encapsulated from the payload that clients of your WebApi would be coupled to - this way you can control exactly which fields are exposed on the Api.

[HttpPost]
public IHttpActionResult LoadById(String id)
{
   using (var mng = new UserManager())
   {
      var domainUser = mng.LoadById(String id);

      var apiUser = new MyUserViewModel
      {
          // Map visible properties ...
          Name = domainUser.UserName,
          // Change the shape
          Address = domainUser.Address.Postal,
          ...
          // Hide fields that shouldn't be externally accessed
      };
      return Ok(apiUser);
   }
}

Other Causes

This commonly happens if inherit your Controller from System.Web.MvcController instead of WebApi's System.Web.Http.ApiController. By Example:

public class Foo
{
    public string Name { get; set; }
}

public class MyController : System.Web.MvcController.Controller
{
    [HttpGet]
    public Foo Index()
    {
        return new Foo{Name = "Bob"};
    }
}

GET on /MyController returns the default ToString() of the class (which will default to the name of the type)

`MyNameSpace.Foo`

What you need to do of course is:

public class MyController : **ApiController**
{
    [HttpGet]
    public Foo Index()
    {
        return new Foo{Name = "Bob"};
    }
}

Will give the required

{
   Name: "Bob"
}


问:
Casting to :any breaks type check
In what scenario is it a good idea for the typescript compiler to accept the following:

const foo: string = 7 as any;
```

I would expect some error message like Type any is not assignable to type string. I let a bug slip through to production because I missed an implicit cast to any on a computed property.

答:
any is assignable to anything, that's kind of it's whole point. To understand why it's there it's important to remember that TypeScript is a superset of JavaScript. A lot of JavaScript APIs returns arbitrary objects (such as JSON.*, fetch), and there's no way to write type declarations for them w/o any. Also any is useful for migration of existing code bases from JS to TS.

I let a bug slip through to production because I missed an implicit cast to any on a computed property.

Set strict option in your tsconfig.json to true. That will forbid unknown types from being implicitly cast to any.

Title: Casting to :any breaks type check

Body:
In what scenario is it a good idea for the typescript compiler to accept the following:

const foo: string = 7 as any;

I would expect some error message like Type any is not assignable to type string. I let a bug slip through to production because I missed an implicit cast to any on a computed property.


答:
Simply use a lookup hash object:</p>

```<code>const result = [], hash = {};

for(const [name, val] of array){
  if( hash[name] ) {
    hash[name][1] += val;
  } else {
    result.push( hash[name] = [name, val] );
  }
}
</code>```

Title: How to add a set on numbers on a two dimensional array based on the results of first row in javascript

Body:
I have a two dimensional array:

var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]];

How can I make a new array where in the result would be something like this.

newArray = [["Alex", 30], ["Sam", 25], ["Rob", 20]];

So basically what I want is to get the sum of the numbers for a particular individual.

Any help would be appreciated. I don't know if I have been able to explain the problem properly.

Body:
Simply use a lookup hash object:

const result = [], hash = {};

for(const [name, val] of array){
  if( hash[name] ) {
    hash[name][1] += val;
  } else {
    result.push( hash[name] = [name, val] );
  }
}


问:
swift3 optional value issue
I have a function to get JSON and put the value into a struct (Job). It prints out the value without optional for the var. But it prints out the struct var with optional. Please kindly help to solve this issue.

```<code>var newJob = Job()
var joblist:[Job] = []

func parseJSON(json:Any){
    if let okJSON = json as? [Any]{
        for item in okJSON {
            let infoDictionary = item as! [String:String]
            if let activityid       = infoDictionary["ActivityID"]
            {
                newJob.ActivityID=activityid
                print(activityid)
                print(newJob.ActivityID)
            }

            if let companyname      = infoDictionary["CompanyName"] {newJob.CompanyName=companyname}
            if let quantity         = infoDictionary["Quantity"] {newJob.Quantity=quantity}
            if let coupontitle      = infoDictionary["Title"] {newJob.CouponTitle=coupontitle}
            if let couponterms      = infoDictionary["Terms"] {newJob.CouponTerms=couponterms}
            if let expirdate        = infoDictionary["ExpirDate"] {newJob.ExpirDate=expirdate}
            if let contactperson    = infoDictionary["ContactPerson"] {newJob.ContactPerson=contactperson}
            if let tel              = infoDictionary["TEL"] {newJob.TEL=tel}

            joblist.append(newJob)
        }
        print(joblist)
    }
}
</code>```

Here with the print result:

```<code>3
Optional("3")
2
Optional("2")
1
Optional("1")
[cateringhk.Job(ActivityID: Optional("3"), CompanyName: Optional("ABC\351\233集\351\233集\345\351\233集\345\345\234團"), Quantity: Optional("5"), CouponTitle: Optional("$30現金卷"), CouponTerms: Optional("消費滿$100可以使用\r\n台灯固定环E27灯头 \r\n黑色白色固定扣 \r\n台灯灯罩床头灯具固定环配件 \r\n[交易快照]"), ExpirDate: Optional("2017-11-24"), ContactPerson: Optional("陳先生"), TEL: Optional("96855000")), cateringhk.Job(ActivityID: Optional("2"), CompanyName: Optional("皇上皇點心集團"), Quantity: Optional("31"), CouponTitle: Optional("$30現金卷"), CouponTerms: Optional("消費滿$100可以使用"), ExpirDate: Optional("2017-11-24"), ContactPerson: Optional("陳先生"), TEL: Optional("96855000")), cateringhk.Job(ActivityID: Optional("1"), CompanyName: Optional("八樂園酒樓"), Quantity: Optional("22"), CouponTitle: Optional("$20消費券"), CouponTerms: Optional("每1帳單只可以使用一用一\345\274張消費券"), ExpirDate: Optional("2017-11-24"), ContactPerson: Optional("陳小姐"), TEL: Optional("94567821"))]
</code>```

答:
This behavior is normal if the properties in the struct are also declared as optionals. In this case the unwrapping with optional binding has actually no effect.

To avoid that declare the property as non-optional and assign a default value for example

```<code>struct Job {

  var activityID = ""
  ...

}

   newJob.activityID = infoDictionary["ActivityID"] ?? ""
</code>```

But assigning an empty string twice looks cumbersome. I'd add an initializer to the struct to take a dictionary, declare the properties as constants and handle the default value in the init method.

```<code>struct Job {

  let activityID : String
  ...

  init(dict: [String:String]) {
      activityID = dict["ActivityID"] ?? ""
      ...
  }

}
</code>```

Note:

Please conform to the naming convention that variable names start with a lowercase letter

Title: swift3 optional value issue

Body:
I have a function to get JSON and put the value into a struct (Job). It prints out the value without optional for the var. But it prints out the struct var with optional. Please kindly help to solve this issue.

var newJob = Job()
var joblist:[Job] = []

func parseJSON(json:Any){
    if let okJSON = json as? [Any]{
        for item in okJSON {
            let infoDictionary = item as! [String:String]
            if let activityid       = infoDictionary["ActivityID"]
            {
                newJob.ActivityID=activityid
                print(activityid)
                print(newJob.ActivityID)
            }

            if let companyname      = infoDictionary["CompanyName"] {newJob.CompanyName=companyname}
            if let quantity         = infoDictionary["Quantity"] {newJob.Quantity=quantity}
            if let coupontitle      = infoDictionary["Title"] {newJob.CouponTitle=coupontitle}
            if let couponterms      = infoDictionary["Terms"] {newJob.CouponTerms=couponterms}
            if let expirdate        = infoDictionary["ExpirDate"] {newJob.ExpirDate=expirdate}
            if let contactperson    = infoDictionary["ContactPerson"] {newJob.ContactPerson=contactperson}
            if let tel              = infoDictionary["TEL"] {newJob.TEL=tel}

            joblist.append(newJob)
        }
        print(joblist)
    }
}

Here with the print result:

3
Optional("3")
2
Optional("2")
1
Optional("1")
[cateringhk.Job(ActivityID: Optional("3"), CompanyName: Optional("ABC\351\233集\351\233集\345\351\233集\345\345\234團"), Quantity: Optional("5"), CouponTitle: Optional("$30現金卷"), CouponTerms: Optional("消費滿$100可以使用\r\n台灯固定环E27灯头 \r\n黑色白色固定扣 \r\n台灯灯罩床头灯具固定环配件 \r\n[交易快照]"), ExpirDate: Optional("2017-11-24"), ContactPerson: Optional("陳先生"), TEL: Optional("96855000")), cateringhk.Job(ActivityID: Optional("2"), CompanyName: Optional("皇上皇點心集團"), Quantity: Optional("31"), CouponTitle: Optional("$30現金卷"), CouponTerms: Optional("消費滿$100可以使用"), ExpirDate: Optional("2017-11-24"), ContactPerson: Optional("陳先生"), TEL: Optional("96855000")), cateringhk.Job(ActivityID: Optional("1"), CompanyName: Optional("八樂園酒樓"), Quantity: Optional("22"), CouponTitle: Optional("$20消費券"), CouponTerms: Optional("每1帳單只可以使用一用一\345\274張消費券"), ExpirDate: Optional("2017-11-24"), ContactPerson: Optional("陳小姐"), TEL: Optional("94567821"))]

Body:
This behavior is normal if the properties in the struct are also declared as optionals. In this case the unwrapping with optional binding has actually no effect.

To avoid that declare the property as non-optional and assign a default value for example

struct Job {

  var activityID = ""
  ...

}

   newJob.activityID = infoDictionary["ActivityID"] ?? ""

But assigning an empty string twice looks cumbersome. I'd add an initializer to the struct to take a dictionary, declare the properties as constants and handle the default value in the init method.

struct Job {

  let activityID : String
  ...

  init(dict: [String:String]) {
      activityID = dict["ActivityID"] ?? ""
      ...
  }

}

Note:

Please conform to the naming convention that variable names start with a lowercase letter


问:
passing listbox item index as parameter to objectdataprovider
I am currently attempting to use an object data provider to return the colour that I would like to use as a background for each listbox item, with the colour dependent on that listbox items index.

Basically the parameters passed to the object is the original colour and the listboxitem index, and it will return a colour that is lighter based on what index it is... here is the code i have currently for the object data provider:

```<code>    <ObjectDataProvider ObjectType="{x:Type local:cUserProfiles}"
              MethodName="GetRankColour" x:Key="RankColour">
        <ObjectDataProvider.MethodParameters>
            <Color> {ORIGINAL_COLOUR}<Color/>
            <system:Int16>{LISTBOXITEM INDEX}</system:Int16>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</code>```

I am aware that you cannot do a direct bind because it is not a dependency object and does not conform to the rules for binding, and that you must set it directly... however, i'm not sure where in my listbox item xaml I am supposed to bind back.

Furthermore, upon a long search for the answer to this, I have only found examples where people only change the parameters based on things such as what someone enters into a textbox using this method:-

```<code>{Binding Source={StaticResource RankColour},
                 Path=MethodParameters[1],
                 BindsDirectlyToSource=True,
                 UpdateSourceTrigger=PropertyChanged}
</code>```

I want it to be bound to the listbox index, so not sure what property to put that into.

Second question:
The listbox item does have a label who's content is bound to the listbox item index, however, how can I use the above binding source technique to bind the content, when i always want to bind it to the index?

Thanks for your help in advance! =)

答:
This may seem kinda silly, but have you thought about indirectly linking this using the code behind? That is, using a series of variables and select cases to set the properties you want to. I know that databinding can get to be a real headache - I avoid it if there is another way to pull off the exact same end result, usually.

I really could need a little more detail on what your end goal is (though it could be that my coffee hasn't kicked in enough for me to comprehend English yet, lol). Are you using a database? How do you get the rank for each user?

Body:
I am currently attempting to use an object data provider to return the colour that I would like to use as a background for each listbox item, with the colour dependent on that listbox items index.

Basically the parameters passed to the object is the original colour and the listboxitem index, and it will return a colour that is lighter based on what index it is... here is the code i have currently for the object data provider:

    <ObjectDataProvider ObjectType="{x:Type local:cUserProfiles}"
              MethodName="GetRankColour" x:Key="RankColour">
        <ObjectDataProvider.MethodParameters>
            <Color> {ORIGINAL_COLOUR}<Color/>
            <system:Int16>{LISTBOXITEM INDEX}</system:Int16>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>

I am aware that you cannot do a direct bind because it is not a dependency object and does not conform to the rules for binding, and that you must set it directly... however, i'm not sure where in my listbox item xaml I am supposed to bind back.

Furthermore, upon a long search for the answer to this, I have only found examples where people only change the parameters based on things such as what someone enters into a textbox using this method:-

{Binding Source={StaticResource RankColour},
                 Path=MethodParameters[1],
                 BindsDirectlyToSource=True,
                 UpdateSourceTrigger=PropertyChanged}

I want it to be bound to the listbox index, so not sure what property to put that into.

Second question:
The listbox item does have a label who's content is bound to the listbox item index, however, how can I use the above binding source technique to bind the content, when i always want to bind it to the index?

Thanks for your help in advance! =)


问:
PHP/XML - checking if a node is set
I have an XML document structured like this:

```<code><produkter>
    <produkt>
        <forhandler></forhandler>
        <produktnavn></produktnavn>
        and so on...
    </produkt>
</produkter>
</code>```

I am pulling out data like this:

```<code>$produktnavn = utf8_decode($xmlObject->item($i)->getElementsByTagName('produktnavn')->item(0)->childNodes->item(0)->nodeValue);
</code>```

Now I am looking to do a check to see if the node is present in the XML document at all.

For example... I only want to make the operation above if there actually IS a node called "produktnavn".

I am trying with:

```<code>if (isset($xmlObject->item($i)->forhandler)) {
</code>```

But this doesn't seem to work.

What an I doing wrong?

答:
You could use DOMDocument with  DOMXPath and check the length for the xpath expression.

For example:

```<code>$source = <<<SOURCE
<produkter>
    <produkt>
        <forhandler></forhandler>
        <produktnavn></produktnavn>
    </produkt>
</produkter>
SOURCE;

$xmlObject = new DOMDocument;
$xmlObject->loadXML($source);
$xpath = new DOMXpath($xmlObject);
$elements = $xpath->query('//produktnavn');
if ($elements->length > 0) {
    // present
}
</code>```

Title: PHP/XML - checking if a node is set

Body:
I have an XML document structured like this:

<produkter>
    <produkt>
        <forhandler></forhandler>
        <produktnavn></produktnavn>
        and so on...
    </produkt>
</produkter>

I am pulling out data like this:

$produktnavn = utf8_decode($xmlObject->item($i)->getElementsByTagName('produktnavn')->item(0)->childNodes->item(0)->nodeValue);

Now I am looking to do a check to see if the node is present in the XML document at all.

For example... I only want to make the operation above if there actually IS a node called "produktnavn".

I am trying with:

if (isset($xmlObject->item($i)->forhandler)) {

But this doesn't seem to work.

What an I doing wrong?

Body:
You could use DOMDocument with  DOMXPath and check the length for the xpath expression.

For example:

$source = <<<SOURCE
<produkter>
    <produkt>
        <forhandler></forhandler>
        <produktnavn></produktnavn>
    </produkt>
</produkter>
SOURCE;

$xmlObject = new DOMDocument;
$xmlObject->loadXML($source);
$xpath = new DOMXpath($xmlObject);
$elements = $xpath->query('//produktnavn');
if ($elements->length > 0) {
    // present
}


问:
WebView app with html <audio> element - possible in notification area?
When you visit a website in Chrome and play a <audio> element, chrome adds a notification with a play/pause btn to the notifications area. Is it possible to do the same with a webview app?

I've managed to get things up and running in Android Studio, but can't figure out the notification thing

Any pointers?

Edit: Here's an example of what I mean: https://developers.google.com/web/updates/2015/07/media-notifications Is that even possible?

答:
Here's an example that I made, this is allot for StackOverflow but there's no documentation for this. https://gist.github.com/DrBrad/7574712c6140ccc468212afa04d9e458

Put this in the WebChromeClient.java

```<code>@Override
public void onProgressChanged(final WebView view, int newProgress){
    super.onProgressChanged(view, newProgress);
    if(newProgress == 100){

        String code = "var videoElement;" +
                "for(var i = 0; i < document.getElementsByTagName('video').length; i++){" +
                "    var vid = document.getElementsByTagName('video')[0];" +
                "    vid.onplay = function(){" +
                "        videoElement = vid;" +
                "        JSOUT.videoAction('true');" +
                "    };" +
                "    vid.onpause = function(){" +
                "        videoElement = vid;" +
                "        JSOUT.videoAction('false');" +
                "    };" +
                "}";
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            wv.evaluateJavascript(code, null);
        }else{
            wv.loadUrl("javascript:"+code);
        }
    }
}
</code>```

Put this in the JSInterface.java

```<code>public class JSInterface {

    public static boolean playing;

    @JavascriptInterface
    public void videoAction(String type){
        Log.e("Info", type);

        playing = Boolean.parseBoolean(type);

        if(playing){
            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PLAYING");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.pause);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);

        }else{
            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PAUSED");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.play);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);
        }
    }
}
</code>```

Put this in NotificationPausePlay.java

```<code>public class NotificationPausePlay extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent){
        Log.e("Here", "I am here");

        if(playing){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                wv.evaluateJavascript("videoElement.pause();", null);
            }else{
                wv.loadUrl("javascript:videoElement.pause();");
            }

            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PAUSED");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.play);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);

            playing = false;
        }else{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                wv.evaluateJavascript("videoElement.play();", null);
            }else{
                wv.loadUrl("javascript:videoElement.play();");
            }

            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PLAYING");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.play);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);

            playing = true;
        }
    }
}
</code>```

Put this in the custom_notification.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#e6e6e6">

<ImageView
    android:layout_width="45dp"
    android:layout_height="45dp"
    android:id="@+id/icon"
    android:src="@drawable/icon"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginRight="10dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/title"
    android:textSize="16dp"
    android:textStyle="bold"
    android:textColor="#000000"
    android:singleLine="true"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/icon"
    android:layout_toEndOf="@+id/icon"
    android:layout_toLeftOf="@+id/pausePlay"
    android:layout_toStartOf="@+id/pausePlay" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/desc"
    android:textSize="16dp"
    android:textColor="#5f5f5f"
    android:singleLine="true"
    android:layout_below="@+id/title"
    android:layout_toRightOf="@+id/icon"
    android:layout_toEndOf="@+id/icon"
    android:layout_toLeftOf="@+id/pausePlay"
    android:layout_toStartOf="@+id/pausePlay"/>

<ImageButton
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:id="@+id/pausePlay"
    android:scaleType="fitXY"
    android:background="#e6e6e6"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

</RelativeLayout>
</code>```

add this to the webview

```<code>wv.setWebChromeClient(new webChromeClient());
wv.addJavascriptInterface(new JSInterface(), "JSOUT");
</code>```

add this to the manifest under </activity>

```<code><receiver android:name=".NotificationPausePlay" />
</code>```

Body:
Here's an example that I made, this is allot for StackOverflow but there's no documentation for this. https://gist.github.com/DrBrad/7574712c6140ccc468212afa04d9e458

Put this in the WebChromeClient.java

@Override
public void onProgressChanged(final WebView view, int newProgress){
    super.onProgressChanged(view, newProgress);
    if(newProgress == 100){

        String code = "var videoElement;" +
                "for(var i = 0; i < document.getElementsByTagName('video').length; i++){" +
                "    var vid = document.getElementsByTagName('video')[0];" +
                "    vid.onplay = function(){" +
                "        videoElement = vid;" +
                "        JSOUT.videoAction('true');" +
                "    };" +
                "    vid.onpause = function(){" +
                "        videoElement = vid;" +
                "        JSOUT.videoAction('false');" +
                "    };" +
                "}";
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            wv.evaluateJavascript(code, null);
        }else{
            wv.loadUrl("javascript:"+code);
        }
    }
}

Put this in the JSInterface.java

public class JSInterface {

    public static boolean playing;

    @JavascriptInterface
    public void videoAction(String type){
        Log.e("Info", type);

        playing = Boolean.parseBoolean(type);

        if(playing){
            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PLAYING");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.pause);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);

        }else{
            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PAUSED");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.play);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);
        }
    }
}

Put this in NotificationPausePlay.java

public class NotificationPausePlay extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent){
        Log.e("Here", "I am here");

        if(playing){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                wv.evaluateJavascript("videoElement.pause();", null);
            }else{
                wv.loadUrl("javascript:videoElement.pause();");
            }

            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PAUSED");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.play);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);

            playing = false;
        }else{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                wv.evaluateJavascript("videoElement.play();", null);
            }else{
                wv.loadUrl("javascript:videoElement.play();");
            }

            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PLAYING");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.play);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);

            playing = true;
        }
    }
}

Put this in the custom_notification.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#e6e6e6">

<ImageView
    android:layout_width="45dp"
    android:layout_height="45dp"
    android:id="@+id/icon"
    android:src="@drawable/icon"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginRight="10dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/title"
    android:textSize="16dp"
    android:textStyle="bold"
    android:textColor="#000000"
    android:singleLine="true"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/icon"
    android:layout_toEndOf="@+id/icon"
    android:layout_toLeftOf="@+id/pausePlay"
    android:layout_toStartOf="@+id/pausePlay" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/desc"
    android:textSize="16dp"
    android:textColor="#5f5f5f"
    android:singleLine="true"
    android:layout_below="@+id/title"
    android:layout_toRightOf="@+id/icon"
    android:layout_toEndOf="@+id/icon"
    android:layout_toLeftOf="@+id/pausePlay"
    android:layout_toStartOf="@+id/pausePlay"/>

<ImageButton
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:id="@+id/pausePlay"
    android:scaleType="fitXY"
    android:background="#e6e6e6"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

</RelativeLayout>

add this to the webview

wv.setWebChromeClient(new webChromeClient());
wv.addJavascriptInterface(new JSInterface(), "JSOUT");

add this to the manifest under </activity>

<receiver android:name=".NotificationPausePlay" />