问:
Python3 For loop iterating through a list won't break

Breaking out of a for loop

My code will not break out of the loop:

(I truncated some parts that were for cosmetics)

lchars = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '\\', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '`', '~', '[', ']', '{', '}', '|', ';', ':', "'", ',', '.', '/', '<', '>', '?', '`', '¡', '™', '£', '¢', '∞', '§', '¶', '•', 'ª', 'º', '–', '≠', 'œ', '∑','´', '®', '†', '¥', '¨', 'ˆ', 'ø', 'π', '“', '‘', '«', 'å', 'ß', '∆', '˚', '¬', '…', '˜', 'µ', '≤', '≥', '÷', 'æ', 'Ω', '≈', 'ç', '√', '"', ' ']

guessThisPass = str(input("Enter the password you want the python-based brute force hacker to guess (Character limit is 4): "))
if len(guessThisPass) > 4:
    print('I SAID CHARACTER LIMIT IS 4!! I AM TRUNCATING YOUR PASSWORD NOW! ')
    guessThisPass[0:4]
    time.sleep(5)
print("Starting...")
time.sleep(2)
start = time.time()
for d in lchars:
    for c in lchars:
        for b in lchars:
            for a in lchars:
                tryPass = str(str(a) + str(b) + str(c) + str(d)). # I know the strs are probably unnessecary.
                print(tryPass). # Outputing the attempted password
                if tryPass == guessThisPass:
                    break # This never happens

print("Whoo!")
print("That took ", time.time()-start, "seconds.")

```

<p>Using this code, let's say my password was 'a' (which IRL, it is <strong>not</strong>). Then, <em>logically</em>, it <em>should</em> be able to break out of it almost instantly, right? Except <strong>it doesn't</strong>; it just keeps on going, not breaking, even up to the combination '^Bc' or higher. Why does it not break? Do I need to add the if statement in every single one of the loops?</p>

<h2>Tester code</h2>

<p>Also, here is the code I used to test the possible combinations:</p>

<p>(Also truncated redundant cosmetics)</p>

<pre class="lang-py prettyprint-override"><code># All possible combinations
lchars = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '\\', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '`', '~', '[', ']', '{', '}', '|', ';', ':', "'", ',', '.', '/', '<', '>', '?', '`', '¡', '™', '£', '¢', '∞', '§', '¶', '•', 'ª', 'º', '–', '≠', 'œ', '∑','´', '®', '†', '¥', '¨', 'ˆ', 'ø', 'π', '“', '‘', '«', 'å', 'ß', '∆', '˚', '¬', '…', '˜', 'µ', '≤', '≥', '÷', 'æ', 'Ω', '≈', 'ç', '√', '"', ' ']
# print("Also, there are ", len(lchars), "characters in our character database\n\n")
from time import time
start = time()
for d in lchars:
    for c in lchars:
        for b in lchars:
            for a in lchars:
                print(a+b+c+d)
print("Whoo!")
print("That took ", time()-start, "seconds.")
</code>```

I checked the output of the above code. The letter 'a' was in the output. It should work. Why is it not working?

答:
Actually it does break but since you have 4 nested loops, it just breaks the innermost loop. You can do several things to solve this:

Create a flag and check it before continueing

Move your code into a function and return when you find an answer

Use itertools.product to create your trial strings. This way you will need only one loop so breaking will be simple.

Body:
Breaking out of a for loop

My code will not break out of the loop:

(I truncated some parts that were for cosmetics)

lchars = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '\\', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '`', '~', '[', ']', '{', '}', '|', ';', ':', "'", ',', '.', '/', '<', '>', '?', '`', '¡', '™', '£', '¢', '∞', '§', '¶', '•', 'ª', 'º', '–', '≠', 'œ', '∑','´', '®', '†', '¥', '¨', 'ˆ', 'ø', 'π', '“', '‘', '«', 'å', 'ß', '∆', '˚', '¬', '…', '˜', 'µ', '≤', '≥', '÷', 'æ', 'Ω', '≈', 'ç', '√', '"', ' ']

guessThisPass = str(input("Enter the password you want the python-based brute force hacker to guess (Character limit is 4): "))
if len(guessThisPass) > 4:
    print('I SAID CHARACTER LIMIT IS 4!! I AM TRUNCATING YOUR PASSWORD NOW! ')
    guessThisPass[0:4]
    time.sleep(5)
print("Starting...")
time.sleep(2)
start = time.time()
for d in lchars:
    for c in lchars:
        for b in lchars:
            for a in lchars:
                tryPass = str(str(a) + str(b) + str(c) + str(d)). # I know the strs are probably unnessecary.
                print(tryPass). # Outputing the attempted password
                if tryPass == guessThisPass:
                    break # This never happens

print("Whoo!")
print("That took ", time.time()-start, "seconds.")

Using this code, let's say my password was 'a' (which IRL, it is not). Then, logically, it should be able to break out of it almost instantly, right? Except it doesn't; it just keeps on going, not breaking, even up to the combination '^Bc' or higher. Why does it not break? Do I need to add the if statement in every single one of the loops?

Tester code

Also, here is the code I used to test the possible combinations:

(Also truncated redundant cosmetics)

# All possible combinations
lchars = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '\\', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '`', '~', '[', ']', '{', '}', '|', ';', ':', "'", ',', '.', '/', '<', '>', '?', '`', '¡', '™', '£', '¢', '∞', '§', '¶', '•', 'ª', 'º', '–', '≠', 'œ', '∑','´', '®', '†', '¥', '¨', 'ˆ', 'ø', 'π', '“', '‘', '«', 'å', 'ß', '∆', '˚', '¬', '…', '˜', 'µ', '≤', '≥', '÷', 'æ', 'Ω', '≈', 'ç', '√', '"', ' ']
# print("Also, there are ", len(lchars), "characters in our character database\n\n")
from time import time
start = time()
for d in lchars:
    for c in lchars:
        for b in lchars:
            for a in lchars:
                print(a+b+c+d)
print("Whoo!")
print("That took ", time()-start, "seconds.")

I checked the output of the above code. The letter 'a' was in the output. It should work. Why is it not working?


来源: stackexchange

问:
reading/recognizing new line operator \n
Pretty Simple question today.

PROBLEM:
I cannot get my code to read the newline operator from a repr string.

Desired Output:
I have a message and dummy variables. I want to write the message over the Dummy variables such as:

```<code>dummy:
$$$$$$$$
$$$$  $$
$$$$$$$$

Message:
Hello!!

Returns:
Hello!!H
ello  He
llo!!Hel

What I'm currently getting:
Hello! Hello! Hello! Hello!
</code>```

Code:

```<code>def patternedMessage(msg, pattern):
    ##Set variables, create repr and long string
    newBuild = ""
    reprPtrn = repr(pattern)
    strRecycleInt = len(reprPtrn)//len(msg)
    longPattern = (msg *(strRecycleInt+1))
    #print(reprPtrn) ## to see what the computer sees
    ##Rudimenray switch build
    lineCounter = 0
    for i in range(len(reprPtrn)):
        if (reprPtrn[i] == "\n"):
            newBuild = newBuild + "\n"
            #lineCounter += 1 ## testing for entering the for
        if (reprPtrn[i] != " "):
            newBuild = newBuild + longPattern[i]
        if (reprPtrn[i] == " "):
            newBuild = newBuild + " "
        #print(lineCounter) ## Not entering the for statement
    return newBuild
</code>```

I'm so close. I basically built a simple switch and everything works but the operator. I know I'm doing something wrong with trying to get my code to recognize the \n. (I commented out the dummy counter. I was using it to see if I was actually entering the if statement. ignore that.)

I searched for a bit but am jsut beating my head against a wall now. any help is welcome. Thanks everyone!

答:
Here is a somewhat different solution that cycles through the message instead of copying it:</p>

```<code>i = 0
s = ""
for x in dummy:
    if x == '$': # Keep it
        s += message[i % len(message)]
        i += 1
    elif x == ' ': # Skip it
        s += ' '
        i += 1
    else: # A line break
        s += x
print(s)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Pretty Simple question today.

PROBLEM:
I cannot get my code to read the newline operator from a repr string.

Desired Output:
I have a message and dummy variables. I want to write the message over the Dummy variables such as:

dummy:
$$$$$$$$
$$$$  $$
$$$$$$$$

Message:
Hello!!

Returns:
Hello!!H
ello  He
llo!!Hel

What I'm currently getting:
Hello! Hello! Hello! Hello!

Code:

def patternedMessage(msg, pattern):
    ##Set variables, create repr and long string
    newBuild = ""
    reprPtrn = repr(pattern)
    strRecycleInt = len(reprPtrn)//len(msg)
    longPattern = (msg *(strRecycleInt+1))
    #print(reprPtrn) ## to see what the computer sees
    ##Rudimenray switch build
    lineCounter = 0
    for i in range(len(reprPtrn)):
        if (reprPtrn[i] == "\n"):
            newBuild = newBuild + "\n"
            #lineCounter += 1 ## testing for entering the for
        if (reprPtrn[i] != " "):
            newBuild = newBuild + longPattern[i]
        if (reprPtrn[i] == " "):
            newBuild = newBuild + " "
        #print(lineCounter) ## Not entering the for statement
    return newBuild

I'm so close. I basically built a simple switch and everything works but the operator. I know I'm doing something wrong with trying to get my code to recognize the \n. (I commented out the dummy counter. I was using it to see if I was actually entering the if statement. ignore that.)

I searched for a bit but am jsut beating my head against a wall now. any help is welcome. Thanks everyone!

Body:
Here is a somewhat different solution that cycles through the message instead of copying it:

i = 0
s = ""
for x in dummy:
    if x == '$': # Keep it
        s += message[i % len(message)]
        i += 1
    elif x == ' ': # Skip it
        s += ' '
        i += 1
    else: # A line break
        s += x
print(s)


问:
Convert API resource to array
I want to store data on Firestore. I need to send an array to Firestore. I have API resources and I wanted to use it.

My ApiResource:

```<code>public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'phone' => $this->phone,
        'addresses' => AddressResource::collection($this->addresses),
    ];
}
</code>```

Firestore store data:

```<code>public function set(User $user){
    $this->firestore->document($user->id)->set((new UserResource($user)));
}
</code>```

It is an error:

Argument 1 passed to
  Google\Cloud\Firestore\DocumentReference::set() must be of the type
  array, object given,...

答:
Do it:</p>

```<code>public function set(User $user){
    $this->firestore->document($user->id)->set(toArray($user));
}
</code>```

Title: Convert API resource to array

Body:
I want to store data on Firestore. I need to send an array to Firestore. I have API resources and I wanted to use it.

My ApiResource:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'phone' => $this->phone,
        'addresses' => AddressResource::collection($this->addresses),
    ];
}

Firestore store data:

public function set(User $user){
    $this->firestore->document($user->id)->set((new UserResource($user)));
}

It is an error:

Argument 1 passed to
  Google\Cloud\Firestore\DocumentReference::set() must be of the type
  array, object given,...

Body:
Do it:

public function set(User $user){
    $this->firestore->document($user->id)->set(toArray($user));
}


问:
Getting JSON from WEB API to R - Beginner here
Im trying to get JSON from webapi to R

From the following website
http://wbes.srldc.in/Report/GetCurrentDayFullScheduleMaxRev?regionid=4&ScheduleDate=31-05-2020

When i try in browser, getting a proper response.

However when i try in R using any method, the fetched data is of a different html page without any JSON format.

Im just starting with R without any programming background. Please help

答:
I feel your pain, it seems the website you're trying to access checks for user-agents to avoid scraping. I'd set a common user agent in httr (Chrome or Firefox are fine) and perform a single GET request. This should get you through scraping the MaxRevision value:

library(httr)

url <- "http://wbes.srldc.in/Report/GetCurrentDayFullScheduleMaxRev?regionid=4&ScheduleDate=31-05-2020"
ua <- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"

res <- GET(url, user_agent(ua))
content(res)
#> $MaxRevision
#> [1] 216
```

