问:
Python 3: Does http.server support ipv6?
Does http.server (http being a Python 3.x module) support ipv6? For instance, using this command-line code (which starts a webserver):

```<code>python -m http.server [port]
</code>```

答:
There is a patch to allow IPv6 bind in http.server in Python 3. I tried it, finding it works on my laptop.
Please visit https://bugs.python.org/issue24209 for more info.
Or just do as following:

Add the lines after + to the file /your/path/to/python/Lib/http/server.py.
Please note lines without + are the original code of server.py.

```<code>    server_address = (bind, port)

+   if ':' in bind:
+       ServerClass.address_family = socket.AF_INET6
+
    HandlerClass.protocal_version = protocol
    httpd = ServerClass(server_address, HandlerClass)
</code>```

Then try:

```<code>python -m http.server -b *your-ipv6-addr* *your-port*
</code>```

Body:
Does http.server (http being a Python 3.x module) support ipv6? For instance, using this command-line code (which starts a webserver):

python -m http.server [port]

Body:
There is a patch to allow IPv6 bind in http.server in Python 3. I tried it, finding it works on my laptop.
Please visit https://bugs.python.org/issue24209 for more info.
Or just do as following:

Add the lines after + to the file /your/path/to/python/Lib/http/server.py.
Please note lines without + are the original code of server.py.

    server_address = (bind, port)

+   if ':' in bind:
+       ServerClass.address_family = socket.AF_INET6
+
    HandlerClass.protocal_version = protocol
    httpd = ServerClass(server_address, HandlerClass)

Then try:

python -m http.server -b *your-ipv6-addr* *your-port*


来源: stackexchange

问:
selecting rank from millions of records
I will ask SO for help since I could not find similar situation, questions/post with my question

Assuming I have millions of records, columns are

user_id - assuming its recorded from 1 to 1,000,000

name - assume its also recorded up to 20 characters in alphabet

score - 0 to 100 assuming its also recorded

date - date it was recorded (timestamp)

```<code>user_id |   name   | score |        date       |
------------------------------------------------
23131   |   name1  |   15  | 2017-01-04 02:01:25
26824   |   name2  |   63  | 2017-01-04 02:41:33
19684   |   name3  |   28  | 2017-01-04 02:56:15
74937   |   name4  |   01  | 2017-01-04 04:07:55
27486   |   name5  |   75  | 2017-01-04 13:07:45
86476   |   name6  |   56  | 2017-01-04 14:21:47
36479   |   name7  |   19  | 2017-01-04 17:11:15
86752   |   name8  |   38  | 2017-01-04 18:22:23
11267   |   name9  |  100  | 2017-01-04 20:34:42
88763   |   name10 |   89  | 2017-01-04 22:45:43
</code>```

I want to know my own rank assuming I know what my user_id is

I also want to get other 10 user records above and below my ranking, let's say my rank is 100, I also want to select user with rank of 90 to 99 (above my rank) and 101 to 110 (below my rank).

if different user has same score order rank by date recorded, earlier record has higher rank.

is it possible?

assuming all records are unique and no index are set.

I know how to sort ranking

```<code>SELECT * FROM record order by score
</code>```

but this would let me select all the records, what are the practical way of selecting specific data without selecting every record?

here is what I would like to achieve

```<code>user_id |   name   | score |        date          |     rank     |
------------------------------------------------------------------
12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |

my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |

86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |
11322   |   namee  |   71  | 2017-01-04 22:51:54  |     109      |
86633   |   namew  |   70  | 2017-01-04 22:55:33  |     110      |
</code>```

ok so here is what I got as of now, sorry that I did not mention anything about not using union or union all, I cannot use that in my project.

but anyway here is my query
I used "multi_query()" function

```<code>$sql = "SELECT score, date FROM table_name WHERE user_id=your_user_id;" //assume you already know your user_id
$sql .= "SELECT name, score, date FROM table_name WHERE score >= your_score ORDER BY score, date LIMIT 10;"; //to get 10 rows that have greater or same score of your score order by date, earlier date is higher rank if score is the same with other user.
$sql .= "SELECT name, score, date table_name WHERE score <= your_score DESC, date ASC LIMIT 10"; //select score less than or equal to my score order by score and date
</code>```

and I get something like this

```<code>my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |
</code>```

```<code>12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |
</code>```

```<code>74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |
my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |
86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |
</code>```

my problem is when using multiple query, it is still the same as doing 3 different query since I have 3 queries, how can I combine it as one? without using union or union all?

and on the 3rd query how can I set my starting point from my data?

答:
Try this</p>

```<code>SELECT user_id, name, score FROM record
WHERE score BETWEEN
CONVERT((SELECT score FROM record WHERE user_id = (SELECT user_id FROM record WHERE score = '100') ), INTEGER) - 10
AND
CONVERT((SELECT score FROM record WHERE user_id = (SELECT user_id FROM record WHERE score = '100') ), INTEGER) + 10
ORDER BY score DESC, date DESC
</code>```

ContentLicense: CC BY-SA 3.0

Title: selecting rank from millions of records

Body:
I will ask SO for help since I could not find similar situation, questions/post with my question

Assuming I have millions of records, columns are

user_id - assuming its recorded from 1 to 1,000,000

name - assume its also recorded up to 20 characters in alphabet

score - 0 to 100 assuming its also recorded

date - date it was recorded (timestamp)

user_id |   name   | score |        date       |
------------------------------------------------
23131   |   name1  |   15  | 2017-01-04 02:01:25
26824   |   name2  |   63  | 2017-01-04 02:41:33
19684   |   name3  |   28  | 2017-01-04 02:56:15
74937   |   name4  |   01  | 2017-01-04 04:07:55
27486   |   name5  |   75  | 2017-01-04 13:07:45
86476   |   name6  |   56  | 2017-01-04 14:21:47
36479   |   name7  |   19  | 2017-01-04 17:11:15
86752   |   name8  |   38  | 2017-01-04 18:22:23
11267   |   name9  |  100  | 2017-01-04 20:34:42
88763   |   name10 |   89  | 2017-01-04 22:45:43

I want to know my own rank assuming I know what my user_id is

I also want to get other 10 user records above and below my ranking, let's say my rank is 100, I also want to select user with rank of 90 to 99 (above my rank) and 101 to 110 (below my rank).

if different user has same score order rank by date recorded, earlier record has higher rank.

is it possible?

assuming all records are unique and no index are set.

I know how to sort ranking

SELECT * FROM record order by score

but this would let me select all the records, what are the practical way of selecting specific data without selecting every record?

here is what I would like to achieve

user_id |   name   | score |        date          |     rank     |
------------------------------------------------------------------
12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |

my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |

86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |
11322   |   namee  |   71  | 2017-01-04 22:51:54  |     109      |
86633   |   namew  |   70  | 2017-01-04 22:55:33  |     110      |

ok so here is what I got as of now, sorry that I did not mention anything about not using union or union all, I cannot use that in my project.

but anyway here is my query
I used "multi_query()" function

$sql = "SELECT score, date FROM table_name WHERE user_id=your_user_id;" //assume you already know your user_id
$sql .= "SELECT name, score, date FROM table_name WHERE score >= your_score ORDER BY score, date LIMIT 10;"; //to get 10 rows that have greater or same score of your score order by date, earlier date is higher rank if score is the same with other user.
$sql .= "SELECT name, score, date table_name WHERE score <= your_score DESC, date ASC LIMIT 10"; //select score less than or equal to my score order by score and date

and I get something like this

my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |

12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |

74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |
my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |
86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |

my problem is when using multiple query, it is still the same as doing 3 different query since I have 3 queries, how can I combine it as one? without using union or union all?

and on the 3rd query how can I set my starting point from my data?

Body:
Try this

SELECT user_id, name, score FROM record
WHERE score BETWEEN
CONVERT((SELECT score FROM record WHERE user_id = (SELECT user_id FROM record WHERE score = '100') ), INTEGER) - 10
AND
CONVERT((SELECT score FROM record WHERE user_id = (SELECT user_id FROM record WHERE score = '100') ), INTEGER) + 10
ORDER BY score DESC, date DESC


问:
Unbind previous events jquery
I'ts possible to unbind  the previos events of a button ,something like that</p>

```<code>$("#my-button").on('click',function(){
        $( "#my-button" ).unbind();
        alert('whatever');
      });
</code>```

答:
TO unbind event used: </p>

```<code>$("#my-button").off('click');
</code>```

Title: Unbind previous events jquery

Body:
I'ts possible to unbind  the previos events of a button ,something like that

$("#my-button").on('click',function(){
        $( "#my-button" ).unbind();
        alert('whatever');
      });

Body:
TO unbind event used:

$("#my-button").off('click');


问:
How can I check if a string contains a specifig character with any digit in front of it in Python 2.7
I've got a question about my code(below). I'm trying to make a function to check if a string contains a gram unit. The code loops checks each string for a g with a digit in front of it. If it find this, it will loop backwards through the indices of the string until the index is not a digit. The code is working for me but I'm wondering how I can improve this code and if there is a better way to do this.

```<code>lines = ["100gr", "pack of 100 gram", "100 g", "great pack of 15 gram", "1 pack of 8", "3 oz = 85 g", "100",]

for lineIndex, line in enumerate(lines): # loop through lines
    line = line.lower() # make line lowercase
    line = "".join(line.split()) # delete whitespaces

    check = False

    for charIndex, char in enumerate(line): # loop through every index from string
        if char == "g" and line[charIndex-1].isdigit() == True: #check for a g with in front a digit
            index = charIndex - 1
            myList = []

            #loop until the index in front is not a digit
            while True:
                if line[index].isdigit() == True:
                    myList.append(line[index])
                    index -= 1
                else:
                    break

            # make a string from the list and print it
            myList.reverse()
            result = ""
            for letter in myList:
                result += letter
            result += "g"
            print("Line: %s\nBecomes: %s" % (line, result))

            # make check False
            check = True

    if check is False:
        print("Line: %s\nDoes not contain grams" % (line))
</code>```