Created on 2020-06-01 by the reprex package (v0.3.0)

Body:
I feel your pain, it seems the website you're trying to access checks for user-agents to avoid scraping. I'd set a common user agent in httr (Chrome or Firefox are fine) and perform a single GET request. This should get you through scraping the MaxRevision value:

library(httr)

url <- "http://wbes.srldc.in/Report/GetCurrentDayFullScheduleMaxRev?regionid=4&ScheduleDate=31-05-2020"
ua <- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"

res <- GET(url, user_agent(ua))
content(res)
#> $MaxRevision
#> [1] 216

Created on 2020-06-01 by the reprex package (v0.3.0)


问:
How can I remove an object from array in python?
How can I remove an object from array in python?

I want to select an msgID and want to delete that full object with username, msg, time_stamp (all of it).

```<code>room_msg =  [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'},
{
  'msgID': 3,
  'username': 'User3',
  'msg': 'msg3',
  'time_stamp': 'May-31 05:29PM'} ]
</code>```

Like if I select 'msgID': 3
after deleting the 'msgID': 3 the array should like this

```<code>room_msg = [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'}
]
</code>```

Is that possible?
I can't find x with that msgID room_msg[x].

答:
To delete a object from an array in python use</p>

```<code>del arr["index"]
</code>```

Body:
How can I remove an object from array in python?

I want to select an msgID and want to delete that full object with username, msg, time_stamp (all of it).

room_msg =  [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'},
{
  'msgID': 3,
  'username': 'User3',
  'msg': 'msg3',
  'time_stamp': 'May-31 05:29PM'} ]

Like if I select 'msgID': 3
after deleting the 'msgID': 3 the array should like this

room_msg = [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'}
]

Is that possible?
I can't find x with that msgID room_msg[x].

Body:
To delete a object from an array in python use

del arr["index"]


问:
Stack Based Column Sum in a data frame using R
My existing data frame looks line given below

```<code>NAV_Date    NAV    Year  Day       Units   Amount  Balance_Units
2013-06-01  282.5  2013  Saturday  3.540   1000    3.540
2013-06-08  279.3  2013  Saturday  3.581   1000    3.581
2013-06-15  276.0  2013  Saturday  3.623   1000    3.623
2013-06-22  261.6  2013  Saturday  3.822   1000    3.822
2013-06-29  273.3  2013  Saturday  3.659   1000    3.659
</code>```

I want my new data frame to have Balance_Units column have entries like given below using R Language
i.e Balance unit column should be the sum of previous value and present value
This is need to be done on the list of dataframe

```<code>NAV_Date    NAV    Year  Day       Units   Amount  Balance_Units
2013-06-01  282.5  2013  Saturday  3.540   1000    3.540
2013-06-08  279.3  2013  Saturday  3.581   1000    7.121
2013-06-15  276.0  2013  Saturday  3.623   1000    10.744
2013-06-22  261.6  2013  Saturday  3.822   1000    14.566
2013-06-29  273.3  2013  Saturday  3.659   1000    18.225
</code>```

I tried this but , this is not working

```<code> for( i in 1:length(W)) {
  W[[i]]$Units  = 1000/W[[i]]$NAV
  W[[i]]$Amount = 1000
  W[[i]]$Balance_Units = 0
  W[[i]]$Balance_Units = W[[i]]$Units + W[[i]]$Balance_Units
   }
</code>```

Body:
My existing data frame looks line given below

NAV_Date    NAV    Year  Day       Units   Amount  Balance_Units
2013-06-01  282.5  2013  Saturday  3.540   1000    3.540
2013-06-08  279.3  2013  Saturday  3.581   1000    3.581
2013-06-15  276.0  2013  Saturday  3.623   1000    3.623
2013-06-22  261.6  2013  Saturday  3.822   1000    3.822
2013-06-29  273.3  2013  Saturday  3.659   1000    3.659

I want my new data frame to have Balance_Units column have entries like given below using R Language
i.e Balance unit column should be the sum of previous value and present value
This is need to be done on the list of dataframe

NAV_Date    NAV    Year  Day       Units   Amount  Balance_Units
2013-06-01  282.5  2013  Saturday  3.540   1000    3.540
2013-06-08  279.3  2013  Saturday  3.581   1000    7.121
2013-06-15  276.0  2013  Saturday  3.623   1000    10.744
2013-06-22  261.6  2013  Saturday  3.822   1000    14.566
2013-06-29  273.3  2013  Saturday  3.659   1000    18.225

I tried this but , this is not working

 for( i in 1:length(W)) {
  W[[i]]$Units  = 1000/W[[i]]$NAV
  W[[i]]$Amount = 1000
  W[[i]]$Balance_Units = 0
  W[[i]]$Balance_Units = W[[i]]$Units + W[[i]]$Balance_Units
   }

Body:
Here's a data.table solution. I added something for sequential sum as well..

library(data.table)
> dat
     NAV_Date   NAV Year      Day Units Amount Balance_Units
1: 2013-06-01 282.5 2013 Saturday 3.540   1000         3.540
2: 2013-06-08 279.3 2013 Saturday 3.581   1000         3.581
3: 2013-06-15 276.0 2013 Saturday 3.623   1000         3.623
4: 2013-06-22 261.6 2013 Saturday 3.822   1000         3.822
5: 2013-06-29 273.3 2013 Saturday 3.659   1000         3.659

# Cumulative sum
> dat[, cumulative_sum := cumsum(Balance_Units)]
> dat
     NAV_Date   NAV Year      Day Units Amount Balance_Units cumulative_sum
1: 2013-06-01 282.5 2013 Saturday 3.540   1000         3.540          3.540
2: 2013-06-08 279.3 2013 Saturday 3.581   1000         3.581          7.121
3: 2013-06-15 276.0 2013 Saturday 3.623   1000         3.623         10.744
4: 2013-06-22 261.6 2013 Saturday 3.822   1000         3.822         14.566
5: 2013-06-29 273.3 2013 Saturday 3.659   1000         3.659         18.225

# Sequential sum
> dat[, sequential_sum := Balance_Units + shift(x = Balance_Units, fill = 0)]
> dat
     NAV_Date   NAV Year      Day Units Amount Balance_Units cumulative_sum sequential_sum
1: 2013-06-01 282.5 2013 Saturday 3.540   1000         3.540          3.540          3.540
2: 2013-06-08 279.3 2013 Saturday 3.581   1000         3.581          7.121          7.121
3: 2013-06-15 276.0 2013 Saturday 3.623   1000         3.623         10.744          7.204
4: 2013-06-22 261.6 2013 Saturday 3.822   1000         3.822         14.566          7.445
5: 2013-06-29 273.3 2013 Saturday 3.659   1000         3.659         18.225          7.481


问:
Is there a C++ preprocessor directive or similar that I can use to convert units
I am doing a bit of motor control, and instead of saying 39553 encoder ticks, it would be easier for my human brain to say 6.5 inches.  I would like to save processor overhead by converting this at compile time.  Is there a way to do this with preprocessor directives or templates maybe?  Thanks.</p>

答:
I would just use #defines:

```<code>#define CM_PER_TICK    0.01
#define toTicks(a)   (a * CM_PER_TICK)

move(toTicks(6.5));
</code>```

This would boil down to

```<code>move(6.5 * 0.01);
</code>```

By using cm per ticks instead of ticks per cm we can get rid of the division, but you won't be able to get rid of any multiplication.

Body:
I would just use #defines:

#define CM_PER_TICK    0.01
#define toTicks(a)   (a * CM_PER_TICK)

move(toTicks(6.5));

This would boil down to

move(6.5 * 0.01);

By using cm per ticks instead of ticks per cm we can get rid of the division, but you won't be able to get rid of any multiplication.


问:
Is it possible to minify JS code inside ejs files?
I'm wondering if it is possible to minify the JS code contained inside template files like EJS files.

Is it useful? I'm thinking about performances. It's still a way to hide comments, explanations.

答:
You can use node-minify for minifying your Javascript, HTML and CSS files.

Also, you shouldn't minify the files on render (on an incoming request). I usually use a my EJS files to pass configurations to the UI and load the UI from S3 or from the public end-point.

You can have index.ejs that includes a script tag