Result of code:

答:
Try this one-liner:

```<code>map(lambda x: (x, map(lambda x: x+'g', re.findall('(\d+)\s*(?=g|gr|gm|gram)', x))) if re.search('(\d+)\s*(?=g|gr|gm|gram)', x) else (x, 'No gram unit'), lines)
</code>```

This returns a list of tuple - (<sentence>, [<quantity_in_grams>, ...])

returns:

```<code>[('100gr', '100g'),
('pack of 100 gram', '100g'),
('100 g', '100g'),
('great pack of 15 gram', '15g'),
('1 pack of 8', 'No gram unit'),
('3 oz = 85 g', '85g'),
('3 oz = 85 g and 200 g', ['85g', '200g']),
('100', 'No gram unit')]
</code>```

Body:
I've got a question about my code(below). I'm trying to make a function to check if a string contains a gram unit. The code loops checks each string for a g with a digit in front of it. If it find this, it will loop backwards through the indices of the string until the index is not a digit. The code is working for me but I'm wondering how I can improve this code and if there is a better way to do this.

lines = ["100gr", "pack of 100 gram", "100 g", "great pack of 15 gram", "1 pack of 8", "3 oz = 85 g", "100",]

for lineIndex, line in enumerate(lines): # loop through lines
    line = line.lower() # make line lowercase
    line = "".join(line.split()) # delete whitespaces

    check = False

    for charIndex, char in enumerate(line): # loop through every index from string
        if char == "g" and line[charIndex-1].isdigit() == True: #check for a g with in front a digit
            index = charIndex - 1
            myList = []

            #loop until the index in front is not a digit
            while True:
                if line[index].isdigit() == True:
                    myList.append(line[index])
                    index -= 1
                else:
                    break

            # make a string from the list and print it
            myList.reverse()
            result = ""
            for letter in myList:
                result += letter
            result += "g"
            print("Line: %s\nBecomes: %s" % (line, result))

            # make check False
            check = True

    if check is False:
        print("Line: %s\nDoes not contain grams" % (line))

Result of code:

Body:
Try this one-liner:

map(lambda x: (x, map(lambda x: x+'g', re.findall('(\d+)\s*(?=g|gr|gm|gram)', x))) if re.search('(\d+)\s*(?=g|gr|gm|gram)', x) else (x, 'No gram unit'), lines)

This returns a list of tuple - (<sentence>, [<quantity_in_grams>, ...])

returns:

[('100gr', '100g'),
('pack of 100 gram', '100g'),
('100 g', '100g'),
('great pack of 15 gram', '15g'),
('1 pack of 8', 'No gram unit'),
('3 oz = 85 g', '85g'),
('3 oz = 85 g and 200 g', ['85g', '200g']),
('100', 'No gram unit')]


问:
How do I bind context to event handler so event and a few more arguments passed to handler function
I have a function:

```<code>function clickButton(event, someArgument) {...}
</code>```

And I need to pass it as event handler in my React component. I'm trying to do something like this:

```<code>onClick={clickButton.bind(this, event, someArgument)}
</code>```

But event is not defined that is predictable.

There should be some trivial solution.

答:
To pass additional data to an event handler in React, you can use an arrow function. This would be the most common solution, but I'll also provide you with a solution using only bind.

```<code>onClick={event => clickButton(event, someArgument)}
</code>```

As you're using an arrow function, there should be no need to bind the this value either.

With bind, you can try something else, but you'll have to modify your handler function a bit too:

```<code>onClick={clickButton.bind(this, someArgument)}

function clickButton(someArgument, event) {

}
</code>```

Personally, I think the arrow function is easier read, but this JSPerf shows that a bound function is more performant, at least at the time of writing.

The results on my machine were as follows:
Opera ran bound functions 30% faster than the arrow functions. While Firefox showed no difference between the two. Strangely though, Opera did get a much higher score across the board. This likely means that Blink is currently much more optimised for ES6 than Gecko is.

Body:
I have a function:

function clickButton(event, someArgument) {...}

And I need to pass it as event handler in my React component. I'm trying to do something like this:

onClick={clickButton.bind(this, event, someArgument)}

But event is not defined that is predictable.

There should be some trivial solution.

Body:
To pass additional data to an event handler in React, you can use an arrow function. This would be the most common solution, but I'll also provide you with a solution using only bind.

onClick={event => clickButton(event, someArgument)}

As you're using an arrow function, there should be no need to bind the this value either.

With bind, you can try something else, but you'll have to modify your handler function a bit too:

onClick={clickButton.bind(this, someArgument)}

function clickButton(someArgument, event) {

}

Personally, I think the arrow function is easier read, but this JSPerf shows that a bound function is more performant, at least at the time of writing.

The results on my machine were as follows:
Opera ran bound functions 30% faster than the arrow functions. While Firefox showed no difference between the two. Strangely though, Opera did get a much higher score across the board. This likely means that Blink is currently much more optimised for ES6 than Gecko is.


问:
Making Push Notifications on release build work again
I have released an app on iOS. Push notifications worked well for ad hoc distribution build. They won't work for released app. I am using PushWizard to send push notifications.
It has been a week and I have tried all of the below :

The signing identities are totally correct, I have signed the released app with the distribution certificate.

The provisioning profile that I have used for release has the correct non - wildcard app ID.

The certificate that is used for sending push on the server is the APN distribution certificate, though I have not replaced it after release of the new version of app, and I don't think that should be an issue.

Is there anything that I am doing wrong that is causing the APNs to send the "invalid token" error? I am using the same device that I used for dev and adhoc to test the release build. Perhaps, is that the problem ?

答:
Have you tested your certificates (.pem) files to be able to connect to APN server using command line?

The most probable issue with 'invalid token' is related to certificate file and private key mismatch.


问:
How to authorize access to Google Cloud Storage API in PHP, without the client library?
I want to access the Google Cloud Storage API directly with my own PHP code, because Google's API library is slow, but I can't figure out how to get authorization to work. See code below.

I am trying to list the files in a "directory" within a Google Cloud Storage bucket (i.e. get all the files with a certain prefix), in PHP code running on App Engine Standard. I found that the native PHP functions (e.g. scandir()) which are implemented to do this on AppEngine are horrifically slow (> 1 second). I'm not talking about huge directories either, maybe 10 files.

I also tried using the Google APIs Client Library, specifically the Objects method, but found it to still be pretty slow, though not quite as bad, like around 0.5 seconds. The strange thing is, when I timed it, the actual "Objects()" call is fast, it's entering the loop ("foreach ($objects as $object)" - but just the first iteration) that's slow! So I think the library may be doing unnecessary work in processing the response. I verified this in "Try this API", looking at the request my browser makes, which takes < 100ms.

So, I want to make and process the API request directly, rather than using Google's slow library. This is the barebones function I wrote:

```<code>function get_files_from_gcs($dir, $data_storage_bucket) {
    $params = array(
        'delimiter' => '/',
        'prefix' => $dir,
        'fields' => 'items/name',);
    $query = http_build_query($params);
    $url = "https://www.googleapis.com/storage/v1/b/" . $data_storage_bucket . "/o?" . $query;
    log_error('Curl URL:'  . $url);
    //  Initiate curl
    $ch = curl_init();
    // Will return the response, if false it print the response
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Set the url
    curl_setopt($ch, CURLOPT_URL, $url);
    // Execute
    $result = curl_exec($ch);
    // Closing
    curl_close($ch);

    $data = json_decode($result, true);
    $filenames = array();
    foreach ($data as $item) {
        if (array_key_exists('name', $item)) {
            $filenames[] = $item['name'];
        }
    }

    return $filenames;
}
</code>```

However, I get an error message in the response:
"Anonymous users does not have storage.objects.list access to bucket ."

I have set public-read ACLs for my bucket like so:

```<code>gsutil defacl ch -u AllUsers:R gs://<MY BUCKET>
gsutil -m acl -r set public-read gs://<MY BUCKET>
</code>```

And I also tried setting the 'project' URL param in my request, and/or creating an API Key and setting the 'key' param. No dice.

So I think I need to get an OAuth token (which I think is kind of silly - my App Engine Standard instance should be able to make requests to my GCS within the same project without any special authorization... but oh well). But honestly, I am pretty lost on how to do this. I've started looking through the Google Client API code, but I can't tell where this is actually happening. Any help would be much appreciated.

答:
If I understand your question correctly, you have a working solution, but it's slow.

On that basis, I would suggest you use a hybrid approach. If you have auth working currently using the library, then keep that code without change. They key bit from the php documentation is:-

```<code>$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token);
</code>```

This is where you get the magical Access Token. Once you have that, you are free to construct your own http/rest calls. All you need to do is instantiate that Access Token into an http Authorization header, thus

Authorization: "Bearer 4979e799a7979b79etc..."

Body:
I want to access the Google Cloud Storage API directly with my own PHP code, because Google's API library is slow, but I can't figure out how to get authorization to work. See code below.

I am trying to list the files in a "directory" within a Google Cloud Storage bucket (i.e. get all the files with a certain prefix), in PHP code running on App Engine Standard. I found that the native PHP functions (e.g. scandir()) which are implemented to do this on AppEngine are horrifically slow (> 1 second). I'm not talking about huge directories either, maybe 10 files.

I also tried using the Google APIs Client Library, specifically the Objects method, but found it to still be pretty slow, though not quite as bad, like around 0.5 seconds. The strange thing is, when I timed it, the actual "Objects()" call is fast, it's entering the loop ("foreach ($objects as $object)" - but just the first iteration) that's slow! So I think the library may be doing unnecessary work in processing the response. I verified this in "Try this API", looking at the request my browser makes, which takes < 100ms.

So, I want to make and process the API request directly, rather than using Google's slow library. This is the barebones function I wrote:

function get_files_from_gcs($dir, $data_storage_bucket) {
    $params = array(
        'delimiter' => '/',
        'prefix' => $dir,
        'fields' => 'items/name',);
    $query = http_build_query($params);
    $url = "https://www.googleapis.com/storage/v1/b/" . $data_storage_bucket . "/o?" . $query;
    log_error('Curl URL:'  . $url);
    //  Initiate curl
    $ch = curl_init();
    // Will return the response, if false it print the response
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Set the url
    curl_setopt($ch, CURLOPT_URL, $url);
    // Execute
    $result = curl_exec($ch);
    // Closing
    curl_close($ch);

    $data = json_decode($result, true);
    $filenames = array();
    foreach ($data as $item) {
        if (array_key_exists('name', $item)) {
            $filenames[] = $item['name'];
        }
    }

    return $filenames;
}

However, I get an error message in the response:
"Anonymous users does not have storage.objects.list access to bucket ."

I have set public-read ACLs for my bucket like so:

gsutil defacl ch -u AllUsers:R gs://<MY BUCKET>
gsutil -m acl -r set public-read gs://<MY BUCKET>

And I also tried setting the 'project' URL param in my request, and/or creating an API Key and setting the 'key' param. No dice.

So I think I need to get an OAuth token (which I think is kind of silly - my App Engine Standard instance should be able to make requests to my GCS within the same project without any special authorization... but oh well). But honestly, I am pretty lost on how to do this. I've started looking through the Google Client API code, but I can't tell where this is actually happening. Any help would be much appreciated.

Body:
If I understand your question correctly, you have a working solution, but it's slow.

On that basis, I would suggest you use a hybrid approach. If you have auth working currently using the library, then keep that code without change. They key bit from the php documentation is:-

$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token);

This is where you get the magical Access Token. Once you have that, you are free to construct your own http/rest calls. All you need to do is instantiate that Access Token into an http Authorization header, thus

Authorization: "Bearer 4979e799a7979b79etc..."


问:
How to use variable defined inside setOnAction outside it?
I have searched all over the internet for a solution to this but nothing seems to work.

What I want to do is use the variable "poeni" that is modified when a button is clicked and display that result in a label that is outside the OnActionEvent.

Here is the part of my code that is giving me trouble.

```<code>//The button
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int poeni = 0; //The variable i want to use outside

                if(odgovor1_1.isSelected()) poeni++;
                if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
                if(odgovor3_2.isSelected()) poeni++;
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);
</code>```

答:
You need to create a mechanism so that the label is updated with the value of the variable. You can create a method and accept an int parameter. When poeni is updated you just need to invoke the method with the updated value. Inside the method you may update the label.

Another approach is to simply have the label defined above and marking it final. You can always set the text on label.

```<code>//The button
    Button rezultat = new Button("Pogledajte Vas rezultat");
    //The label in which I want to display the results
    final  Label lbl_rezultat = new Label();
    rezultat.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            int poeni = 0; //The variable i want to use outside

            if(odgovor1_1.isSelected()) poeni++;
            if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
            if(odgovor3_2.isSelected()) poeni++;
            lbl_rezultat.setText("Vas rezultat je: " + poeni);
        }
    });
</code>```

Body:
I have searched all over the internet for a solution to this but nothing seems to work.

What I want to do is use the variable "poeni" that is modified when a button is clicked and display that result in a label that is outside the OnActionEvent.

Here is the part of my code that is giving me trouble.

//The button
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int poeni = 0; //The variable i want to use outside

                if(odgovor1_1.isSelected()) poeni++;
                if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
                if(odgovor3_2.isSelected()) poeni++;
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);

Body:
You need to create a mechanism so that the label is updated with the value of the variable. You can create a method and accept an int parameter. When poeni is updated you just need to invoke the method with the updated value. Inside the method you may update the label.

Another approach is to simply have the label defined above and marking it final. You can always set the text on label.

//The button
    Button rezultat = new Button("Pogledajte Vas rezultat");
    //The label in which I want to display the results
    final  Label lbl_rezultat = new Label();
    rezultat.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            int poeni = 0; //The variable i want to use outside

            if(odgovor1_1.isSelected()) poeni++;
            if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
            if(odgovor3_2.isSelected()) poeni++;
            lbl_rezultat.setText("Vas rezultat je: " + poeni);
        }
    });


问:
how to split array in ajax?
```<code>var rows_selected = [];
var rowId = data[0]; // conten [24,25,26,27 etc]
var namaFile = data[4]; // content [foto1.JPG, foto2.JPG, foto3.JPG, foto4.JPG ]

//If checkbox is checked and row ID is not in list of selected row IDs
rows_selected.push(rowId,namaFile);

var dataId=[];
$.each(rows_selected, function(index, rowId, namaFile){
  dataId.push(rowId,namaFile);
});
</code>```

in ajax i sent dataId to controller

```<code>$.ajax({
   data: {"iddata": "[{"+dataId+"}]"},
});
</code>```

but in controller iddata receive just one array like this 24,6a5236ee48848e648553a35d64c4f64dJPG,25,a31ea31db31483506fbd95e463d4c8ffJPG,26,042fd1eee499e5bb9c93853c0299b42eJPG,27,e243845bcc0447324d449e37b271c9ebJPG,28,8f331fa2a713f5268ab71698a65185b6JPG

some code in controller

```<code>$iddata=array();
    $iddata=array($_GET['iddata']);
    $a=explode(",", $iddata[0]);
    $b=preg_replace('/[^A-Za-z0-9\-]/', '', $a);
    $jumlahdata=count($b)/2;
    for($i=0;$i<$jumlahdata;$i++)
    {
        //delete on database
       $data=array('id_perjal'=>$b[$i]);
       $this->M_perjal_terpasang->Delete_Foto($data);
        //and i want deleting foto with unlink
       unlink("assets/images/uploads/"$b[$i]);
    }
</code>```

答:
I would start by using a naming convention, and name arrays with plural words, so that you know that namaFiles (plural) is an array, and one element of it is called namaFile (singular). This will avoid some confusion.

Let's say that two checkboxes are checked, and their IDs are different, then you would somehow add two rows to rows_selected. Currently, you push those values one after the other so that you get an array like [24, 'foto1.JPG', 27, 'foto4.JPG'], but you really want to get them grouped in pairs, like this:

```<code>[{rowId: 24, namaFile: 'foto1.JPG'}, {rowId: 27, namaFile: 'foto4.JPG'}]
</code>```

So you should push the values like this (supposing you have an index):

```<code>rows_selected.push( {rowId: rowIds[index], namaFile: namaFiles[index]} );
</code>```

This you would repeat for other pairs that need to be added.

In your Ajax data, you should use a JSON string, like this:

```<code>var ajaxobj = {
   data: {"iddata": JSON.stringify(rows_selected) },
}
</code>```

On the server side you would convert the JSON back to an associative array, and then access the two elements of each pair by their key name:

```<code>$iddata = $_GET['iddata'];
$a = json_decode($iddata, true);
foreach($a as $pair) {
   //delete in database
   $data = array('id_perjal' => $pair['rowId']);
   $this->M_perjal_terpasang->Delete_Foto($data);
   //delete foto with unlink
   unlink("assets/images/uploads/" . $pair['namaFile']);
}
</code>```

Title: how to split array in ajax?

Body:
var rows_selected = [];
var rowId = data[0]; // conten [24,25,26,27 etc]
var namaFile = data[4]; // content [foto1.JPG, foto2.JPG, foto3.JPG, foto4.JPG ]

//If checkbox is checked and row ID is not in list of selected row IDs
rows_selected.push(rowId,namaFile);

var dataId=[];
$.each(rows_selected, function(index, rowId, namaFile){
  dataId.push(rowId,namaFile);
});

in ajax i sent dataId to controller

$.ajax({
   data: {"iddata": "[{"+dataId+"}]"},
});

but in controller iddata receive just one array like this 24,6a5236ee48848e648553a35d64c4f64dJPG,25,a31ea31db31483506fbd95e463d4c8ffJPG,26,042fd1eee499e5bb9c93853c0299b42eJPG,27,e243845bcc0447324d449e37b271c9ebJPG,28,8f331fa2a713f5268ab71698a65185b6JPG

some code in controller

$iddata=array();
    $iddata=array($_GET['iddata']);
    $a=explode(",", $iddata[0]);
    $b=preg_replace('/[^A-Za-z0-9\-]/', '', $a);
    $jumlahdata=count($b)/2;
    for($i=0;$i<$jumlahdata;$i++)
    {
        //delete on database
       $data=array('id_perjal'=>$b[$i]);
       $this->M_perjal_terpasang->Delete_Foto($data);
        //and i want deleting foto with unlink
       unlink("assets/images/uploads/"$b[$i]);
    }

Body:
I would start by using a naming convention, and name arrays with plural words, so that you know that namaFiles (plural) is an array, and one element of it is called namaFile (singular). This will avoid some confusion.

Let's say that two checkboxes are checked, and their IDs are different, then you would somehow add two rows to rows_selected. Currently, you push those values one after the other so that you get an array like [24, 'foto1.JPG', 27, 'foto4.JPG'], but you really want to get them grouped in pairs, like this:

[{rowId: 24, namaFile: 'foto1.JPG'}, {rowId: 27, namaFile: 'foto4.JPG'}]

So you should push the values like this (supposing you have an index):

rows_selected.push( {rowId: rowIds[index], namaFile: namaFiles[index]} );

This you would repeat for other pairs that need to be added.

In your Ajax data, you should use a JSON string, like this:

var ajaxobj = {
   data: {"iddata": JSON.stringify(rows_selected) },
}

On the server side you would convert the JSON back to an associative array, and then access the two elements of each pair by their key name:

$iddata = $_GET['iddata'];
$a = json_decode($iddata, true);
foreach($a as $pair) {
   //delete in database
   $data = array('id_perjal' => $pair['rowId']);
   $this->M_perjal_terpasang->Delete_Foto($data);
   //delete foto with unlink
   unlink("assets/images/uploads/" . $pair['namaFile']);
}


问:
Python pexpect - python 2.6 - unable to print variable and > in one line
I am trying to concatenate string + variable + string
picks up the variable from the file using Python

```<code>with open("file.txt") as fh:
for line line in fh:
d = "c:/" + xyz + ">"
print d
</code>```

it prints c:/xyz
>
I wanted the output as "c:/xyz>". When i am trying in interactive mode it prints it fine.

答:
It's hard to understand the question because of the weird formatting, but in any case try using the format method:

```<code> d = "c:/{}>".format(xyz.strip('\n'))
</code>```

Body:
I am trying to concatenate string + variable + string
picks up the variable from the file using Python

with open("file.txt") as fh:
for line line in fh:
d = "c:/" + xyz + ">"
print d

it prints c:/xyz
>
I wanted the output as "c:/xyz>". When i am trying in interactive mode it prints it fine.

Body:
It's hard to understand the question because of the weird formatting, but in any case try using the format method:

 d = "c:/{}>".format(xyz.strip('\n'))


问:
Error in trigger
Can anybody please tell me what is wrong with this trigger? I have spend 1 hour trying to solve it but unfortunately no success, thank you.

```<code>DELIMITER $$
CREATE TRIGGER  `pt_hotels_zero_check`BEFORE INSERT ON pt_hotels
FOR EACH ROW
BEGIN
IF(pt_hotels.touroperator_of = 0) THEN
    SIGNAL '45000'
    SET MESSAGE_TEXT = '0 value not allowed';
END IF;
END$$
DELIMITER ;
</code>```

i get this error:

```<code>#1064 - You have an error in your SQL syntax; check the manual that    corresponds to your MariaDB server version for the right syntax to use near ''45000'
    SET MESSAGE_TEXT = '0 value not allowed';
END IF;
</code>```

END' at line 5

答:
The proper syntax for the SIGNAL statement is:

```<code>SIGNAL SQLSTATE '45000'
  SET MESSAGE_TEXT = '0 value not allowed';
</code>```

See the doc at:
https://dev.mysql.com/doc/refman/5.5/en/signal.html

Title: Error in trigger

Body:
Can anybody please tell me what is wrong with this trigger? I have spend 1 hour trying to solve it but unfortunately no success, thank you.

DELIMITER $$
CREATE TRIGGER  `pt_hotels_zero_check`BEFORE INSERT ON pt_hotels
FOR EACH ROW
BEGIN
IF(pt_hotels.touroperator_of = 0) THEN
    SIGNAL '45000'
    SET MESSAGE_TEXT = '0 value not allowed';
END IF;
END$$
DELIMITER ;

i get this error:

#1064 - You have an error in your SQL syntax; check the manual that    corresponds to your MariaDB server version for the right syntax to use near ''45000'
    SET MESSAGE_TEXT = '0 value not allowed';
END IF;

END' at line 5

Body:
The proper syntax for the SIGNAL statement is:

SIGNAL SQLSTATE '45000'
  SET MESSAGE_TEXT = '0 value not allowed';

See the doc at:
https://dev.mysql.com/doc/refman/5.5/en/signal.html


问:
Method RegExp.prototype.exec called on incompatible receiver
Recently, I met a trouble with RegExp.prototype. As normal, RegExp.prototype is an empty regular expression, but, I try to use RegExp.prototype.test('') in console , it will be wrong. Why it will show error

答:
console.log(RegExp.prototype.test.toString());
//RegExp.prototype.test is a native function
//if you want call this function,you should new a Regexp
console.log(new RegExp(/^$/).test(''));```

ContentLicense: CC BY-SA 4.0


问:
how to copy Folders - FAKE F#MAKE
I am using  Copy function of FAKE to copy files from project1 to release folder ,I am using below code :

```<code>Target "CopyProject1" (fun _ ->
    !!(buildDir @@ "/_PublishWebsites/Project1/**/*.*")
        |> Copy releaseDir
)
</code>```

to copy files from Project1 folder to release folder , then all files inside Project1 are being copied to release folder , but I want to maintain folder structure of Project1 inside my release folder , i.e. I want to copy folders of Project1 to release , Is this possible or I will have to create subfolders inside my release folders and copy one by one .and if there is no such way of doing this then is this possible using custom task?

If anyone can help in this regard , that would be really helpful.

答:
That's available through CopyWithSubfoldersTo. It's description says that it:

Copies several file groups, each represented by a FileIncludes object, to the target folder preserving the folder structure starting from the BaseDirectory of each FileIncludes.

The parameters are the same as Copy:

```<code>Target "CopyProject1" (fun _ ->
    [!!(buildDir @@ "/_PublishWebsites/Project1/**/*.*")]
        |> CopyWithSubfoldersTo releaseDir
)
</code>```

EDIT

CopyWithSubfoldersTo works with seq<FileInculdes> while !! returns a single FileIncludes. This has to be converted to a single element list before it can be used.

Title: how to copy Folders - FAKE F#MAKE

Body:
I am using  Copy function of FAKE to copy files from project1 to release folder ,I am using below code :

Target "CopyProject1" (fun _ ->
    !!(buildDir @@ "/_PublishWebsites/Project1/**/*.*")
        |> Copy releaseDir
)

to copy files from Project1 folder to release folder , then all files inside Project1 are being copied to release folder , but I want to maintain folder structure of Project1 inside my release folder , i.e. I want to copy folders of Project1 to release , Is this possible or I will have to create subfolders inside my release folders and copy one by one .and if there is no such way of doing this then is this possible using custom task?

If anyone can help in this regard , that would be really helpful.

Body:
That's available through CopyWithSubfoldersTo. It's description says that it:

Copies several file groups, each represented by a FileIncludes object, to the target folder preserving the folder structure starting from the BaseDirectory of each FileIncludes.

The parameters are the same as Copy:

Target "CopyProject1" (fun _ ->
    [!!(buildDir @@ "/_PublishWebsites/Project1/**/*.*")]
        |> CopyWithSubfoldersTo releaseDir
)

EDIT

CopyWithSubfoldersTo works with seq<FileInculdes> while !! returns a single FileIncludes. This has to be converted to a single element list before it can be used.


问:
Jquery/Ajax Modal is not loading
I am having a problem opening up my modal. I am not sure where the problem lies. rental_id is the primary key for the table in database.</p>

```<code><script>
    function detailsmodal(rental_id){
        var data = {"rental_id" : rental_id};
        jQuery.ajax({
            url : <?=BASEURL;?>+'includes/detailsmodal.php',
            method : "post",
            data : data,
            success: function(data){
                jQuery('body').append(data);
                jQuery('#quote').modal('toggle');
            },
            error: function(){
                alert("Something went wrong!");
            }
        });
    }
</script>
</code>```

答:
use

```<code> jQuery('#quote').modal('show');
</code>```

as i noticed "toggle" not working sometimes

Title: Jquery/Ajax Modal is not loading

Body:
use

 jQuery('#quote').modal('show');

as i noticed "toggle" not working sometimes


答:
You can use array elements or associative array members as storage, instead of files. They're stored in the memory, so of course, usable only for reasonable small content.

E.g. you can:

```<code>declare -a res
for file in md*/*; do
    res+=( "$(./myscript.sh "$file")" ) #each result as an element of array
done
#here you have the results stored as an array elements

#the $final variable will store the whole output
final=("${res[@]:1}") #store the 1st elemnt to "final" and remove it from the array

# for all remaining elements
# use the "pr" utility for the append up the $width width
width=$(tput cols) #maybe you will need define much larger width...
for ele in "${res[@]}"; do
    final=$(pr -w$width -t -m <(echo "$final") <(echo "$ele"))
done
echo "$final"
</code>```

finally, i do not understand the

I want to avoid first write temporary file and then paste all files.

It is much easier and simpler use temp-files as this in-memory array solution. Just read @Leon comments!

Title: Append data horizontally to file in bash

Body:
for file in md*/*; do ./myscript.sh "$file" >> result.out; done
I use the above command to print output from myscript and append result to result.out. Data in result.out can be seen below.

---------------------------------------------------
Report for logfile = ABC/a.log
---------------------------------------------------
ErrorCode         0 12.9.13.43
Time_req
2015-03-29 count     1082.000000
           mean    159297.302218
           std     143091.598683
           min      94656.000000
           25%     115803.250000
           50%     128557.000000
           75%     145264.250000
           max    2580735.000000

---------------------------------------------------
Report for logfile = def/c.log
---------------------------------------------------
ErrorCode         0 12.9.13.52   1 12.9.13.51  2 12.9.13.46
Time_req
2015-03-28 count    7.820000e+02       771.000000    7.730000e+02
           mean     4.167715e+05    320999.997406    4.109359e+05
           std      4.000224e+06   1204153.141004    4.005233e+06
           min      8.716000e+04     87598.000000    9.115800e+04
           25%      1.104602e+05    109813.000000    1.092160e+05
           50%      1.421680e+05    139038.000000    1.406030e+05
           75%      2.459625e+05    229918.000000    2.272990e+05
           max      1.097561e+08  25290018.000000    1.097695e+08

But I need to append horizontally and not vertically (like landscape mode). I  want to avoid first write temporary file and then paste all files. I assume this is a common use-case and should have a better solution. These outputs are pandas dataframe printed by python.

Body:
You can use array elements or associative array members as storage, instead of files. They're stored in the memory, so of course, usable only for reasonable small content.

E.g. you can:

declare -a res
for file in md*/*; do
    res+=( "$(./myscript.sh "$file")" ) #each result as an element of array
done
#here you have the results stored as an array elements

#the $final variable will store the whole output
final=("${res[@]:1}") #store the 1st elemnt to "final" and remove it from the array

# for all remaining elements
# use the "pr" utility for the append up the $width width
width=$(tput cols) #maybe you will need define much larger width...
for ele in "${res[@]}"; do
    final=$(pr -w$width -t -m <(echo "$final") <(echo "$ele"))
done
echo "$final"

finally, i do not understand the

I want to avoid first write temporary file and then paste all files.

It is much easier and simpler use temp-files as this in-memory array solution. Just read @Leon comments!


问:
Best practice boolean logic multiple not equal to
When writing a boolean statement with multiple 'not equal to' clauses I believe there are two potential syntaxes for achieving this, both of which are functionally equivalent. c# example:

1.

```<code>x != 1 && y != 1
</code>```

2.

```<code>!(x == 1 || y == 1)
</code>```

For the sake of being consistent and deciding on a best practice, are there any clear advantages/disadvantages to either?

Thanks

答: They are the same indeed, the only difference is the readability. Usually I see the first option more often in code and I prefer this one (for me it's more clear that you don't want them to be equal to something). However, that's a personal preference. If you want you can go with the second one, but just make sure you are consistent throughout your project to avoid confusion. </p>

Body:
When writing a boolean statement with multiple 'not equal to' clauses I believe there are two potential syntaxes for achieving this, both of which are functionally equivalent. c# example:

1.

x != 1 && y != 1

2.

!(x == 1 || y == 1)

For the sake of being consistent and deciding on a best practice, are there any clear advantages/disadvantages to either?

Thanks


问:
Xamarin saving a video path in sqlite. Having permission issue to save
I am recording for 7 seconds and after that I want to save the video but I have an error. Trying to save the video. error is =

Java.IO.IOException: invalid preview surface
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ()

The code is

```<code>  private  void SetupRecording(object sender, EventArgs e)   // start recording
    {

        try
        {
            video.StopPlayback();

            recorder = new MediaRecorder();
            recorder.SetVideoSource(VideoSource.Camera);
            recorder.SetOutputFormat(OutputFormat.Default);
            recorder.SetVideoFrameRate(30);
            recorder.SetVideoEncoder(VideoEncoder.Default);
            recorder.SetOutputFile(path);
            recorder.SetPreviewDisplay(video.Holder.Surface);
            recorder.SetMaxDuration(7000);
            // recording for 7 seconds

            recorder.Prepare();

            try
            {

                Video vid = new Video()
                {
                    ProjectID = passedID,
                    VideoPath = path,

                };
                updatavideodb.insertIntoTableVideo(vid);

            }
            catch (Java.Lang.Exception ex)
            {

                recorder.Stop();
                recorder.Release();
                return;
            }
            recorder.Start();
            Thread.Sleep(8000);
            recorder.Stop();
            recorder.Release();
            textCountDown.Text = " Finshed Recording ";

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

The path i am trying to save to

path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test" + time.ToString().Replace("/", "-") + ".mp4";

The manifest is -

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ShowWorksDemo6.ShowWorksDemo6" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.INTERNET" />
<application android:label="ShowWorksDemo6"></application>
</manifest>
</code>```

the code stop running at the line recorder.Prepare();

I like any help in what I am wrong would be great help.

答: I found the issue I was having, I was using dispose before I called the the video reorder. Which ended the activity before it should display the recorder. Thanks for your help any way </p>

Body:
I am recording for 7 seconds and after that I want to save the video but I have an error. Trying to save the video. error is =

Java.IO.IOException: invalid preview surface
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ()

The code is

  private  void SetupRecording(object sender, EventArgs e)   // start recording
    {

        try
        {
            video.StopPlayback();

            recorder = new MediaRecorder();
            recorder.SetVideoSource(VideoSource.Camera);
            recorder.SetOutputFormat(OutputFormat.Default);
            recorder.SetVideoFrameRate(30);
            recorder.SetVideoEncoder(VideoEncoder.Default);
            recorder.SetOutputFile(path);
            recorder.SetPreviewDisplay(video.Holder.Surface);
            recorder.SetMaxDuration(7000);
            // recording for 7 seconds

            recorder.Prepare();

            try
            {

                Video vid = new Video()
                {
                    ProjectID = passedID,
                    VideoPath = path,

                };
                updatavideodb.insertIntoTableVideo(vid);

            }
            catch (Java.Lang.Exception ex)
            {

                recorder.Stop();
                recorder.Release();
                return;
            }
            recorder.Start();
            Thread.Sleep(8000);
            recorder.Stop();
            recorder.Release();
            textCountDown.Text = " Finshed Recording ";

            CloseCamera();
        }

The path i am trying to save to

path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test" + time.ToString().Replace("/", "-") + ".mp4";

The manifest is -

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ShowWorksDemo6.ShowWorksDemo6" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.INTERNET" />
<application android:label="ShowWorksDemo6"></application>
</manifest>

the code stop running at the line recorder.Prepare();

I like any help in what I am wrong would be great help.


问:
Access wordpress website from phone hosted locally through Xammp
I have a test WordPress website hosted locally by my PC. This is fine but i am now wanting to test the website on a phone and tablet (iPhone and iPad).

I have looked online for all the options and i can't get any to work (changing the httpd files and i have tried everything else) I can type my IP address of my PC with the port number added at the end and this takes me to the Xampp control panel page but i cant access my website by typing 'IPaddress/websitename'.

Can someone please give me a full step by step of what i need to do to be able to see my locally xampp WordPress website from my iPhone and iPad.

答:
Your phone is probably not on the same network as your PC, and you might not be sharing your XAMPP website over the network. It would be possible to make your website available to your phone, but it is likely to be quite a lot of work, and might be insecure.

A better idea would be to shrink your desktop browser down to phone / tablet size, and check the layout that way. You can even throttle the internet speed, to simulate slower connections, and choose specific device models. On Chrome, this is called device mode. You will need to turn on Chrome developer tools first, which is done by clicking View -> Developer -> Developer Tools, in the Chrome toolbar. You will see a little icon there (see the link for a screenshot).

If you are going to make the site live, you should still probably check it with a real phone / tablet, but for the first steps, using 'device mode' is a good place to start.


问:
remove empty Arrays from multidimensional Array generated with simplexml
I have an xml file with the following structure:

```<code><categories>
  <category>
    <id>3</id>
    <title><![CDATA[Testname]]></title>
    <text><![CDATA[]]></text>
    <keywords><![CDATA[]]></keywords>
    <description><![CDATA[]]></description>
  </category>
</categories>
</code>```

Now I'm loading this file and creating an array of it:

```<code>$xmlData = simplexml_load_file( 'categories.xml', null, LIBXML_NOCDATA);
$array = json_decode(json_encode($xmlData), true);
</code>```

That generates me the following Result (print_r Output):

```<code>Array
(
  [@attributes] => Array
    (
      [version] => 1.0
    )

  [categories] => Array
    (
      [category] => Array
        (
          [0] => Array
            (
              [id] => 3
              [title] => Testname
              [text] => Array
                (
                )

              [keywords] => Array
                (
                )

              [description] => Array
                (
                )
            )
        )
    )
)
</code>```

Here is my question, how could I remove those empty arrays? I tried it with array Filter, but this didn't work. (I need the keys, but they should be empty)

I know there would be a way, in my next step where I'm renaming the array keys as needed, i could check for empty arrays in the foreach loop, but I think there is an easier way, because every field (except id) could be empty in the xml file.

```<code>foreach($array['categories']['category'] as $key => $category){
  $results[$key]['id'] = $category['id'];
  $results[$key]['headline'] = $category['title'];
  $results[$key]['content'] = $category['text'];
  $results[$key]['metaKeywords'] = $category['keywords'];
  $results[$key]['metaDescription'] = $category['description'];
}
</code>```

Does someone has an idea, what i could do after the json_decode? Or is there an easier way for all I'm trying to accomplish here?

Thanks!

答:
Hope this will work. PHP code demo</p>

```<code><?php
$result=Array
(

  "categories" => Array
    (
      "category" => Array
        (
          0 => Array
            (
              "id" => 3,
              "title" => "Testname",
              "text" => Array
                (
                ),

              "keywords" => Array
                (
                ),

              "description" => Array
                (
                )
            )
        )
    )
);
$results=array();
foreach($result['categories']['category'] as $key => $category){
  $results[$key]['id'] = $category['id'];
  $results[$key]['headline'] = $category['title'];
  $results[$key]['content'] = is_array($category['text']) && count($category['text'])>0 ? $category['text'] : false;
  $results[$key]['metaKeywords'] = is_array($category['keywords']) && count($category['keywords'])>0 ? $category['keywords'] : false;
  $results[$key]['metaDescription'] = is_array($category['description']) && count($category['description'])>0 ? $category['description'] : false;
  $results[$key]=array_filter($results[$key]);
}
print_r($results);
</code>```

Body:
I have an xml file with the following structure:

<categories>
  <category>
    <id>3</id>
    <title><![CDATA[Testname]]></title>
    <text><![CDATA[]]></text>
    <keywords><![CDATA[]]></keywords>
    <description><![CDATA[]]></description>
  </category>
</categories>

Now I'm loading this file and creating an array of it:

$xmlData = simplexml_load_file( 'categories.xml', null, LIBXML_NOCDATA);
$array = json_decode(json_encode($xmlData), true);

That generates me the following Result (print_r Output):

Array
(
  [@attributes] => Array
    (
      [version] => 1.0
    )

  [categories] => Array
    (
      [category] => Array
        (
          [0] => Array
            (
              [id] => 3
              [title] => Testname
              [text] => Array
                (
                )

              [keywords] => Array
                (
                )

              [description] => Array
                (
                )
            )
        )
    )
)

Here is my question, how could I remove those empty arrays? I tried it with array Filter, but this didn't work. (I need the keys, but they should be empty)

I know there would be a way, in my next step where I'm renaming the array keys as needed, i could check for empty arrays in the foreach loop, but I think there is an easier way, because every field (except id) could be empty in the xml file.

foreach($array['categories']['category'] as $key => $category){
  $results[$key]['id'] = $category['id'];
  $results[$key]['headline'] = $category['title'];
  $results[$key]['content'] = $category['text'];
  $results[$key]['metaKeywords'] = $category['keywords'];
  $results[$key]['metaDescription'] = $category['description'];
}

Does someone has an idea, what i could do after the json_decode? Or is there an easier way for all I'm trying to accomplish here?

Thanks!

Body:
Hope this will work. PHP code demo

<?php
$result=Array
(

  "categories" => Array
    (
      "category" => Array
        (
          0 => Array
            (
              "id" => 3,
              "title" => "Testname",
              "text" => Array
                (
                ),

              "keywords" => Array
                (
                ),

              "description" => Array
                (
                )
            )
        )
    )
);
$results=array();
foreach($result['categories']['category'] as $key => $category){
  $results[$key]['id'] = $category['id'];
  $results[$key]['headline'] = $category['title'];
  $results[$key]['content'] = is_array($category['text']) && count($category['text'])>0 ? $category['text'] : false;
  $results[$key]['metaKeywords'] = is_array($category['keywords']) && count($category['keywords'])>0 ? $category['keywords'] : false;
  $results[$key]['metaDescription'] = is_array($category['description']) && count($category['description'])>0 ? $category['description'] : false;
  $results[$key]=array_filter($results[$key]);
}
print_r($results);


问:
Is it possible for me to get the current trending topics from Youtube?
Currently, I'm working on getting the latest trend on Youtube. Is there a way to get the JSON Object so that I can use it in my java code.</p>

答:
From V3 you can use the following  (from API Reference)

HTTP request

GET https://www.googleapis.com/youtube/v3/videos

API Reference for Videos List

For what you intend the chart parameter of the query string is what you need, and it accepts mostPopular

The response is JSON as the following taken from their API example.

{
    "kind": "youtube#videoListResponse",
    "etag": etag,
    "nextPageToken": string,
    "prevPageToken": string,
    "pageInfo": {
      "totalResults": integer,
      "resultsPerPage": integer
    },
    "items": [
      video Resource
    ]
  }


问:
Sequelize association include returns null
I am having an issue when I'm trying to associate a table into my query with sequelize-cli.

My query works but it doesn't populate Adresse table. Only Patient is  populated. Adresse array is ignored. (return null)

I made a one-to-one relationship between the tables and am not sure if that's the cause of the error or if it is somewhere else where I am associating the two tables.

here is my models :

server/models/patient.js

```<code>module.exports = (sequelize, Sequelize) => {
    const Patient = sequelize.define('Patient', {
        ///
    }, {
        classMethods: {
            associate: (models) => {
                Patient.belongsTo(models.Adresse, {
                    foreignKey: 'adresseId',
                });
            }
        }
    });
    return Patient;
};
</code>```

server/models/adresse.js

```<code>module.exports = function(sequelize, Sequelize) {
    const Adresse = sequelize.define('Adresse', {
        adresse: {
            type: Sequelize.STRING,
            allowNull: false,
        },
        complementAdr: {
            type: Sequelize.STRING
        },
        codePostal: {
            type: Sequelize.INTEGER,
            allowNull: false
        },
    }, {
        classMethods: {
            associate: (models) => {
                Adresse.hasMany(models.Patient, {
                    foreignKey: 'adresseId',
                    as: 'Patients',
                });
            }
        }
    });
    return Adresse;
};
</code>```

and here is where I specified the association on my migration files  :

server/migrations/20170326145609-create-patient.js

```<code>adresseId: {
    type: Sequelize.INTEGER,
    references: {
        model: 'Adresses',
        key: 'id_adresse',
        as: 'adresseId',
    },
},
</code>```

server/migrations/20170326145502-create-adresse.js

```<code>module.exports = {
    up: (queryInterface, Sequelize) => {
        return queryInterface.createTable('Adresses', {
            id_adresse: {
                allowNull: false,
                autoIncrement: true,
                primaryKey: true,
                type: Sequelize.INTEGER
            },
            adresse: {
                type: Sequelize.STRING,
                allowNull: false,
            },
            complementAdr: {
                type: Sequelize.STRING
            },
            codePostal: {
                type: Sequelize.INTEGER,
                allowNull: false
            },
            createdAt: {
                allowNull: false,
                type: Sequelize.DATE
            },
            updatedAt: {
                allowNull: false,
                type: Sequelize.DATE
            }
        });
    },
    down: function(queryInterface, Sequelize) {
        return queryInterface.dropTable('Adresses');
    }
};
</code>```

and finally here is my query on my controller file :

server/controllers/patients.js

```<code>const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const Patient = require('../models').Patient;
const Adresse = require('../models').Adresse;

module.exports = {
    create(req, res) {
        return Patient
            .create({
                ///
                adressesId: {
                    adresse: req.body.adresse,
                    codePostal: req.body.codePostal,
                }
            }, {
                include: [{
                    model : Adresse
                }]
            })
            .then(patient => res.status(201).send(patient))
            .catch(error => res.status(400).send(error));
    }
};
</code>```

答:
Try using Adresse instead adresseId when eager creating the Adresse model instance related to given Patient

return Patient.create({
    // patient attributes,
    Adresse: {
        adresse: req.body.adresse,
        codePostal: req.body.codePostal
    },
    include: [ Adresse ]
}).then(patient => {
    // look at the query generated by this function
    // it should create both patient and adresse
});
```

Body:
I am having an issue when I'm trying to associate a table into my query with sequelize-cli.

My query works but it doesn't populate Adresse table. Only Patient is  populated. Adresse array is ignored. (return null)

I made a one-to-one relationship between the tables and am not sure if that's the cause of the error or if it is somewhere else where I am associating the two tables.

here is my models :

server/models/patient.js

module.exports = (sequelize, Sequelize) => {
    const Patient = sequelize.define('Patient', {
        ///
    }, {
        classMethods: {
            associate: (models) => {
                Patient.belongsTo(models.Adresse, {
                    foreignKey: 'adresseId',
                });
            }
        }
    });
    return Patient;
};

server/models/adresse.js

module.exports = function(sequelize, Sequelize) {
    const Adresse = sequelize.define('Adresse', {
        adresse: {
            type: Sequelize.STRING,
            allowNull: false,
        },
        complementAdr: {
            type: Sequelize.STRING
        },
        codePostal: {
            type: Sequelize.INTEGER,
            allowNull: false
        },
    }, {
        classMethods: {
            associate: (models) => {
                Adresse.hasMany(models.Patient, {
                    foreignKey: 'adresseId',
                    as: 'Patients',
                });
            }
        }
    });
    return Adresse;
};

and here is where I specified the association on my migration files  :

server/migrations/20170326145609-create-patient.js

adresseId: {
    type: Sequelize.INTEGER,
    references: {
        model: 'Adresses',
        key: 'id_adresse',
        as: 'adresseId',
    },
},

server/migrations/20170326145502-create-adresse.js

module.exports = {
    up: (queryInterface, Sequelize) => {
        return queryInterface.createTable('Adresses', {
            id_adresse: {
                allowNull: false,
                autoIncrement: true,
                primaryKey: true,
                type: Sequelize.INTEGER
            },
            adresse: {
                type: Sequelize.STRING,
                allowNull: false,
            },
            complementAdr: {
                type: Sequelize.STRING
            },
            codePostal: {
                type: Sequelize.INTEGER,
                allowNull: false
            },
            createdAt: {
                allowNull: false,
                type: Sequelize.DATE
            },
            updatedAt: {
                allowNull: false,
                type: Sequelize.DATE
            }
        });
    },
    down: function(queryInterface, Sequelize) {
        return queryInterface.dropTable('Adresses');
    }
};

and finally here is my query on my controller file :

server/controllers/patients.js

const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const Patient = require('../models').Patient;
const Adresse = require('../models').Adresse;

module.exports = {
    create(req, res) {
        return Patient
            .create({
                ///
                adressesId: {
                    adresse: req.body.adresse,
                    codePostal: req.body.codePostal,
                }
            }, {
                include: [{
                    model : Adresse
                }]
            })
            .then(patient => res.status(201).send(patient))
            .catch(error => res.status(400).send(error));
    }
};


问:
Can I create an index FROM another index?
I am doing various regepx_filters in an index to modify the stored index text, this from data that is originally in tagged html format (multiple zones). After I do so is is possible to now make a second index based on the first modified index that uses only one of the zones in the original index?

```<code>index_zones = Title, Author, Description
</code>```

Can I, after indexing this with a custom configuration, then duplicate this index in some way that says

Create IndexB based on IndexA using ZONE:(Title) only

Say for instance I did the following regexp:

```<code>regexp_filter=(<Title>.*?ipad.*?)(<\/Title>)<Description>.*?Used.*?<\/Description>=>\1 Used\2 in order to index used into the Title Zone.
</code>```

Now I want to reindex or make a new index with just the newly indexed

```<code><Title>Bla bla ipad bla bla Used</Title>
</code>```

is this possible?  If not can I then update my Mysql table with the newly indexed text?

答:
I don't think it's possible to create an index based on an existing sphinx index. I also don't think its possible to retrieve the regexp_filtered result - im pretty sure its only available to query against.

Why dont you do your regex's before sphinx indexing? For example, create a new db column ipad_used_regex and populate this with whatever scripting language you choose. Or using mariaDb with the PCRE Regex Enhancements you could build the regex match into the SQL, something like this:

```<code>SELECT Title, REGEXP_REPLACE(Title, "(<Title>.*?ipad.*?)(<\/Title>)<Description>.*?Used.*?<\/Description>", '\\1 Used\\2') as ipad_used_regex
FROM `your_table`
</code>```

You could then use this SQL in your sphinx index source?

Body:
I am doing various regepx_filters in an index to modify the stored index text, this from data that is originally in tagged html format (multiple zones). After I do so is is possible to now make a second index based on the first modified index that uses only one of the zones in the original index?

index_zones = Title, Author, Description

Can I, after indexing this with a custom configuration, then duplicate this index in some way that says

Create IndexB based on IndexA using ZONE:(Title) only

Say for instance I did the following regexp:

regexp_filter=(<Title>.*?ipad.*?)(<\/Title>)<Description>.*?Used.*?<\/Description>=>\1 Used\2 in order to index used into the Title Zone.

Now I want to reindex or make a new index with just the newly indexed

<Title>Bla bla ipad bla bla Used</Title>

is this possible?  If not can I then update my Mysql table with the newly indexed text?

Body:
I don't think it's possible to create an index based on an existing sphinx index. I also don't think its possible to retrieve the regexp_filtered result - im pretty sure its only available to query against.

Why dont you do your regex's before sphinx indexing? For example, create a new db column ipad_used_regex and populate this with whatever scripting language you choose. Or using mariaDb with the PCRE Regex Enhancements you could build the regex match into the SQL, something like this:

SELECT Title, REGEXP_REPLACE(Title, "(<Title>.*?ipad.*?)(<\/Title>)<Description>.*?Used.*?<\/Description>", '\\1 Used\\2') as ipad_used_regex
FROM `your_table`

You could then use this SQL in your sphinx index source?


问:
Change detection not working when creating a component via ComponentFactoryResolver
I have a component, creating another component with ComponentFactoryResolver. It seems to work fine, I can access data through the @Input. Problem is ngOnChanges never gets called when the component boots up, or when the data changes. However, it does trigger if I create the component the normal way, with it's selector in HTML. That isn't dynamic though, so I am left with ComponentFactoryResolver. Is this normal behavior?

My parent component has it's input:

@ViewChild( MyDirective ) myHost: MyDirective;

Then it creates child components whose inputs are like this:

```<code>@Input('key') key: String;
@Input('index') index: number;
</code>```

and I'm creating the component like this:

```<code>let item = new Item(ItemDropdownComponent, this.key, 0);
let componentFactory = this._componentFactoryResolver.resolveComponentFactory(item.component);
let viewContainerRef = this.myHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
(<ItemInterfaceComponent>componentRef.instance).key = item.key;
(<ItemInterfaceComponent>componentRef.instance).index = item.index;
</code>```

答:
That's expected behavior.
You can invoke change detection explicitely though</p>

```<code>componentRef.changeDetectorRef.detectChanges();
</code>```

Body:
I have a component, creating another component with ComponentFactoryResolver. It seems to work fine, I can access data through the @Input. Problem is ngOnChanges never gets called when the component boots up, or when the data changes. However, it does trigger if I create the component the normal way, with it's selector in HTML. That isn't dynamic though, so I am left with ComponentFactoryResolver. Is this normal behavior?

My parent component has it's input:

@ViewChild( MyDirective ) myHost: MyDirective;

Then it creates child components whose inputs are like this:

@Input('key') key: String;
@Input('index') index: number;

and I'm creating the component like this:

let item = new Item(ItemDropdownComponent, this.key, 0);
let componentFactory = this._componentFactoryResolver.resolveComponentFactory(item.component);
let viewContainerRef = this.myHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
(<ItemInterfaceComponent>componentRef.instance).key = item.key;
(<ItemInterfaceComponent>componentRef.instance).index = item.index;

Body:
That's expected behavior.
You can invoke change detection explicitely though

componentRef.changeDetectorRef.detectChanges();


问:
Laravel - Get specific rows first from db
So I want to "fix" the first three results in my array, that I get from my be so here is my example:

```<code>$ids = explode(',', '2,3,1');

$result = Items::whereIn('id', $ids)
                    ->where('active', '1')
                    ->get();
</code>```

So I want this to return an array where the id 2 is the first, then 2, then 1. The order of the id's will be determent different each time, so I can't do something like order by id etc.

答:
Use Raw for FIELD</p>

```<code>$result = Items::whereIn('id', $ids)
                    ->where('active', '1')
                    ->orderByRaw('FIELD(id,$ids)')
                    ->get();
</code>```

Body:
So I want to "fix" the first three results in my array, that I get from my be so here is my example:

$ids = explode(',', '2,3,1');

$result = Items::whereIn('id', $ids)
                    ->where('active', '1')
                    ->get();

So I want this to return an array where the id 2 is the first, then 2, then 1. The order of the id's will be determent different each time, so I can't do something like order by id etc.

Body:
Use Raw for FIELD

$result = Items::whereIn('id', $ids)
                    ->where('active', '1')
                    ->orderByRaw('FIELD(id,$ids)')
                    ->get();


问:
C# generics: How to specify type constraint and return instance of generic type
In java I can make a method with the following signature:

```<code>public <E extends Form> E makeForm(Class<E> formType) {
    //return new instance of formType
}
</code>```

You pass a class to the method that is constrained, and return an instance of that generic type. This way you can do things like:

```<code>makeForm(SomeForm.class).specificSomeFormMethod();
</code>```

How can I do this in C#? From what I've found so far it's not possible?
I can make the generic type for the form instance OR for the type parameter, but not for both, and I also don't know how to constrain a Type parameter to be only of a specific class.

I'm not quite sure how to label this, so that might be my issue as well. Perhaps I'm overthinking it? I need another person's view!

答:
I think you mean you want generic type constraints:

```<code>public E MakeForm<E>() where E : Form { }
</code>```

The where indicates the start of the type constraints. Here it says that E should be or derive from Form.

You call it like this:

```<code>MyFormType form = MakeForm<MyFormType>();
</code>```

When you just have the type, and nothing more, you can use this:

```<code>public Form MakeForm(Type formType)
{
    return Activator.CreateInstance(formType) as Form;
}

Form form = MakeForm(typeof(MyFormType));
</code>```

Body:
In java I can make a method with the following signature:

public <E extends Form> E makeForm(Class<E> formType) {
    //return new instance of formType
}

You pass a class to the method that is constrained, and return an instance of that generic type. This way you can do things like:

makeForm(SomeForm.class).specificSomeFormMethod();

How can I do this in C#? From what I've found so far it's not possible?
I can make the generic type for the form instance OR for the type parameter, but not for both, and I also don't know how to constrain a Type parameter to be only of a specific class.

I'm not quite sure how to label this, so that might be my issue as well. Perhaps I'm overthinking it? I need another person's view!

Body:
I think you mean you want generic type constraints:

public E MakeForm<E>() where E : Form { }

The where indicates the start of the type constraints. Here it says that E should be or derive from Form.

You call it like this:

MyFormType form = MakeForm<MyFormType>();

When you just have the type, and nothing more, you can use this:

public Form MakeForm(Type formType)
{
    return Activator.CreateInstance(formType) as Form;
}

Form form = MakeForm(typeof(MyFormType));


问:
Division to percentage in Ruby on Rails
If

@prescribed_wod_count = @user.workouts.rx_workouts.count returns 4

and

@user_workout_count = @user.workouts.count returns 26

how come

<%= number_to_percentage(@prescribed_wod_count / @user_workout_count) %> returns 0.000% and not 15% ?

答:
It does integer division, before you call number_to_percentage.

You want

```<code><%= number_to_percentage(@prescribed_wod_count.to_f / @user_workout_count) %>
</code>```

to force it to do floating-point

ContentLicense: CC BY-SA 2.5

Title: Division to percentage in Ruby on Rails

Body:
It does integer division, before you call number_to_percentage.

You want

<%= number_to_percentage(@prescribed_wod_count.to_f / @user_workout_count) %>

to force it to do floating-point


问:
for_in loop for nested object javascript don't return expected values
I am trying to walk through a JS object, with the for_in loop.
That seems to be returning the found value (contentCard1) as plain text.
I can't get it to print val.text

```<code>var contentCards = {
    contentCard1: {text: "text in here", date: "date in here"}
}

for(var val in contentCards) {
    console.log(val.text);
}
</code>```

Logging val.text gives me undefined, and logging just val gives me contentCard1.

Thanks for helping.

答:
With for ... in, you are iterating over the keys of contentCards. For the access you need the object and the key with bracket notation.

```<code>contentCards[val].text
//          ^^^^^
</code>```

var contentCards = { contentCard1: { text: "text in here", date: "date in here" } };

for (var val in contentCards) {
    console.log(contentCards[val].text);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I am trying to walk through a JS object, with the for_in loop.
That seems to be returning the found value (contentCard1) as plain text.
I can't get it to print val.text

var contentCards = {
    contentCard1: {text: "text in here", date: "date in here"}
}

for(var val in contentCards) {
    console.log(val.text);
}

Logging val.text gives me undefined, and logging just val gives me contentCard1.

Thanks for helping.

Body:
With for ... in, you are iterating over the keys of contentCards. For the access you need the object and the key with bracket notation.

contentCards[val].text
//          ^^^^^

var contentCards = { contentCard1: { text: "text in here", date: "date in here" } };

for (var val in contentCards) {
    console.log(contentCards[val].text);
}

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


问:
Can you have an optional QueryParam in jersey?
Using java jersey, I have the following @QueryParam's in my method handler:

```<code>@Path("/hello")
handleTestRequest(@QueryParam String name, @QueryParam Integer age)
</code>```

I know if I do:
http://myaddress/hello?name=something

It will go into that method....

I want to make it so that I can call:

http://myaddress/hello?name=something

And it will also go into that same method. Is there any way I can flag an "optional" PathParam? Does it work with @FormParam too? Or am I required to create a separate method with a different method signature?

答: You can always wrap return type in optional, for example: @QueryParam("from") Optional<String> from

Body:
Using java jersey, I have the following @QueryParam's in my method handler:

@Path("/hello")
handleTestRequest(@QueryParam String name, @QueryParam Integer age)

I know if I do:
http://myaddress/hello?name=something

It will go into that method....

I want to make it so that I can call:

http://myaddress/hello?name=something

And it will also go into that same method. Is there any way I can flag an "optional" PathParam? Does it work with @FormParam too? Or am I required to create a separate method with a different method signature?


问:
Plotting a 3d surface of a function
I'm learning Matlab as I am moving from software development into Artificial Intelligence. I have been learning the M language and I'm currently hitting a bit of a roadblock.

I am trying to generate a 3d surface of the Rastrigin function.

```<code>**rastm.m**
function y = rast(x)
n = 2;
s = 0;
for j = 1:n
    s = s+(x(j)^2-10*cos(2*pi*x(j)));
end
y = 10*n+s;
</code>```

Below is the code being executed, test.m

```<code>**test.m**
syms f(x,y)
f(x,y) = s;
fsurf(f,[-5.12 5.12 -5.12 5.12]);
zlim([0 80])
</code>```

When the code is executed, a 3d graph is generated of the correct proportions, but the surface is completely flat. I imagine I am misunderstanding the reference to the calculation of the Z co-ordinate called on line two of test.m

```<code>f(x,y) = s;
</code>```

I'm using rast(x) incorrectly but I can't quite figure out why

Thank you

答:
Unless you have a clear case of using symbolic maths, I suggest you avoid them and do your maths numerically, as ML/AI are numerical methods after all.

You can define the Rastrigrid function in 2D as:

```<code>[x1,x2]=meshgrid(-5.12:0.01:5.12,-5.12:0.01:5.12);
f =20+x1.^2+x2.^2-10*(cos(2*pi*x1)+cos(2*pi*x2));
</code>```

or inside a function

```<code>function y = rast2D(x1,x2)
   f =20+x1.^2+x2.^2-10*(cos(2*pi*x1)+cos(2*pi*x2));
end
</code>```

alternatively, if you have the Global Optimization Toolbox you can use rastriginsfcn. Its behavior seems undocumented but easy to follow:

```<code>[x1,x2]=meshgrid(-5.12:0.01:5.12,-5.12:0.01:5.12);
f=rastriginsfcn([x1(:) x2(:)]);
f=reshape(f,size(x1));
</code>```

I tried to come up with a function that behaves similarly. I'd do:

```<code>function f=myRastrigrid(x)
   d=size(x,2);
   f=10*d+sum(x.^2-10*cos(2*pi*x),2);
end
</code>```

Both of this cases output surf(x1,x2,f,'linestyle','none');axis tight:

For the curious, this is how it looks like in 3D:

Title: Plotting a 3d surface of a function

Body:
I'm learning Matlab as I am moving from software development into Artificial Intelligence. I have been learning the M language and I'm currently hitting a bit of a roadblock.

I am trying to generate a 3d surface of the Rastrigin function.

**rastm.m**
function y = rast(x)
n = 2;
s = 0;
for j = 1:n
    s = s+(x(j)^2-10*cos(2*pi*x(j)));
end
y = 10*n+s;

Below is the code being executed, test.m

**test.m**
syms f(x,y)
f(x,y) = s;
fsurf(f,[-5.12 5.12 -5.12 5.12]);
zlim([0 80])

When the code is executed, a 3d graph is generated of the correct proportions, but the surface is completely flat. I imagine I am misunderstanding the reference to the calculation of the Z co-ordinate called on line two of test.m

f(x,y) = s;

I'm using rast(x) incorrectly but I can't quite figure out why

Thank you

Body:
Unless you have a clear case of using symbolic maths, I suggest you avoid them and do your maths numerically, as ML/AI are numerical methods after all.

You can define the Rastrigrid function in 2D as:

[x1,x2]=meshgrid(-5.12:0.01:5.12,-5.12:0.01:5.12);
f =20+x1.^2+x2.^2-10*(cos(2*pi*x1)+cos(2*pi*x2));

or inside a function

function y = rast2D(x1,x2)
   f =20+x1.^2+x2.^2-10*(cos(2*pi*x1)+cos(2*pi*x2));
end

alternatively, if you have the Global Optimization Toolbox you can use rastriginsfcn. Its behavior seems undocumented but easy to follow:

[x1,x2]=meshgrid(-5.12:0.01:5.12,-5.12:0.01:5.12);
f=rastriginsfcn([x1(:) x2(:)]);
f=reshape(f,size(x1));

I tried to come up with a function that behaves similarly. I'd do:

function f=myRastrigrid(x)
   d=size(x,2);
   f=10*d+sum(x.^2-10*cos(2*pi*x),2);
end

Both of this cases output surf(x1,x2,f,'linestyle','none');axis tight:

For the curious, this is how it looks like in 3D:


问:
UIButton in Swift with two images
I'm trying to make a UIButton that has a UIImage on either side (left and right) of the button's title. Ideally, the images would be pinned to the left and right sides of the button, and the title would be centered, but I can live with the images being right next to the title label I suppose. I have been able to add one image, which appears right before the title, but how would I add a second?</p>

答:
I know this is an old question but since no code was provided and someone asked for it I figured I would share my solution for this.

What I did was create a new class which subclasses a UIButton. I made sure that you can see all the changes you do instantly in your interface builder as well. So you can just drag in a UIButton. Specify the class to your own class and it will allow you to set the images and see it being drawn instantly

Here is what I did to achieve this

```<code>import UIKit

@IBDesignable
class AddProfilePictureView: UIButton {

    @IBInspectable var leftHandImage: UIImage? {
        didSet {
            leftHandImage = leftHandImage?.withRenderingMode(.alwaysOriginal)
            setupImages()
        }
    }
    @IBInspectable var rightHandImage: UIImage? {
        didSet {
            rightHandImage = rightHandImage?.withRenderingMode(.alwaysTemplate)
            setupImages()
        }
    }

    func setupImages() {
        if let leftImage = leftHandImage {
            self.setImage(leftImage, for: .normal)
            self.imageView?.contentMode = .scaleAspectFill
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: self.frame.width - (self.imageView?.frame.width)!)
        }

        if let rightImage = rightHandImage {
            let rightImageView = UIImageView(image: rightImage)
            rightImageView.tintColor = COLOR_BLUE

            let height = self.frame.height * 0.2
            let width = height
            let xPos = self.frame.width - width
            let yPos = (self.frame.height - height) / 2

            rightImageView.frame = CGRect(x: xPos, y: yPos, width: width, height: height)
            self.addSubview(rightImageView)
        }
    }
}
</code>```

Title: UIButton in Swift with two images

Body:
I know this is an old question but since no code was provided and someone asked for it I figured I would share my solution for this.

What I did was create a new class which subclasses a UIButton. I made sure that you can see all the changes you do instantly in your interface builder as well. So you can just drag in a UIButton. Specify the class to your own class and it will allow you to set the images and see it being drawn instantly

Here is what I did to achieve this

import UIKit

@IBDesignable
class AddProfilePictureView: UIButton {

    @IBInspectable var leftHandImage: UIImage? {
        didSet {
            leftHandImage = leftHandImage?.withRenderingMode(.alwaysOriginal)
            setupImages()
        }
    }
    @IBInspectable var rightHandImage: UIImage? {
        didSet {
            rightHandImage = rightHandImage?.withRenderingMode(.alwaysTemplate)
            setupImages()
        }
    }

    func setupImages() {
        if let leftImage = leftHandImage {
            self.setImage(leftImage, for: .normal)
            self.imageView?.contentMode = .scaleAspectFill
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: self.frame.width - (self.imageView?.frame.width)!)
        }

        if let rightImage = rightHandImage {
            let rightImageView = UIImageView(image: rightImage)
            rightImageView.tintColor = COLOR_BLUE

            let height = self.frame.height * 0.2
            let width = height
            let xPos = self.frame.width - width
            let yPos = (self.frame.height - height) / 2

            rightImageView.frame = CGRect(x: xPos, y: yPos, width: width, height: height)
            self.addSubview(rightImageView)
        }
    }
}


问:
String.toUpperCase may strip accents or not
I have to apply toUpperCase on a name that may contain accents ("é", "à", etc.).

Problem:

with JUnit, "é".toUpperCase converts to "E", the accent is removed

in my application (a Spring REST API), "é".toUpperCase converts to "É". The input comes from an Ember frontend, but the encoding is the same (UTF-8)

JUnit tests and Spring application use the same characters set (UTF-8) and the locale is French. Both running on Oracle Java 8, on the same machine (Jenkins CI on Debian, but I can reproduce this behavior on my computer: Windows 7).

I tried to specify the locale toUpperCase(Locale.FRANCE), but it doesn't solve my problem.

Are you aware of something that may explain this difference?

答:
As in the conversation with @JonathanLermitage this is not a Java problem but is related to the embedded database (h2) used in the unit tests that is not correctly configured.

I'm using Java 8, no particular configuration.

```<code>  @Test
  public void test()
  {
    String a = "àòùìèé";
    String b = a.toUpperCase();
    System.out.println(b);

    System.out.println(Locale.getDefault());
    assertEquals(b,"ÀÒÙÌÈÉ");
  }
</code>```

Returns

```<code>ÀÒÙÌÈÉ
en_US
</code>```

Body:
As in the conversation with @JonathanLermitage this is not a Java problem but is related to the embedded database (h2) used in the unit tests that is not correctly configured.

I'm using Java 8, no particular configuration.

  @Test
  public void test()
  {
    String a = "àòùìèé";
    String b = a.toUpperCase();
    System.out.println(b);

    System.out.println(Locale.getDefault());
    assertEquals(b,"ÀÒÙÌÈÉ");
  }

Returns

ÀÒÙÌÈÉ
en_US