```<code><script type='text/javascript'>
  var clientSideConfig =<%-JSON.stringify(backendConfigurations)%>
</script>
<script src="/public/your_minified_vuejs.js"></script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use node-minify for minifying your Javascript, HTML and CSS files.

Also, you shouldn't minify the files on render (on an incoming request). I usually use a my EJS files to pass configurations to the UI and load the UI from S3 or from the public end-point.

You can have index.ejs that includes a script tag

<script type='text/javascript'>
  var clientSideConfig =<%-JSON.stringify(backendConfigurations)%>
</script>
<script src="/public/your_minified_vuejs.js"></script>


问:
Compile java to object files compatible with C/C++
So I am working(actually still planning) on a GUI project, and I need control over every single pixel on the window. I have done a lot of Java and I know how to do that, the problem is that I want to do all the logic on C++(because I just love how it works) and I don't even know how to  setup a GUI in C++(I already took a small look at Qt, but I haven't done anything great).
So I had this idea of writing all the GUI related things in Java and somehow compile java source files to object files that can be linked with the rest of C++ code. This is just a personal project I am working on so I don't care if I lose the cross-compatibility of Java.

Thanks to anyone who took time to read this.

答:
Look into JNI. Years ago, when doing the game of life in programming class, I chose to have a C function do the pixel work, just like you are thinking of, because it, ahem, back then, made the graphics work run many times faster. Noticeably, back then anyway.

Write the Java Program and Compile

Generate header file from java class

Write the C Program

Generate Shared Library File

Run Java Program

Here's one of probably many resources to show you.


问:
Getting a number of digits
I've been searching for a way in python to get only 4 digits on the right of the comma of a decimal number, but i couldn't find. Took a look on this post,---> Rounding decimals with new Python format function
,but the function written there...

```<code>    >>> n = 4
    >>> p = math.pi
    >>> '{0:.{1}f}'.format(p, n)
    '3.1416'
</code>```

...seems not to work in my case.

I imported the modules "math" and "decimal", but maybe i'm missing some others to import, but i don't know which of them to import.

Thanks everyone, and sorry if this issue has already been posted.

Peixe

答:
What you have is fine (rounding the 5 up to a 6)

If you want truncation instead of rounding you could go:

```<code>from math import pi as p
print p
print int(p*10**4)/10.0**4

p=str(p).split(".")
p[1]=p[1][:4]
print ".".join(p)
</code>```

output:

3.14159265359

3.1415

3.1415

Title: Getting a number of digits

Body:
I've been searching for a way in python to get only 4 digits on the right of the comma of a decimal number, but i couldn't find. Took a look on this post,---> Rounding decimals with new Python format function
,but the function written there...

    >>> n = 4
    >>> p = math.pi
    >>> '{0:.{1}f}'.format(p, n)
    '3.1416'

...seems not to work in my case.

I imported the modules "math" and "decimal", but maybe i'm missing some others to import, but i don't know which of them to import.

Thanks everyone, and sorry if this issue has already been posted.

Peixe

Body:
What you have is fine (rounding the 5 up to a 6)

If you want truncation instead of rounding you could go:

from math import pi as p
print p
print int(p*10**4)/10.0**4

p=str(p).split(".")
p[1]=p[1][:4]
print ".".join(p)

output:

3.14159265359

3.1415

3.1415


问:
Ansible for Windows
I am trying to set up my ansible host to connect to windows.  However ping is failing with the following error:

sudo ansible win -m win_ping
hostname | UNREACHABLE! => {
    "changed": false,
    "msg": "basic: HTTPConnectionPool(host='hostname', port=5986): Read timed out. (read timeout=30)",
    "unreachable": true
}

pywinrm is installed on my linux box and WinRM is installed on the windows box.

Hosts file:

[win]
systemname
[win:vars]
ansible_user=username
ansible_password=passord
ansible_connection=winrm
ansible_winrm_scheme=http
ansible_winrm_server_cert_validation=ignore
ansible_winrm_transport=basic```

Appreciate any advice.
Thanks.

答:
Can you double check the WinRM Listener settings:

```<code>winrm enumerate winrm/config/Listener
</code>```

If the output is what you expect, can you test a command on the local server as shown here:

```<code>winrs -r:http://server:5985/wsman -u:Username -p:Password ipconfig
</code>```

Ansible has a good reference on this topic as well.

Title: Ansible for Windows

Body:
I am trying to set up my ansible host to connect to windows.  However ping is failing with the following error:

sudo ansible win -m win_ping
hostname | UNREACHABLE! => {
    "changed": false,
    "msg": "basic: HTTPConnectionPool(host='hostname', port=5986): Read timed out. (read timeout=30)",
    "unreachable": true
}

pywinrm is installed on my linux box and WinRM is installed on the windows box.

Hosts file:

[win]
systemname
[win:vars]
ansible_user=username
ansible_password=passord
ansible_connection=winrm
ansible_winrm_scheme=http
ansible_winrm_server_cert_validation=ignore
ansible_winrm_transport=basic

Appreciate any advice.
Thanks.

Body:
Can you double check the WinRM Listener settings:

winrm enumerate winrm/config/Listener

If the output is what you expect, can you test a command on the local server as shown here:

winrs -r:http://server:5985/wsman -u:Username -p:Password ipconfig

Ansible has a good reference on this topic as well.


问:
Are res/req keywords or can you name them whatever you want to?
Referring to response and request in express methods. </p>

答: you can name it whatever you want, but req, res and next are the Express defaults. I recommend you to use it with that same syntax but it will note broke your app if not :) </p>


问:
Frontend SVN client, closest thing to Tortoise for the mac
Just wondering what is the best frontend SVN client like Tortoise for the mac.

Andrei

答: I thought it was Versions.</p>

Body: I thought it was Versions.


问:
Laravel's timestamp has weird return format
I have a posts Model & Controller and when I try to get all posts, it returns the created_at and updated_at colums as this:
"created_at": "2020-05-31T22:04:38.000000Z",

As you can see, there is a weird "T" between the date and time + there's ".000000Z" at the end.

I tried using Carbon::setToStringFormat(); but no luck.

This is my PostsController@index

```<code>    {
        Carbon::setToStringFormat(DateTime::ISO8601);
        $posts = Post::with('author:id,name,lastName')->get();
        return response()->json(['posts' => $posts->toArray()],200);
    }
</code>```

And this problem persists on every single model/migration I have made. Including the users table.

```<code>"users": [
    {
      "id": 1,
      "email": "admin@test.com",
      "status": "admin",
      "name": "Administrators",
      "lastName": "Uzvārds",
      "department": "client",
      "phone": "null",
      "created_at": "2020-05-31T22:03:36.000000Z",
      "updated_at": "2020-05-31T22:03:36.000000Z"
    },
    {
      "id": 2,
      "email": "user@test.com",
      "status": "employee",
      "name": "Darbinieks",
      "lastName": "Uzvārds",
      "department": "client",
      "phone": "null",
      "created_at": "2020-05-31T22:03:36.000000Z",
      "updated_at": "2020-05-31T22:03:36.000000Z"
    }
  ]
</code>```

As you can see, in PHPMyAdmin everything's completely fine:

答:
That’s not “weird”. It’s pretty standard ISO8601 format with a microsecond precision and “Z” (ie. UTC) time zone designation. The ISO8601 format allows a “T” between date and time components, as well as several other variations.

The database display happens to use a different variation. This is OK and expected because the database type is a DATETIME (or similar), so the displayed text is only a given representation. Both representations represent the same date and time^.

This is a good format to transfer information (and is common in JSON serialization), less so to display to a user.

^ Assuming the data in the database is stored from a UTC source, which appears to be the case here. If it’s a local time source there are other complications as the “Z” offset in the JSON would be incorrect/misleading without value adjustments.

Body:
I have a posts Model & Controller and when I try to get all posts, it returns the created_at and updated_at colums as this:
"created_at": "2020-05-31T22:04:38.000000Z",

As you can see, there is a weird "T" between the date and time + there's ".000000Z" at the end.

I tried using Carbon::setToStringFormat(); but no luck.

This is my PostsController@index

    {
        Carbon::setToStringFormat(DateTime::ISO8601);
        $posts = Post::with('author:id,name,lastName')->get();
        return response()->json(['posts' => $posts->toArray()],200);
    }

And this problem persists on every single model/migration I have made. Including the users table.

"users": [
    {
      "id": 1,
      "email": "admin@test.com",
      "status": "admin",
      "name": "Administrators",
      "lastName": "Uzvārds",
      "department": "client",
      "phone": "null",
      "created_at": "2020-05-31T22:03:36.000000Z",
      "updated_at": "2020-05-31T22:03:36.000000Z"
    },
    {
      "id": 2,
      "email": "user@test.com",
      "status": "employee",
      "name": "Darbinieks",
      "lastName": "Uzvārds",
      "department": "client",
      "phone": "null",
      "created_at": "2020-05-31T22:03:36.000000Z",
      "updated_at": "2020-05-31T22:03:36.000000Z"
    }
  ]

As you can see, in PHPMyAdmin everything's completely fine:


问:
h264 to FLV conversion, ambiguous FrameType definition: What differentiates a Key Frame vs an Inter Frame?
I'm trying to write out an Annex B formatted h264 bitstream in an FLV container over RTMP in an Android app. After reading this SO answer and several more, I understand my Annex B bitstream first has to be converted to AVCC before being wrapped in an FLV container.

That said, the FLV container spec is a bit unclear in the wrapping of its video tags. It requires a FrameType which can be:

keyframe (For AVC a seekable frame)

interframe (For AVC a non seekable frame)

Disposable interframe (h263 only)

Generated keyframe (serverside only)

Video info / command frame (The message string contains a byte, 0 or 1 meaning either start of client seeking video frame sequence, or end of client seeking frame sequence)

When writing IDR or non-IDR AVC frames, i.e VCL NAL units, it's clear that options 1 and 2 should be used respectively. However, my h264 bitstream also contains non-VCL NAL units, specifically SEI payload type 47 (Display Orientation). It's not clear whether this fits when going from AVC to FLV per the spec. Do I simply consider the SEI a non seekable frame? What is a "frame" from FLV's point of view?

答:
It’s not ambiguous. What flv calls a frame, h264 calls an access unit. Like the link you posted said, an access unit can contain more than one NAL. An SEI by itself is not an access unit, hence it is not a frame, hence it should never be by itself in an flv tag, hence the question does not make sense. </p>

<p>An SEI is sent along as part of the same frame (AU) payload and the flv frame type is that if the VCL nalus in that au. </p>

Body:
It’s not ambiguous. What flv calls a frame, h264 calls an access unit. Like the link you posted said, an access unit can contain more than one NAL. An SEI by itself is not an access unit, hence it is not a frame, hence it should never be by itself in an flv tag, hence the question does not make sense.

An SEI is sent along as part of the same frame (AU) payload and the flv frame type is that if the VCL nalus in that au.


问:
When do values passed to a parameter require quotes?
I have been working with Exchange Online unified groups and Microsoft Teams teams in powershell: New-UnifiedGroup, Set-UnifiedGroup, Get-UnifiedGroup, New-Team, Get-Team etc. I have been creating groups and teams from PowerShell.

I am interested in understanding a bit better when a value for a parameter requires quotes and when it does not.

When I import from CSV, it seems the values are automatically interpreted as strings. When I supply them to a parameter that requires a string, the value does not require quotes even if it has spaces e.g New-UnifiedGroup -DisplayName $item.displayName does not require quotes even when the display name has spaces.

But when I want to create a team from an existing group, and I get the ID of the group, the group id requires quotes: New-Teams -GroupId "$group.ExternalDirectoryObjectId". In this case the parameter -GroupId requires a string value, although the ExternalDirectoryObjectId that it requires is not a string.

Is there a rule that a value does not require quotes if it is a string, and a string value is expected? Does it help to declare a variable as a string before passing it to a parameter that requires a string? For example, if I have a $path variable, I usually have to provide it as -Path "$path". If I declared the path as [String]$path =, would I then not need to use the quotes in -Path $path

答:
That's strange.  Usually you only need quotes to pass a literal string that has a space in it.

```<code>get-childitem -path 'foo 2'
</code>```

I can pass an object property without quotes usually:

```<code>$a = [pscustomobject]@{path = 'foo 2'}
get-childitem -path $a.path
</code>```

This is more rare, but if a string looks like an array element, I've found I have to quote it:

```<code>select-xml -XPath "//*[@a='hi']" -Path file.xml
</code>```

Even using something like an integer works without quotes, because it can be 'coerced' into a string.

Body:
That's strange.  Usually you only need quotes to pass a literal string that has a space in it.

get-childitem -path 'foo 2'

I can pass an object property without quotes usually:

$a = [pscustomobject]@{path = 'foo 2'}
get-childitem -path $a.path

This is more rare, but if a string looks like an array element, I've found I have to quote it:

select-xml -XPath "//*[@a='hi']" -Path file.xml

Even using something like an integer works without quotes, because it can be 'coerced' into a string.


问:
FsReveal Line Highlighting
I am trying to highlight lines in an FsReveal presentation. I want to show all the lines then in the next step highlight line 3. I know this is possible in Reveal.js but I am not sure how to use it from FsReveal. Here is what I tried:

```<code>***
- data-line-number : 1-3|3

### Chicken

```
let x = 10
let y = ["a"; "b"; "c"]
let monkey = 100.0
```

***
</code>```

Instead of showing all the lines and then highlighting the third line on the next right-arrow, it just shows all the lines as normal and moves on.

答:
I don't really have a working answer, but I have two thoughts that could help.

First, the data-line-numbers attribute needs to be set on the  element of your snippet. The way you are setting it, it will be copied to the
 element. This is unfortunate, because the  element is generated from Markdown formatting, so you cannot directly set this. You can still have HTML elements in your markdown document, so you could try if this works:

```<code>```

    Apples
    $1
    7

    Oranges
    $2
    18

```
</code>```

This did not actually work for me, sadly, despite generating what looks like correct HTML. I suspect this is because FsReval uses an older version of reveal.js. There should be a way to update that.

If you got this to work, you could try setting the attribute on the generated  using JavaScript, right after your HTML element:

```<code>```
let x = 10
let y = ["a"; "b"; "c"]
let monkey = 100.0
```

<script>
var els = document.getElementsByTagName("code");
els[els.length-1].setAttribute("data-line-numbers","3,8-10");
</script>
</code>```

Title: FsReveal Line Highlighting

Body:
I am trying to highlight lines in an FsReveal presentation. I want to show all the lines then in the next step highlight line 3. I know this is possible in Reveal.js but I am not sure how to use it from FsReveal. Here is what I tried:

***
- data-line-number : 1-3|3

### Chicken

```
let x = 10
let y = ["a"; "b"; "c"]
let monkey = 100.0
```

***

Instead of showing all the lines and then highlighting the third line on the next right-arrow, it just shows all the lines as normal and moves on.

Body:
I don't really have a working answer, but I have two thoughts that could help.

First, the data-line-numbers attribute needs to be set on the <code> element of your snippet. The way you are setting it, it will be copied to the <section> element. This is unfortunate, because the <code> element is generated from Markdown formatting, so you cannot directly set this. You can still have HTML elements in your markdown document, so you could try if this works:

<pre><code class="nohighlight" data-line-numbers="3,8-10">
<table>
  <tr>
    <td>Apples</td>
    <td>$1</td>
    <td>7</td>
  </tr>
  <tr>
    <td>Oranges</td>
    <td>$2</td>
    <td>18</td>
  </tr>
</table>
</code></pre>

This did not actually work for me, sadly, despite generating what looks like correct HTML. I suspect this is because FsReval uses an older version of reveal.js. There should be a way to update that.

If you got this to work, you could try setting the attribute on the generated <code> using JavaScript, right after your HTML element:

```
let x = 10
let y = ["a"; "b"; "c"]
let monkey = 100.0
```

<script>
var els = document.getElementsByTagName("code");
els[els.length-1].setAttribute("data-line-numbers","3,8-10");
</script>


问:
Adding subview to UITable
I'm trying to add as subview into a section in UITableView, It looks like the code is correct, the it doesn't show anything, just blank section. Here's the code that I use:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    if(indexPath.section==0){
        cell.textLabel.text =@"<>";
    }else if(indexPath.section==1){
        if(indexPath.row==1){
            cell.frame =CGRectMake(0,0, 100, 100);
            [cell.contentView addSubview:page.view];
        }
    } else if(indexPath.section==2){

    }

    // Configure the cell.
    return cell;
}
</code>```

Thanx in advance..

答:
One of the problems is that you are trying to change the height of the cell. If you want to do so, in addition to changing its frame, you must also implement tableView:heightForRowAtIndexPath: and return appropriate values for each row. If page is properly loaded (assuming it's a view controller), you can add the view as a subview. Make sure its frame falls within the bounds of the cell.

Attaching the view

Since dPage is a view controller, you will have to declare page as an ivar of class dPage and then do this in viewDidAppear:,

```<code>page = [[dPage alloc] initWithNibName:"page" bundle:nil];
</code>```

and tableView:cellForRowAtIndexPath: remains unchanged.

Title: Adding subview to UITable

Body:
I'm trying to add as subview into a section in UITableView, It looks like the code is correct, the it doesn't show anything, just blank section. Here's the code that I use:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    if(indexPath.section==0){
        cell.textLabel.text =@"<>";
    }else if(indexPath.section==1){
        if(indexPath.row==1){
            cell.frame =CGRectMake(0,0, 100, 100);
            [cell.contentView addSubview:page.view];
        }
    } else if(indexPath.section==2){

    }

    // Configure the cell.
    return cell;
}

Thanx in advance..

Body:
One of the problems is that you are trying to change the height of the cell. If you want to do so, in addition to changing its frame, you must also implement tableView:heightForRowAtIndexPath: and return appropriate values for each row. If page is properly loaded (assuming it's a view controller), you can add the view as a subview. Make sure its frame falls within the bounds of the cell.

Attaching the view

Since dPage is a view controller, you will have to declare page as an ivar of class dPage and then do this in viewDidAppear:,

page = [[dPage alloc] initWithNibName:"page" bundle:nil];

and tableView:cellForRowAtIndexPath: remains unchanged.


问:
Returning an array from a function to main in c++
How can I return this array to the main function for further use in my program?</p>

```<code>int* enterMarks(int marks) {

int arr[marks];
cout << "Please enter " << marks << "marks (0<=Mark<=100):" << endl;

for (int i = 0; i < marks; i++) {
    cout << i+1 << ">";
    cin >> arr[i];
}
cout << "Thank you..." << endl;

return *arr;
</code>```

答:
```<code>int arr[marks];
</code>```

This is a local variable and so you cannot return it, otherwise the behaviour is undefined, caused crashing etc.

You have two options

1) Allocate the array in the heap and return it

```<code>int *arr = (int *)malloc(sizeof(int)*marks);
...
return arr;
</code>```

You must then free the arr in the calling function.

2) Better, use C++ vector and return it

```<code>std::vector<int> arr;
...
cin >> mark;
arr.push_back(mark);
...
return arr;
</code>```

This way you don't have to remember to free the heap memory.

Body:
How can I return this array to the main function for further use in my program?

int* enterMarks(int marks) {

int arr[marks];
cout << "Please enter " << marks << "marks (0<=Mark<=100):" << endl;

for (int i = 0; i < marks; i++) {
    cout << i+1 << ">";
    cin >> arr[i];
}
cout << "Thank you..." << endl;

return *arr;

Body:
int arr[marks];

This is a local variable and so you cannot return it, otherwise the behaviour is undefined, caused crashing etc.

You have two options

1) Allocate the array in the heap and return it

int *arr = (int *)malloc(sizeof(int)*marks);
...
return arr;

You must then free the arr in the calling function.

2) Better, use C++ vector and return it

std::vector<int> arr;
...
cin >> mark;
arr.push_back(mark);
...
return arr;

This way you don't have to remember to free the heap memory.


问:
Horizontal scroll inside Column Flutter
I want to implement a horizontal scroll with categories:

I put my Categories section in Column (maybe it is not the right way, correct me please if I am wrong) and then I try to make my categories scrollable using ListView/Slivers. I have faced with issue that I need to specify constraints for ListView if I use it inside Column. I tried to wrap it with Expanded widget but it didnt work for me. Then I tried CustomScrollView and Slivers but it seems I am doing something wrong. Can you please suggest me the right structure of the widgtes for this view or correct me.

```<code>          Container(
            margin: EdgeInsets.all(40),
            child: Column(
              children: <Widget>[
                Container(
                  child: Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text(
                            'Category',
                            style: TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(
                            '8 CATEGORIES',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 30,
                      ),
                      CustomScrollView(
                        scrollDirection: Axis.horizontal,
                        slivers: <Widget>[
                          SliverList(
                            delegate: SliverChildListDelegate([
                              CategoryCard(
                                title: 'Featured',
                                previewImageAsset:
                                    'assets/images/bliny-shokolad-klubnika.jpg',
                              ),
                            ]),
                          )
                        ],
                      ),
                      Row(
                        children: <Widget>[
                          CategoryCard(
                            title: 'Featured',
                            previewImageAsset:
                                'assets/images/bliny-shokolad-klubnika.jpg',
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
</code>```

答:
You are getting the error when using the ListView the renderview port was exceeded. To fix this, warp your ListView in a Container widget and give it the height and width property:

Check below:

```<code>Container(
        // change your height based on preference
        height: 80,
        width: double.infinity,
        child: ListView(
          // set the scroll direction to horizontal
          scrollDirection: Axis.horizontal,
          children: <Widget>[
            // add your widgets here
            CategoryCard(
              title: 'Featured',
              previewImageAsset:
              'assets/images/bliny-shokolad-klubnika.jpg',
            ),
            // space them using a sized box
            SizedBox(width: 15,),
            CategoryCard(
              title: 'Featured',
              previewImageAsset:
              'assets/images/bliny-shokolad-klubnika.jpg',
            ),
          ],
        ),
      ),
</code>```

Title: Horizontal scroll inside Column Flutter

Body:
I want to implement a horizontal scroll with categories:

I put my Categories section in Column (maybe it is not the right way, correct me please if I am wrong) and then I try to make my categories scrollable using ListView/Slivers. I have faced with issue that I need to specify constraints for ListView if I use it inside Column. I tried to wrap it with Expanded widget but it didnt work for me. Then I tried CustomScrollView and Slivers but it seems I am doing something wrong. Can you please suggest me the right structure of the widgtes for this view or correct me.

          Container(
            margin: EdgeInsets.all(40),
            child: Column(
              children: <Widget>[
                Container(
                  child: Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text(
                            'Category',
                            style: TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(
                            '8 CATEGORIES',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 30,
                      ),
                      CustomScrollView(
                        scrollDirection: Axis.horizontal,
                        slivers: <Widget>[
                          SliverList(
                            delegate: SliverChildListDelegate([
                              CategoryCard(
                                title: 'Featured',
                                previewImageAsset:
                                    'assets/images/bliny-shokolad-klubnika.jpg',
                              ),
                            ]),
                          )
                        ],
                      ),
                      Row(
                        children: <Widget>[
                          CategoryCard(
                            title: 'Featured',
                            previewImageAsset:
                                'assets/images/bliny-shokolad-klubnika.jpg',
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

Body:
You are getting the error when using the ListView the renderview port was exceeded. To fix this, warp your ListView in a Container widget and give it the height and width property:

Check below:

Container(
        // change your height based on preference
        height: 80,
        width: double.infinity,
        child: ListView(
          // set the scroll direction to horizontal
          scrollDirection: Axis.horizontal,
          children: <Widget>[
            // add your widgets here
            CategoryCard(
              title: 'Featured',
              previewImageAsset:
              'assets/images/bliny-shokolad-klubnika.jpg',
            ),
            // space them using a sized box
            SizedBox(width: 15,),
            CategoryCard(
              title: 'Featured',
              previewImageAsset:
              'assets/images/bliny-shokolad-klubnika.jpg',
            ),
          ],
        ),
      ),


问:
Search through identical links and return first match. - Python BS4
I'm trying collect an input and I want the first link match to be printed. I can't seem to figure it out so I'm here. Any ideas would be great thanks

```<code>import bs4
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import requests

result = requests.get("https://naruto-arena.net/characters-and-skills")
src = result.content
soup = BeautifulSoup(src, 'lxml')

links = soup.find_all("a", { "class" : "subjlink"})

name = input("Enter name: ")

for link in links:
href = (link.attrs['href'])
if name.lower() in href[30:].replace("-", "").lower():
    print(href)
</code>```

Result:

Enter name: naruto

https://naruto-arena.net/char/Uzumaki-Naruto

https://naruto-arena.net/char/Kyuubi-Naruto

https://naruto-arena.net/char/Uzumaki-Naruto-(S)

https://naruto-arena.net/char/Sennin-Naruto-(S)

https://naruto-arena.net/char/Four-Tail-Kyuubi-Naruto-(S)

https://naruto-arena.net/char/Kyuubi-Naruto-(S)

Desired result:

https://naruto-arena.net/char/Uzumaki-Naruto

答:
All your links match, with "naruto" near the end of all of them. If you want just one to be printed, you'll need a break statement. You also seem to have mis-indented your code, as the lines immediately after your for loop are not indented. Here's something that should work:

```<code>name = input("Enter name: ")
for link in links:
    href = (link.attrs['href'])
    if name.lower() in href[30:].replace("-", "").lower():
        print(href)
        break
</code>```

Hope that helps, Happy Coding!

Body:
I'm trying collect an input and I want the first link match to be printed. I can't seem to figure it out so I'm here. Any ideas would be great thanks

import bs4
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import requests

result = requests.get("https://naruto-arena.net/characters-and-skills")
src = result.content
soup = BeautifulSoup(src, 'lxml')

links = soup.find_all("a", { "class" : "subjlink"})

name = input("Enter name: ")

for link in links:
href = (link.attrs['href'])
if name.lower() in href[30:].replace("-", "").lower():
    print(href)

Result:

Enter name: naruto

https://naruto-arena.net/char/Uzumaki-Naruto

https://naruto-arena.net/char/Kyuubi-Naruto

https://naruto-arena.net/char/Uzumaki-Naruto-(S)

https://naruto-arena.net/char/Sennin-Naruto-(S)

https://naruto-arena.net/char/Four-Tail-Kyuubi-Naruto-(S)

https://naruto-arena.net/char/Kyuubi-Naruto-(S)

Desired result:

https://naruto-arena.net/char/Uzumaki-Naruto

Body:
All your links match, with "naruto" near the end of all of them. If you want just one to be printed, you'll need a break statement. You also seem to have mis-indented your code, as the lines immediately after your for loop are not indented. Here's something that should work:

name = input("Enter name: ")
for link in links:
    href = (link.attrs['href'])
    if name.lower() in href[30:].replace("-", "").lower():
        print(href)
        break

Hope that helps, Happy Coding!


问:
How to join strings between parentheses in a list of strings
```<code>poke_list = [... 'Charizard', '(Mega', 'Charizard', 'X)', '78', '130', ...] #1000+ values
</code>```

Is it possible to merge strings that start with '(' and end with ')' and then reinsert it into the same list or a new list?

My desired output poke_list = [... 'Charizard (Mega Charizard X)', '78', '130', ...]

答:
You can iterate over list element checking if each element starts with ( or ends with ). Once you have find the elements between brackets, you can join them by the string .join method, like this:

```<code>poke_list = ['Charizard', '(Mega', 'Charizard', 'X)', '78', '130']

new_poke_list = []
to_concatenate = []
flag = 0

for item in poke_list:
    if item.startswith('(') and not item.endswith(')'):
        to_concatenate.append(item)
        flag = 1
    elif item.endswith(')') and not item.startswith('('):
        to_concatenate.append(item)
        concatenated = ' '.join(to_concatenate)
        new_poke_list.append(concatenated)
        to_concatenate = []
        flag = 0
    elif item.startswith('(') and item.endswith(')'):
        new_poke_list.append(item)
    else:
        if flag == 0:
            new_poke_list.append(item)
        else:
            to_concatenate.append(item)

print(new_poke_list)
</code>```

The flag is set to 1 when the element is within brackets, 0 otherwise, so you can manage all cases.

Body:
poke_list = [... 'Charizard', '(Mega', 'Charizard', 'X)', '78', '130', ...] #1000+ values

Is it possible to merge strings that start with '(' and end with ')' and then reinsert it into the same list or a new list?

My desired output poke_list = [... 'Charizard (Mega Charizard X)', '78', '130', ...]

Body:
You can iterate over list element checking if each element starts with ( or ends with ). Once you have find the elements between brackets, you can join them by the string .join method, like this:

poke_list = ['Charizard', '(Mega', 'Charizard', 'X)', '78', '130']

new_poke_list = []
to_concatenate = []
flag = 0

for item in poke_list:
    if item.startswith('(') and not item.endswith(')'):
        to_concatenate.append(item)
        flag = 1
    elif item.endswith(')') and not item.startswith('('):
        to_concatenate.append(item)
        concatenated = ' '.join(to_concatenate)
        new_poke_list.append(concatenated)
        to_concatenate = []
        flag = 0
    elif item.startswith('(') and item.endswith(')'):
        new_poke_list.append(item)
    else:
        if flag == 0:
            new_poke_list.append(item)
        else:
            to_concatenate.append(item)

print(new_poke_list)

The flag is set to 1 when the element is within brackets, 0 otherwise, so you can manage all cases.


问:
How to use ngx-countdown-timer for time h:m:s only?
How can i use ngx-countdown-timer for time h:m:s only?

        <countdown-timer [end]="i.times"></countdown-timer>

```

答:
the author of ngx-countdown-timer doesn't provide much docs so I went through his source code. The author doesn't seem to have an output format either. Perhaps you can raise an issue with the Github Repo itself.

Other than that, you might need to write code to grab the innerHTML of countdown-timer every second and convert the string to the format that you want.


答:
You should not return a pointer to a variable you define in the local scope of your function i.e. in your case arr.

Return a copy of std::vector instead.

#include <vector>

vector<int> enterMarks(int marks) {
  vector<int> arr;
  cout << "Please enter " << marks << "marks (0<=Mark<=100):" << endl;
  for (int i = 0; i < marks; i++) {
    cout << i+1 << ">";
    int mark;
    cin >> mark;
    arr.push_back(mark);
  }
  cout << "Thank you..." << endl;

  return arr;
}
```

<p>To print these value out in main, you can simply do the following.</p>

<pre class="lang-c prettyprint-override"><code>vector<int> arr = enterMarks(marks);
for (int i = 0; i < arr.size(); i++) {
  cout << "Mark " << i << " = " << arr[i] << endl;
}
</code>```

Title: Returning an array from a function to main in c++

Body:
You should not return a pointer to a variable you define in the local scope of your function i.e. in your case arr.

Return a copy of std::vector instead.

#include <vector>

vector<int> enterMarks(int marks) {
  vector<int> arr;
  cout << "Please enter " << marks << "marks (0<=Mark<=100):" << endl;
  for (int i = 0; i < marks; i++) {
    cout << i+1 << ">";
    int mark;
    cin >> mark;
    arr.push_back(mark);
  }
  cout << "Thank you..." << endl;

  return arr;
}

To print these value out in main, you can simply do the following.

vector<int> arr = enterMarks(marks);
for (int i = 0; i < arr.size(); i++) {
  cout << "Mark " << i << " = " << arr[i] << endl;
}


问:
Video / Voice Chat Web Application with Java
I am trying to add a voice / video chat feature to my web-based chat application developed in JavaEE.
I have not found any tutorials on how to achieve that with both Server and Client written in Java (no javascript allowed).

Is there any tutorials that can help me (using websockets for example) ?

答: You might check out the github project Jitsi. I don't know exactly what tech they are using, but there is a Java version and the code is available for inspection. They may have a forum. I have only taken a cursory look but was reminded of the project by your question.</p>


问:
Max height of 100% for nested children
Is it possible to make a div with a height of 100%, and have the inner item that overflows scroll.

It sounds like a simple problem (and it might be), but I have been thinking about it for days. Some things that don't work in my specific case are:

height: calc(100% - xx px), because the header is of a variable height.

Putting all high children as direct children in the wrapper component (I use a component that has some layers

```<code><div class="wrapper">
  <div class="header">
    A header
  </div>
  <div class="container">
    A container
    <div class="with-many">
      Don't scroll
      <div class="divs">
         Scroll
      </div>
    </div>
  </div>
</div>
</code>```

```<code>.wrapper {
  width: 80vw;
  height: 80vh;
  background-color: lightgrey;

  * {
    width: 100%;
  }

  .header {
    height: 30px;
    background-color: orange;
  }

  .container {
    height: 100%;
    background-color: lightgreen;

    .with-many {
      height: 100%;
      overflow-y: auto;
      background-color: green;

      .divs {
        height: 400vh;
        background-color: blue;
      }
    }
  }
}
</code>```

https://jsfiddle.net/zdb8pmuL/1/

答:
Do you mean like this?:

.wrapper {
  width: 80vw;
  height: 80vh;
  background-color: lightgrey;
}

.wrapper * {
  width: 100%;
}

.header {
  height: 30px;
  background-color: orange;
}

.container {
  height: 100%;
  background-color: lightgreen;
  display: flex;
  flex-direction: column;
}

.with {
  height: 100%;
  background-color: green;
}

.another-wrapper {
  overflow-y: scroll;
  height: 100%;
}

.divs {
  height: 400vh;

  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="header">
    A header
  </div>
  <div class="container">
    A container
    <div class="with">
      With many
      <div class="another-wrapper">
        <div class="divs">
          nested divs
        </div>
      </div>
    </div>
  </div>
</div></code>```

Title: Max height of 100% for nested children

Body:
Is it possible to make a div with a height of 100%, and have the inner item that overflows scroll.

It sounds like a simple problem (and it might be), but I have been thinking about it for days. Some things that don't work in my specific case are:

height: calc(100% - xx px), because the header is of a variable height.

Putting all high children as direct children in the wrapper component (I use a component that has some layers

    A header

    A container

      Don't scroll

         Scroll

.wrapper {
  width: 80vw;
  height: 80vh;
  background-color: lightgrey;

  * {
    width: 100%;
  }

  .header {
    height: 30px;
    background-color: orange;
  }

  .container {
    height: 100%;
    background-color: lightgreen;

    .with-many {
      height: 100%;
      overflow-y: auto;
      background-color: green;

      .divs {
        height: 400vh;
        background-color: blue;
      }
    }
  }
}

https://jsfiddle.net/zdb8pmuL/1/

Body:
Do you mean like this?:

.wrapper {
  width: 80vw;
  height: 80vh;
  background-color: lightgrey;
}

.wrapper * {
  width: 100%;
}

.header {
  height: 30px;
  background-color: orange;
}

.container {
  height: 100%;
  background-color: lightgreen;
  display: flex;
  flex-direction: column;
}

.with {
  height: 100%;
  background-color: green;
}

.another-wrapper {
  overflow-y: scroll;
  height: 100%;
}

.divs {
  height: 400vh;

  background-color: blue;
}

<div class="wrapper">
  <div class="header">
    A header
  </div>
  <div class="container">
    A container
    <div class="with">
      With many
      <div class="another-wrapper">
        <div class="divs">
          nested divs
        </div>
      </div>
    </div>
  </div>
</div>


问:
How to add Rich Text or HTML in Label or Text field in Xamarin Forms?
I want to add Rich Text or Formatted Text in Label or any Text Field in my Xamarin Forms project. I have tried using separate Labels for the text and also using WebView, etc. But none of them worked. Using a Webview worked somehow, but it needed to refresh every time the contents were changed. Using AJAX with WebView would require a Web Server hence it cannot work locally/offline.

I just want to add Rich text on Label in Read only mode, or can be modified from the code behind at runtime.

答:
There are basically 2 ways to do it.

1] You can use Span property of a Label to enter formatted text inside Label Just like:

        <FormattedString>

        </FormattedString>

```
<p>You can also use <code>Binding</code> in <code>Span</code> and every style and other properties of <code>Label</code> inside <code>Span</code>.</p>
<hr/>
<p><strong>2]</strong> The second method is, use <code>TextType</code> property of <code>Label</code> and set it to <code>TextType="Html"</code>. But please note that <code>Label TextType="Html"</code> has limited supported HTML tags according to the underlying platform on which the app runs.</p>
<p>We can define HTML in the C# code behind or directly in XAML.</p>
<p><strong>Inside C# code behind:</strong></p>
<pre class="lang-cs prettyprint-override"><code>Label richTextLabel = new Label
{
    Text = "This is <strong style=\"color:red\">HTML</strong> text.",
    TextType = TextType.Html
};

// OR
richTextLabel.Text = "This is <strong style=\"color:red\">HTML</strong> text."
richTextLabel.TextType = TextType.Html;
// In XAML set Label Name as <Label x:Name="richTextLabel" />
</code>```

In XAML

```<code><Label Text="This is <strong style="color:red">HTML</strong> text."
       TextType="Html"  />

<!--The symbols <, >, " needs to be escaped -->
</code>```

RE: Refer this for more documentation.

Conclusion:
The First method using Span is much reliable as everything will be rendered as coded.
In the second method, most of the HTML markup is not supported by Label in different underlying platforms.
Hence the first method is recommended.

Body:
There are basically 2 ways to do it.

1] You can use Span property of a Label to enter formatted text inside Label Just like:

<Label>
    <Label.FormattedText>
        <FormattedString>
            <Span Text="This is a " FontSize="15" TextColor="Blue"/>
            <Span Text="Rich Text" FontSize="30" TextColor="Red"/>
            <Span Text=" inside a Label in Xamarin Forms" FontSize="15" TextColor="Blue" />
        </FormattedString>
    </Label.FormattedText>
</Label>

You can also use Binding in Span and every style and other properties of Label inside Span.

2] The second method is, use TextType property of Label and set it to TextType="Html". But please note that Label TextType="Html" has limited supported HTML tags according to the underlying platform on which the app runs.

We can define HTML in the C# code behind or directly in XAML.

Inside C# code behind:

Label richTextLabel = new Label
{
    Text = "This is <strong style=\"color:red\">HTML</strong> text.",
    TextType = TextType.Html
};

// OR
richTextLabel.Text = "This is <strong style=\"color:red\">HTML</strong> text."
richTextLabel.TextType = TextType.Html;
// In XAML set Label Name as <Label x:Name="richTextLabel" />

In XAML

<Label Text="This is &lt;strong style=&quot;color:red&quot;&gt;HTML&lt;/strong&gt; text."
       TextType="Html"  />

<!--The symbols <, >, " needs to be escaped -->

RE: Refer this for more documentation.

Conclusion:
The First method using Span is much reliable as everything will be rendered as coded.
In the second method, most of the HTML markup is not supported by Label in different underlying platforms.
Hence the first method is recommended.


问:
When is the Amazon S3 lifecycle rule executed?
I have configured the Amazon S3 buckets (just some special ones) with a Lifecycle Rule to run every 1 day to move the bucket objects to Glacier.

I have checked the buckets many times but I'm not seeing it executed. The docs I referred to are Object Lifecycle Management - Amazon Simple Storage Service.

However, I can't find any places to show the executed time.

Also read through Working with Amazon S3 Buckets - Amazon Simple Storage Service

Any ideas are really appreciated.

答:
According to this
https://aws.amazon.com/premiumsupport/knowledge-center/s3-lifecycle-rule-intelligent-tiering/</p>

```<code>Lifecycle rules run once a day at midnight Universal Coordinated Time (UTC).
</code>```

Body:
According to this
https://aws.amazon.com/premiumsupport/knowledge-center/s3-lifecycle-rule-intelligent-tiering/

Lifecycle rules run once a day at midnight Universal Coordinated Time (UTC).


问:
Is it possible to have multiple potential values for a variable in java
This is a portion of my code, I'd like a variable be assigned a certain rate depending on the different custid number. I'm seeing a duplicate local variable error, is there anyway to get around this?</p>

```<code>if(custid<=100 && custid>=1) {
        double disc = .15;
    }
    else if(custid<=250 && custid>=101) {
        double disc = .18;
    }
    else if(custid<=500 && custid>=251) {
        double disc = .23;
    }
    else if(custid<=1000 && custid>=501) {
        double disc = .28;
    }
    else if(custid>=1001) {
        double disc = .32;
    }

    if(bill>=1000) {
        System.out.println(bill*disc);
    }
</code>```

答:
You only need to declare the variable data type once, as you are declaring it multiple times whilst assigning it, hence the duplicate local variable error. Declare your variable once before the conditions to allow it to be reassignable in your conditions.

Try this:

```<code>double disc = 0;

if(custid<=100 && custid>=1) {
    disc = .15;
}
else if(custid<=250 && custid>=101) {
    disc = .18;
}
else if(custid<=500 && custid>=251) {
    disc = .23;
}
else if(custid<=1000 && custid>=501) {
    disc = .28;
}
else if(custid>=1001) {
    disc = .32;
}
</code>```

Body:
This is a portion of my code, I'd like a variable be assigned a certain rate depending on the different custid number. I'm seeing a duplicate local variable error, is there anyway to get around this?

if(custid<=100 && custid>=1) {
        double disc = .15;
    }
    else if(custid<=250 && custid>=101) {
        double disc = .18;
    }
    else if(custid<=500 && custid>=251) {
        double disc = .23;
    }
    else if(custid<=1000 && custid>=501) {
        double disc = .28;
    }
    else if(custid>=1001) {
        double disc = .32;
    }

    if(bill>=1000) {
        System.out.println(bill*disc);
    }

Body:
You only need to declare the variable data type once, as you are declaring it multiple times whilst assigning it, hence the duplicate local variable error. Declare your variable once before the conditions to allow it to be reassignable in your conditions.

Try this:

double disc = 0;

if(custid<=100 && custid>=1) {
    disc = .15;
}
else if(custid<=250 && custid>=101) {
    disc = .18;
}
else if(custid<=500 && custid>=251) {
    disc = .23;
}
else if(custid<=1000 && custid>=501) {
    disc = .28;
}
else if(custid>=1001) {
    disc = .32;
}


问:
Primary key in sqlite3

I'm designing a new Python application to store historical and realtime stock trades using Sqlite3.
The database will store many stock symbols with varying amount of data.
Some symbols would have data for every day, some would only have the current day.

My problem is to decide on the best database design in terms of disk efficiency and speed performance.
One approach is to use one table per symbol and the PK would be datetime (text or integer).  It makes sense since my analyser will only need a few tables at a time. Con: the database will contain many thousands of tables.

The other approach would be to use one table for all stocks. The PK would be a compound of 2 columns (Stock+datetime).

 Best design decision requires a good knowledge about cache management in sqlite3.

Which approach would be the best?

Is there a tool to simulate or estimate performance?

What would be your choice? based on what?

Thanks

答:
I would recommend having a unique table to store the trades instead of multiple tables.

From database normalization perspective, all data of the same entity should be store in the same table (obviously, a stock trade is an entity). If you spread your data into multiple tables, querying across trades will be tedious, and require hardcoding table names, or using dynamic SQL.

You mentionned 0 to 1 row per trade and per day, so unless you have a huge number of quotes, the volume of the table should be reasonable.

I would also recommend having a separate table to store the list of stocks, with an auto-incremented primary key (and possibly a unique key on the stock name); the daily trades table should then reference that table through a forein key constraint. This allows you to guarantee referential integrity, while also limiting the size of trades table (an integer is usually cheaper than a string).

Title: Primary key in sqlite3


问:
How can I add a mouse over event to this function?
I am working on a slideshow / carousel in HTML with vanilla JS controlling the changing of the slides. I am happy with the current functionality, but I would like the slideshow to pause if the user hovers over the gallery. I understand that I could do this by clearing the timeout function, but I am stuck on how to integrate that into the current function. I am trying to add this functionality to the 'showSlides' function.

HTML

```<code><div class="galleryImages">
            <div class="numbertext">1 / 2</div>
            <img src="./assets/images/1.jpg" style="width: 100%;" />
          </div>

          <div class="galleryImages">
            <div class="numbertext">2 / 2</div>
            <img src="./assets/images/2.jpg" style="width: 100%;" />
          </div>

          <!-- Next and previous buttons -->
          <a class="prev" onclick="plusSlides(-1)">❮</a>
          <a class="next" onclick="plusSlides(1)">❯</a>
        </div>
</code>```

JS

```<code>var slideIndex = 0;
showSlides();

// Next/previous controls
function plusSlides(n) {
  changeSlides((slideIndex += n));
}
// automatically show slides and change the slide at the set timeout
function showSlides() {
  var i;
  var slides = document.getElementsByClassName("galleryImages");
  let gallery = document.getElementById("gallery");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {
    slideIndex = 1;
  }
  slides[slideIndex - 1].style.display = "block";
  setTimeout(showSlides, 5000); // Change image every 5 seconds
}
// change the slides based on the user input on the prev and next buttons
function changeSlides(n) {
  var i;
  var slides = document.getElementsByClassName("galleryImages");
  if (n > slides.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = slides.length;
  }
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slides[slideIndex - 1].style.display = "block";
}
</code>```

答:
Add a variable which will hold a reference to the timeout to the top:

var currentTimeout = null;
```

<p>Store the new timeout into this variable when creating:</p>

<pre class="lang-js prettyprint-override"><code>currentTimeout = setTimeout(showSlides, 5000); // Change image every 5 seconds
</code>```

Hover event handler:

if (currentTimeout) {
   clearTimeout(currentTimeout);
   currentTimeout = null;
}
```

<p>Hoverout event handler:</p>

<pre class="lang-js prettyprint-override"><code>if (currentTimeout) {
  // Should never happen, but to be safe...
  clearTimeout(currentTimeout);
}
currentTimeout = setTimeout(showSlides, 5000); // Change image every 5 seconds
</code>```

Body:
I am working on a slideshow / carousel in HTML with vanilla JS controlling the changing of the slides. I am happy with the current functionality, but I would like the slideshow to pause if the user hovers over the gallery. I understand that I could do this by clearing the timeout function, but I am stuck on how to integrate that into the current function. I am trying to add this functionality to the 'showSlides' function.

HTML

1 / 2

2 / 2

          ❮
          ❯

JS

var slideIndex = 0;
showSlides();

// Next/previous controls
function plusSlides(n) {
  changeSlides((slideIndex += n));
}
// automatically show slides and change the slide at the set timeout
function showSlides() {
  var i;
  var slides = document.getElementsByClassName("galleryImages");
  let gallery = document.getElementById("gallery");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {
    slideIndex = 1;
  }
  slides[slideIndex - 1].style.display = "block";
  setTimeout(showSlides, 5000); // Change image every 5 seconds
}
// change the slides based on the user input on the prev and next buttons
function changeSlides(n) {
  var i;
  var slides = document.getElementsByClassName("galleryImages");
  if (n > slides.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = slides.length;
  }
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slides[slideIndex - 1].style.display = "block";
}

Body:
Add a variable which will hold a reference to the timeout to the top:

var currentTimeout = null;

Store the new timeout into this variable when creating:

currentTimeout = setTimeout(showSlides, 5000); // Change image every 5 seconds

Hover event handler:

if (currentTimeout) {
   clearTimeout(currentTimeout);
   currentTimeout = null;
}

Hoverout event handler:

if (currentTimeout) {
  // Should never happen, but to be safe...
  clearTimeout(currentTimeout);
}
currentTimeout = setTimeout(showSlides, 5000); // Change image every 5 seconds


问:
Laravel run code when new user registrated with default registration code
Im running a laravel 6.9 application with default authentication/registration.

I want to maintain the default registration process but i want to run a curl command if a user has registered.
Is it possible to hook into the default registration process and extend it with extra code?

答:
Observer is good point in code where you can, well, observe if user is just registered but good place to put additional code after user has been registered is event/listener group. There is already Registered event set in EventServiceProvider so you would need to put additional listener beside one already set there (for sending email to newly registered user if opted). To have all sorted next steps should be followed (disclaimer: I am taking that you use all default auth code so far):

First copy registered(Request $request, $user) method from Illuminate\Foundation\Auth\RegistersUsers.php trait to default App\Http\Controllers\Auth\RegisterController

```<code>/**
 * The user has been registered.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function registered(Request $request, $user)
{
    //
}
</code>```

So you would override that piece of default code which is meant to stay intact (as should every code from vendor directory).

Then, you would need to create listener. In App\Providers\EventServiceProvider::listen array, add one more class into value array so it should looks like

```<code>/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    Registered::class => [
        SendEmailVerificationNotification::class,
        \App\Listeners\FooBarBaz::class,
    ],
];
</code>```

Don't bother for not having created class already, next artisan command will do that for you:

```<code>php artisan event:generate
</code>```

Now, in \App\Listeners\FooBarBaz::class you can make your custom code related to new user:

```<code>namespace App\Listeners;

use Illuminate\Auth\Events\Registered;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class FooBarBaz
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Registered  $event
     * @return void
     */
    public function handle(Registered $event)
    {
        // $event->user is accessible here
        //
        // this method should return void, it is just executed
    }
}
</code>```

Now, back to registered method of RegisterController. Here you would need to initiate event:

```<code>/**
 * The user has been registered.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function registered(Request $request, $user)
{
    event(new \Illuminate\Auth\Events\Registered($user));
}
</code>```

And you are done.
I wanted to show you use of already lot of prebuilt code although Observer is also good place. But also for calling event; I wouldn't put more code than this event(new \Illuminate\Auth\Events\Registered($user)); line into UserObserver::created(User $user). Whole part with event/listener is very good and decoupled now. Of course, you can make even custom event not using default Illuminate's one, just set that new key => value into EventServiceProvider.

Events
Observers

Body:
Observer is good point in code where you can, well, observe if user is just registered but good place to put additional code after user has been registered is event/listener group. There is already Registered event set in EventServiceProvider so you would need to put additional listener beside one already set there (for sending email to newly registered user if opted). To have all sorted next steps should be followed (disclaimer: I am taking that you use all default auth code so far):

First copy registered(Request $request, $user) method from Illuminate\Foundation\Auth\RegistersUsers.php trait to default App\Http\Controllers\Auth\RegisterController

/**
 * The user has been registered.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function registered(Request $request, $user)
{
    //
}

So you would override that piece of default code which is meant to stay intact (as should every code from vendor directory).

Then, you would need to create listener. In App\Providers\EventServiceProvider::listen array, add one more class into value array so it should looks like

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    Registered::class => [
        SendEmailVerificationNotification::class,
        \App\Listeners\FooBarBaz::class,
    ],
];

Don't bother for not having created class already, next artisan command will do that for you:

php artisan event:generate

Now, in \App\Listeners\FooBarBaz::class you can make your custom code related to new user:

namespace App\Listeners;

use Illuminate\Auth\Events\Registered;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class FooBarBaz
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Registered  $event
     * @return void
     */
    public function handle(Registered $event)
    {
        // $event->user is accessible here
        //
        // this method should return void, it is just executed
    }
}

Now, back to registered method of RegisterController. Here you would need to initiate event:

/**
 * The user has been registered.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function registered(Request $request, $user)
{
    event(new \Illuminate\Auth\Events\Registered($user));
}

And you are done.
I wanted to show you use of already lot of prebuilt code although Observer is also good place. But also for calling event; I wouldn't put more code than this event(new \Illuminate\Auth\Events\Registered($user)); line into UserObserver::created(User $user). Whole part with event/listener is very good and decoupled now. Of course, you can make even custom event not using default Illuminate's one, just set that new key => value into EventServiceProvider.

Events
Observers


答:
Declare your variable before conditions. Then you only have to assign value to this variable:</p>

```<code>    double disc = 0;

    if(custid<=100 && custid>=1) {
        disc = .15;
    }
    else if(custid<=250 && custid>=101) {
        disc = .18;
    }
    else if(custid<=500 && custid>=251) {
        disc = .23;
    }
    else if(custid<=1000 && custid>=501) {
        disc = .28;
    }
    else if(custid>=1001) {
        disc = .32;
    }

    if(bill>=1000) {
        System.out.println(bill*disc);
    }
</code>```

Title: Is it possible to have multiple potential values for a variable in java

Body:
Declare your variable before conditions. Then you only have to assign value to this variable:

    double disc = 0;

    if(custid<=100 && custid>=1) {
        disc = .15;
    }
    else if(custid<=250 && custid>=101) {
        disc = .18;
    }
    else if(custid<=500 && custid>=251) {
        disc = .23;
    }
    else if(custid<=1000 && custid>=501) {
        disc = .28;
    }
    else if(custid>=1001) {
        disc = .32;
    }

    if(bill>=1000) {
        System.out.println(bill*disc);
    }


问:
Http failure during parsing for - angular http post to php
I am able to consume the php endpoint from postman. I try to do the same from angular post, I get this error - Http failure during parsing for. Even though everything looks perfect to me, the problem is surprising. Here is my snippet

php file

```<code><?php
header('Access-Control-Allow-Origin: *');

// check for post
if ($_SERVER['REQUEST_METHOD']=='POST') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';
    // connecting to db
    $conn = new db_CONNECT();

    $cone=$conn->con;

    //escpae the strings to be inserted to DB
    $escapedname = mysqli_real_escape_string($cone, $name);
    $escapedemail = mysqli_real_escape_string($cone, $email);
    $escapedsubject= mysqli_real_escape_string($cone, $subject);
    $escapedmessage = mysqli_real_escape_string($cone, $message);

    // mysql inserting a new row
    $sql = "INSERT INTO contacts(name, email, subject, message) VALUES ('$escapedname', '$escapedemail', '$escapedsubject', '$escapedmessage')";
    // $result= $cone -> query($sql);
    // $affected = $cone -> affected_rows;

    if (mysqli_query($cone,$sql)) {
        echo "Information saved successfully.";
    } else {
        echo "Not successful";
    }
 } else {
    echo "Some field missing.";
}
?>
</code>```

here is the angular snippet

```<code>saveContactDetails = function () {

    this.proceed = true;
    this.success = false;
    const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
    data.append('name', this.contactDeJson.name);
    data.append('email', this.contactDeJson.email);
    data.append('subject', this.contactDeJson.subject);
    data.append('message', this.contactDeJson.message);

    this.http
    .post('http://localhost:80/'+'api/create_contact.php', data.toString(), {headers: myheader})
</code>```

Please why am I getting this error

```<code>{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost/api/create_contact.php","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://localhost/api/create_contact.php",
</code>```

答:
I believe you are trying to send some query parameters using data variable. You could actually send a JS object as the parameters. Try the following

private saveContactDetails() {
  this.proceed = true;
  this.success = false;
  const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
  const data = {
    'name': this.contactDeJson.name,
    'email': this.contactDeJson.email,
    'subject': this.contactDeJson.subject,
    'message': this.contactDeJson.message
  }

  this.http.post('http://localhost:80/'+'api/create_contact.php', { params: data }, { headers: myheader })
}
```

Body:
I am able to consume the php endpoint from postman. I try to do the same from angular post, I get this error - Http failure during parsing for. Even though everything looks perfect to me, the problem is surprising. Here is my snippet

php file

<?php
header('Access-Control-Allow-Origin: *');

// check for post
if ($_SERVER['REQUEST_METHOD']=='POST') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';
    // connecting to db
    $conn = new db_CONNECT();

    $cone=$conn->con;

    //escpae the strings to be inserted to DB
    $escapedname = mysqli_real_escape_string($cone, $name);
    $escapedemail = mysqli_real_escape_string($cone, $email);
    $escapedsubject= mysqli_real_escape_string($cone, $subject);
    $escapedmessage = mysqli_real_escape_string($cone, $message);

    // mysql inserting a new row
    $sql = "INSERT INTO contacts(name, email, subject, message) VALUES ('$escapedname', '$escapedemail', '$escapedsubject', '$escapedmessage')";
    // $result= $cone -> query($sql);
    // $affected = $cone -> affected_rows;

    if (mysqli_query($cone,$sql)) {
        echo "Information saved successfully.";
    } else {
        echo "Not successful";
    }
 } else {
    echo "Some field missing.";
}
?>

here is the angular snippet

saveContactDetails = function () {

    this.proceed = true;
    this.success = false;
    const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
    data.append('name', this.contactDeJson.name);
    data.append('email', this.contactDeJson.email);
    data.append('subject', this.contactDeJson.subject);
    data.append('message', this.contactDeJson.message);

    this.http
    .post('http://localhost:80/'+'api/create_contact.php', data.toString(), {headers: myheader})

Please why am I getting this error

{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost/api/create_contact.php","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://localhost/api/create_contact.php",


问:
How to pass a templated function parameter with a subclass of the templated type in C++?
Compiling the following contrived example:

```<code>class Base
{};

class Derived : public Base
{};

template< typename T >
class A
{};

class B
{
public:

    static void f( const A< Base >& ) {}
};

int main()
{
    A< Base > tb;
    A< Derived > td;

    B::f( tb );
    B::f( td );

    return 0;
}
</code>```

using g++-8 gives me the following error:

```<code>error: no matching function for call to 'B::f(A<Derived>&)'
 B::f( td );
note:   no known conversion for argument 1 from 'A<Derived>' to 'const A<Base>&'
</code>```

Why?

Since Derived is-a Base and it doesn't override any of Base's stuff, why can't I give a Derived in the place of a Base in the templated function parameter?

答:
It is true that Derived is derived from Base, but that doesn't mean that A<Derived> must therefore be derived from A<Base>. C++ templates don't work this way.

All that A<Derived> is, is a class, instantiated by the A template. You could've simply declared:

```<code>class A_Derived {

     // ...

};
</code>```

With the same members (if it had any), and pretty much got the same results. Same for A<Base>. With nothing else in the picture, the two classes have absolutely nothing to do with each other, whatsoever. You can draw a mental picture here, as if you made the following declarations:

```<code>class A_Derived {

};
</code>```

and

```<code>class A_Base {

};
</code>```

Which is pretty much what this is history. Do you see A_Derived being explicitly derived from A_Base here? Obviously not. If something expects a reference or a pointer to A_Base, you cannot give it A_Derived, because the two classes have absolutely nothing to do with each other. They are independent classes.

P.S. You could declare an explicit specialization of A<Derived> as being derived from A<Base>, if you so wish, but specialization is a completely different topic...

Body:
Compiling the following contrived example:

class Base
{};

class Derived : public Base
{};

template< typename T >
class A
{};

class B
{
public:

    static void f( const A< Base >& ) {}
};

int main()
{
    A< Base > tb;
    A< Derived > td;

    B::f( tb );
    B::f( td );

    return 0;
}

using g++-8 gives me the following error:

error: no matching function for call to 'B::f(A<Derived>&)'
 B::f( td );
note:   no known conversion for argument 1 from 'A<Derived>' to 'const A<Base>&'

Why?

Since Derived is-a Base and it doesn't override any of Base's stuff, why can't I give a Derived in the place of a Base in the templated function parameter?

Body:
It is true that Derived is derived from Base, but that doesn't mean that A<Derived> must therefore be derived from A<Base>. C++ templates don't work this way.

All that A<Derived> is, is a class, instantiated by the A template. You could've simply declared:

class A_Derived {

     // ...

};

With the same members (if it had any), and pretty much got the same results. Same for A<Base>. With nothing else in the picture, the two classes have absolutely nothing to do with each other, whatsoever. You can draw a mental picture here, as if you made the following declarations:

class A_Derived {

};

and

class A_Base {

};

Which is pretty much what this is history. Do you see A_Derived being explicitly derived from A_Base here? Obviously not. If something expects a reference or a pointer to A_Base, you cannot give it A_Derived, because the two classes have absolutely nothing to do with each other. They are independent classes.

P.S. You could declare an explicit specialization of A<Derived> as being derived from A<Base>, if you so wish, but specialization is a completely different topic...


问:
datalist how to tell if input is one of the options
I was wondering why why I select 2 with a select tag it returns true in the console. But Whenever I select 2 in the datalist it returns false in the console.

In short I need the datalist to return tru. I need to it be true so that when the user enters in the input I can ensure that the user has enter in a option I wanted (one of the drop down menu options )

function castvote() {
    var selected = document.getElementById('vote');
    console.log("Chrome" in selected);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <input list="vote" onchange="castvote()" id="voteInput">
  <datalist id="vote" >
    <option value="Chrome">
  </datalist>

<label>Choose a browser from this list:
    <input id = "a" list="browsers" name="myBrowser"
      style="width: 400px;" onclick="test()" /></label>
  <datalist id="browsers">
    <option value="Chrome">
    <option value="Firefox">
    <option value="Internet Explorer">
    <option value="Opera">
    <option value="Safari">
    <option value="Microsoft Edge">
  </datalist></code>```

答:
You should try this.
I just put (.children) at the getElementById() to get all children of datalist and the onChange() function put at the input tag.

```<code>       <input list="vote" onchange="castvote()" id="voteInput">
        <datalist id="vote" >
            <option value="2">
            <option value="3">
            <option value="4">
            <option value="5">
            <option value="6">
        </datalist>

        <script>
        function castvote() {
            var datalist = document.getElementById('vote').children;
            console.log("2" in datalist);
        }
        </script>
</code>```

Body:
I was wondering why why I select 2 with a select tag it returns true in the console. But Whenever I select 2 in the datalist it returns false in the console.

In short I need the datalist to return tru. I need to it be true so that when the user enters in the input I can ensure that the user has enter in a option I wanted (one of the drop down menu options )

function castvote() {
    var selected = document.getElementById('vote');
    console.log("Chrome" in selected);
}

  <input list="vote" onchange="castvote()" id="voteInput">
  <datalist id="vote" >
    <option value="Chrome">
  </datalist>

Choose a browser from this list:
    <input id = "a" list="browsers" name="myBrowser"
      style="width: 400px;" onclick="test()" />
  <datalist id="browsers">
    <option value="Chrome">
    <option value="Firefox">
    <option value="Internet Explorer">
    <option value="Opera">
    <option value="Safari">
    <option value="Microsoft Edge">
  </datalist>

Body:
You should try this.
I just put (.children) at the getElementById() to get all children of datalist and the onChange() function put at the input tag.

       <input list="vote" onchange="castvote()" id="voteInput">
        <datalist id="vote" >
            <option value="2">
            <option value="3">
            <option value="4">
            <option value="5">
            <option value="6">
        </datalist>

        <script>
        function castvote() {
            var datalist = document.getElementById('vote').children;
            console.log("2" in datalist);
        }
        </script>