问:
Icecast Server url only works on ":80"
I am running Icecast server on Windows system, latest version, and trying to use SSL. It does work, but only when I add :80 to my URL. Some Android users say that they have problems listening to the stream, but it does work for me. I want to try to reach the server without this added :80 to the url, hopefully taht will solve listening issues (I probably do something wrong! I just don't know what).

Server URL: https://icecast.myradio.co.il:80

Audio tag Fiddle: https://jsfiddle.net/hd3r1p29/

Icecast XML:

```<code><icecast>
    <admin>hidden</admin>
    <location>earth</location>
    <limits>
        <clients>1000</clients>
        <sources>5</sources>
        <queue-size>524288</queue-size>
        <client-timeout>30</client-timeout>
        <header-timeout>15</header-timeout>
        <source-timeout>10</source-timeout>
        <!-- same as burst-on-connect, but this allows for being more
             specific on how much to burst. Most people won't need to
             change from the default 64k. Applies to all mountpoints  -->
        <burst-size>65535</burst-size>
    </limits>

    <authentication>
        <!-- Sources log in with username 'source' -->
        <source-password>hidden</source-password>
        <!-- Relays log in username 'relay' -->
        <relay-password>hidden</relay-password>

        <!-- Admin logs in with the username given below -->
        <admin-user>hidden</admin-user>
        <admin-password>hidden</admin-password>
    </authentication>

    <hostname>icecast.myradio.co.il</hostname>

    <!-- You may have multiple <listener> elements -->
    <listen-socket>
        <port>8000</port>
        <bind-address>144.76.80.253</bind-address>
        </listen-socket>
    <listen-socket>
        <port>80</port>
        <bind-address>144.76.80.253</bind-address>
        <ssl>1</ssl>
        </listen-socket>
    <fileserve>1</fileserve>
<paths>
<logdir>./log</logdir>
<webroot>./web</webroot>
<adminroot>./admin</adminroot>
<ssl-certificate>./ssl/icecast.pem</ssl-certificate>
<alias source="/" dest="/index.html"/>
    </paths>

</icecast>
</code>```

Thanks for your help!

答:
It's not normal to run HTTPS on port 80.  Normally, it's ran up on port 443.  Port 80 is where normal HTTP runs.  This is why when you use an HTTPS URL, you have to specify the port... because you're not using the standard port configuration.

Set your <listen-socket> with SSL enabled to use port 443.  Change the other that's currently on port 8000 to 80.

Title: Icecast Server url only works on ":80"

Body:
I am running Icecast server on Windows system, latest version, and trying to use SSL. It does work, but only when I add :80 to my URL. Some Android users say that they have problems listening to the stream, but it does work for me. I want to try to reach the server without this added :80 to the url, hopefully taht will solve listening issues (I probably do something wrong! I just don't know what).

Server URL: https://icecast.myradio.co.il:80

Audio tag Fiddle: https://jsfiddle.net/hd3r1p29/

Icecast XML:

<icecast>
    <admin>hidden</admin>
    <location>earth</location>
    <limits>
        <clients>1000</clients>
        <sources>5</sources>
        <queue-size>524288</queue-size>
        <client-timeout>30</client-timeout>
        15
        <source-timeout>10</source-timeout>

        <burst-size>65535</burst-size>
    </limits>

    <authentication>

        <source-password>hidden</source-password>

        <relay-password>hidden</relay-password>

        <admin-user>hidden</admin-user>
        <admin-password>hidden</admin-password>
    </authentication>

    <hostname>icecast.myradio.co.il</hostname>

    <listen-socket>
        <port>8000</port>
        <bind-address>144.76.80.253</bind-address>
        </listen-socket>
    <listen-socket>
        <port>80</port>
        <bind-address>144.76.80.253</bind-address>
        <ssl>1</ssl>
        </listen-socket>
    <fileserve>1</fileserve>
<paths>
<logdir>./log</logdir>
<webroot>./web</webroot>
<adminroot>./admin</adminroot>
<ssl-certificate>./ssl/icecast.pem</ssl-certificate>
<alias source="/" dest="/index.html"/>
    </paths>

</icecast>

Thanks for your help!


来源: stackexchange

问:
Program to Download all PDF files from webpage
I am trying to write a Python 3 program which will download all the PDF files from this website.
I currently have two codes but none of them work.

```<code>import requests
import urllib.request
import urllib.request
import time
import re
from bs4 import BeautifulSoup
url = 'https://fraser.stlouisfed.org/title/1339#556573.html'
response = requests.get(url)
if response.status_code == 200:
      print("Success")
else:
      print("Failure")

soup = BeautifulSoup(response.text, 'html.parser')
for one_a_tag in soup.findAll('a',href=re.compile(r'(.pdf)')):
    link = one_a_tag['href']
    download_url = 'https://fraser.stlouisfed.org/title/1339'+ link
    urllib.request.urlretrieve(download_url)
    time.sleep(1)
</code>```

The program runs without giving any output or stopping.

An the second program

```<code>from urllib import request
from bs4 import BeautifulSoup
import re
import os
import urllib
url="https://fraser.stlouisfed.org/title/1339#518552"
response = request.urlopen(url).read()
soup= BeautifulSoup(response, "html.parser")
links = soup.find_all('a', href=re.compile(r'(.pdf)'))
url_list = []
for el in links:
    if(el['href'].startswith('http')):
    url_list.append(el['href'])
else:
    url_list.append("https://fraser.stlouisfed.org/title/1339/" + el['href'])

print(url_list)
for url in url_list:
     print(url)
     request.urlretrieve(url, r'C:/Downloads')
</code>```

For both programs if I add a second argument (filename) to urlretrieve where PDF files should download it gives me

[Errno 13] Permission denied: 'C:/Downloads' error.

(I have tried multiple things to solve this error, it does not work, I have Windows). If I do not have the second argument, the second program keeps going on and producing output but does not download.

Could anybody help please?

答: In most instances, the C:/ drive is locked down try changing to a different drive as X:/ or D:/ or redirect C:/Downloads to C:\Users\Name\Downloads.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a Python 3 program which will download all the PDF files from this website.
I currently have two codes but none of them work.

import requests
import urllib.request
import urllib.request
import time
import re
from bs4 import BeautifulSoup
url = 'https://fraser.stlouisfed.org/title/1339#556573.html'
response = requests.get(url)
if response.status_code == 200:
      print("Success")
else:
      print("Failure")

soup = BeautifulSoup(response.text, 'html.parser')
for one_a_tag in soup.findAll('a',href=re.compile(r'(.pdf)')):
    link = one_a_tag['href']
    download_url = 'https://fraser.stlouisfed.org/title/1339'+ link
    urllib.request.urlretrieve(download_url)
    time.sleep(1)

The program runs without giving any output or stopping.

An the second program

from urllib import request
from bs4 import BeautifulSoup
import re
import os
import urllib
url="https://fraser.stlouisfed.org/title/1339#518552"
response = request.urlopen(url).read()
soup= BeautifulSoup(response, "html.parser")
links = soup.find_all('a', href=re.compile(r'(.pdf)'))
url_list = []
for el in links:
    if(el['href'].startswith('http')):
    url_list.append(el['href'])
else:
    url_list.append("https://fraser.stlouisfed.org/title/1339/" + el['href'])

print(url_list)
for url in url_list:
     print(url)
     request.urlretrieve(url, r'C:/Downloads')

For both programs if I add a second argument (filename) to urlretrieve where PDF files should download it gives me

[Errno 13] Permission denied: 'C:/Downloads' error.

(I have tried multiple things to solve this error, it does not work, I have Windows). If I do not have the second argument, the second program keeps going on and producing output but does not download.

Could anybody help please?


问:
How to call another function's results
```<code>def most_frequency_occ(chars,inputString):
    count = 0
    for ind_char in inputString:
        ind_char = ind_char.lower()
        if chars == ind_char:
             count += 1
    return count

def general(inputString):
    maxOccurences = 0
    for chars in inputString:
        most_frequency_occ(chars, inputString)
</code>```

This is my current code. I'm trying to find the most frequent occurring letter in general. I created another function called most_frequency_occ that finds a specific character in the string that occurs the most often, but how do I generalize it into finding the frequent letter in a string without specifying a specific character and only using loops, without any build in string functions either.

For example:

```<code>print(general('aqweasdaza'))
</code>```

should print 4 as "a" occurs the most frequently, occurring 4 times.

答:
If I got your task, I think that using a dictionary will be more comfortable for you.</p>

```<code> # initializing string
 str = "Hello world"

 # initializing dict of freq
 freq = {}

     for i in str:
         if i in freq:
              freq[i] += 1
         else:
              freq[i] = 1

 # Now, you have the count of every char in this string.
 # If you want to extract the max, this step will do it for you:

 max_freq_chr = max(stats.values())
</code>```

Title: How to call another function's results

Body:
def most_frequency_occ(chars,inputString):
    count = 0
    for ind_char in inputString:
        ind_char = ind_char.lower()
        if chars == ind_char:
             count += 1
    return count

def general(inputString):
    maxOccurences = 0
    for chars in inputString:
        most_frequency_occ(chars, inputString)

This is my current code. I'm trying to find the most frequent occurring letter in general. I created another function called most_frequency_occ that finds a specific character in the string that occurs the most often, but how do I generalize it into finding the frequent letter in a string without specifying a specific character and only using loops, without any build in string functions either.

For example:

print(general('aqweasdaza'))

should print 4 as "a" occurs the most frequently, occurring 4 times.

Body:
If I got your task, I think that using a dictionary will be more comfortable for you.

 # initializing string
 str = "Hello world"

 # initializing dict of freq
 freq = {}

     for i in str:
         if i in freq:
              freq[i] += 1
         else:
              freq[i] = 1

 # Now, you have the count of every char in this string.
 # If you want to extract the max, this step will do it for you:

 max_freq_chr = max(stats.values())


问:
Can i have the treegrid structure in my hierarchical treestructure in the same nattable? Can i combine both?
I want to have the treegrid strcuture(screenshot: https://imgur.com/M4HUG6d) where we have the root object at the top and then A and A.1 and so on get expanded as comparator handles that, but i want to know how to have this functionality in the hierarchical grid table,its a tricky think to ask, but i need to know what things i need to change and what should be my approach towards getting that functionality, how the bodylayerstack should look like and i want to keep the hierarchy and i want to add the tree format in the hierarchical table at least in the first column.
Your answer will be highly apprecaited.
Thanks  </p>

答: You can either have a tree or a hierachical tree representation. It is not supported to combine those two representations. You can not re-use the TreeFormat from the tree representation as the hierarchical tree has its own internally. And if your data model is not a hierarchical data model, you can not use it in the hierachical representation. The hierarchical representation takes a hierachical data model and transfers it to a special wrapper model, where the tree takes a flat list and builds the tree structure from that. So you need to change your data model if you want to move to the hierarchical tree representation. </p>


问:
Replace duplicates with first values in dataframe
df

```<code>ITEM      CATEGORY       COLOR

48684      CAR           RED
54519      BIKE          BLACK
14582      CAR           BLACK
45685      JEEP          WHITE
23661      BIKE          BLUE
23226      BIKE          BLUE
54252      BIKE          BLACK

</code>```

df.loc[df.duplicated(['CATEGORY', 'COLOR','ITEM']), 'ITEM'] = 'ITEM' Does not give me required output. I need the output a below.

```<code>ITEM      CATEGORY       COLOR

48684      CAR           RED
54519      BIKE          BLACK
14582      CAR           BLACK
45685      JEEP          WHITE
23661      BIKE          BLUE
23661      BIKE          BLUE
54519      BIKE          BLACK
</code>```

If the CATEGORY and COLOR are the same replace the ITEM number should be replaced with the first value.

答:
Use GroupBy.transform with GroupBy.first by all values:

```<code>df['ITEM'] = df.groupby(['CATEGORY', 'COLOR'])['ITEM'].transform('first')

print (df)
    ITEM CATEGORY  COLOR
0  48684      CAR    RED
1  54519     BIKE  BLACK
2  14582      CAR  BLACK
3  45685     JEEP  WHITE
4  23661     BIKE   BLUE
5  23661     BIKE   BLUE
6  54519     BIKE  BLACK
</code>```

If want filter only duplicated for improve performance (if is more unique rows and less duplicates) add DataFrame.duplicated by 2 columns with keep=False and apply groupby only for filter rows by boolean indexing, also assign to filtered column ITEM:

```<code>m = df.duplicated(['CATEGORY', 'COLOR'], keep=False)
df.loc[m, 'ITEM'] = df[m].groupby(['CATEGORY', 'COLOR'])['ITEM'].transform('first')
</code>```

Body:
df

ITEM      CATEGORY       COLOR

48684      CAR           RED
54519      BIKE          BLACK
14582      CAR           BLACK
45685      JEEP          WHITE
23661      BIKE          BLUE
23226      BIKE          BLUE
54252      BIKE          BLACK

df.loc[df.duplicated(['CATEGORY', 'COLOR','ITEM']), 'ITEM'] = 'ITEM' Does not give me required output. I need the output a below.

ITEM      CATEGORY       COLOR

48684      CAR           RED
54519      BIKE          BLACK
14582      CAR           BLACK
45685      JEEP          WHITE
23661      BIKE          BLUE
23661      BIKE          BLUE
54519      BIKE          BLACK

If the CATEGORY and COLOR are the same replace the ITEM number should be replaced with the first value.

Body:
Use GroupBy.transform with GroupBy.first by all values:

df['ITEM'] = df.groupby(['CATEGORY', 'COLOR'])['ITEM'].transform('first')

print (df)
    ITEM CATEGORY  COLOR
0  48684      CAR    RED
1  54519     BIKE  BLACK
2  14582      CAR  BLACK
3  45685     JEEP  WHITE
4  23661     BIKE   BLUE
5  23661     BIKE   BLUE
6  54519     BIKE  BLACK

If want filter only duplicated for improve performance (if is more unique rows and less duplicates) add DataFrame.duplicated by 2 columns with keep=False and apply groupby only for filter rows by boolean indexing, also assign to filtered column ITEM:

m = df.duplicated(['CATEGORY', 'COLOR'], keep=False)
df.loc[m, 'ITEM'] = df[m].groupby(['CATEGORY', 'COLOR'])['ITEM'].transform('first')


问:
Sqoop import from MySQL to Hive is successful but select returns all NULL values
This has imported correct number of records, but my Hive select command gave me NULL data values.

```<code>hive> select * from widgets;
OK
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
Time taken: 0.179 seconds, Fetched: 6 row(s)
</code>```

I am importing data from MySQL table to Hive table using the command:

```<code>sqoop import
--connect jdbc:mysql://localhost/kmdb
--table widgets
-m 1
--hive-import
--hive-table widgets
</code>```

My schema looks good as below:
    hive> describe widgets;
    OK
    id                      int

    widget_name             string

    price                   double

    design_date             string

    version                 int

    design_comment          string

    Time taken: 0.268 seconds, Fetched: 6 row(s)

My data also looks good as below:

```<code>$ hdfs dfs -cat /user/hive/warehouse/widgets/part-m-00000_copy_1
1sprocket0.252010-02-101Connects two gizmos
2gizmo4.002009-11-304null
3gadget99.991983-08-1313Our flagship product
</code>```

(Note: I can see the field delimiter special characters on my console, but they are not showing up here due to some rendering.)

Background: The table was actually created using another sqoop command:

```<code>$sqoop create-hive-table
   --connect jdbc:mysql://localhost/kmdb
   --table widgets
   --fields-terminated-by ','
</code>```

Could this make any difference?

Any thoughts?

答:
When we use given import sqoop command then the hive table created by self and data should be dumped on the given directory location, as below.

```<code>> sqoop import --connect jdbc:mysql://xx.xx.xx.xx/tournament \
> --username "analytics" --password "xxxxxx" --table store_config \
> --target-dir maprfs:///user/hive/warehouse/tournament.db/store_config/  \
> --hive-import --create-hive-table --hive-table tournament.store_config
</code>```

what we are missing here in this import command?

```<code>> --fields-terminated-by
</code>```

By default, it takes delimiter as a tab but if you want to explicitly define it you need to use this command.

```<code>> --fields-terminated-by **char**
</code>```

and in next time when we go to overwrite data using

```<code>> sqoop import --connect jdbc:mysql://xx.xx.xx.xx/tournament
> --username "xxxxxx" --password "xxxxxx" \
> --table store_config \
> --delete-target-dir --target-dir 'maprfs:///user/hive/warehouse/tournament.db/store_config/' \
> --lines-terminated-by '\n' -m 1
</code>```

then we face this NULL issue when we go for fetch data via HIVE CLI.

```<code>hive> select * from store_config;
OK
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
</code>```

then what should I do, it's simple we have to just add --fields-terminated-by "\001" this in our overwrite command and problem solve.

ContentLicense: CC BY-SA 3.0

Body:
This has imported correct number of records, but my Hive select command gave me NULL data values.

hive> select * from widgets;
OK
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
Time taken: 0.179 seconds, Fetched: 6 row(s)

I am importing data from MySQL table to Hive table using the command:

sqoop import
--connect jdbc:mysql://localhost/kmdb
--table widgets
-m 1
--hive-import
--hive-table widgets

My schema looks good as below:
    hive> describe widgets;
    OK
    id                      int

    widget_name             string

    price                   double

    design_date             string

    version                 int

    design_comment          string

    Time taken: 0.268 seconds, Fetched: 6 row(s)

My data also looks good as below:

$ hdfs dfs -cat /user/hive/warehouse/widgets/part-m-00000_copy_1
1sprocket0.252010-02-101Connects two gizmos
2gizmo4.002009-11-304null
3gadget99.991983-08-1313Our flagship product

(Note: I can see the field delimiter special characters on my console, but they are not showing up here due to some rendering.)

Background: The table was actually created using another sqoop command:

$sqoop create-hive-table
   --connect jdbc:mysql://localhost/kmdb
   --table widgets
   --fields-terminated-by ','

Could this make any difference?

Any thoughts?

Body:
When we use given import sqoop command then the hive table created by self and data should be dumped on the given directory location, as below.

> sqoop import --connect jdbc:mysql://xx.xx.xx.xx/tournament \
> --username "analytics" --password "xxxxxx" --table store_config \
> --target-dir maprfs:///user/hive/warehouse/tournament.db/store_config/  \
> --hive-import --create-hive-table --hive-table tournament.store_config

what we are missing here in this import command?

> --fields-terminated-by

By default, it takes delimiter as a tab but if you want to explicitly define it you need to use this command.

> --fields-terminated-by **char**

and in next time when we go to overwrite data using

> sqoop import --connect jdbc:mysql://xx.xx.xx.xx/tournament
> --username "xxxxxx" --password "xxxxxx" \
> --table store_config \
> --delete-target-dir --target-dir 'maprfs:///user/hive/warehouse/tournament.db/store_config/' \
> --lines-terminated-by '\n' -m 1

then we face this NULL issue when we go for fetch data via HIVE CLI.

hive> select * from store_config;
OK
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL

then what should I do, it's simple we have to just add --fields-terminated-by "\001" this in our overwrite command and problem solve.


问:
creating a new guid at each iteration in an ARM template
I try to script an ARM template like this:

```<code>{
    "type": "Microsoft.EventHub/namespaces/ipfilterrules",
    "apiVersion": "2018-01-01-preview",
    "name": "[concat(parameters('name'), '/fr', copyIndex())]",
    "location": "[resourceGroup().location]",

    "properties": {
        "ipMask": "[parameters('ipMasks')[copyIndex()]]",
        "action": "Accept",
        "filterName": "[concat('fr', copyIndex())]"
    },
    "copy": {
        "name": "eventHubfirewallrulescopy",
        "count": "[length(parameters('ipMasks'))]"
}
</code>```

What I really want to to is to feed "name" and "filtername" by the same GUID value. in order to have something like this:

```<code>{
    "type": "Microsoft.EventHub/namespaces/ipfilterrules",
    "apiVersion": "2018-01-01-preview",
    "name": "[concat(parameters('name'), 'd8fb1ab2-a6cb-439f-9354-918bd96d6ace')]",
    "location": "[resourceGroup().location]",

    "properties": {
        "ipMask": "[parameters('ipMasks')[copyIndex()]]",
        "action": "Accept",
        "filterName": "d8fb1ab2-a6cb-439f-9354-918bd96d6ace"
    },
    "copy": {
        "name": "eventHubfirewallrulescopy",
        "count": "[length(parameters('ipMasks'))]"
}
</code>```

As you can see this is a multi deployement resource. So I need a new guid generated at each iteration.

I first thought to create a variable using guid() function, but it is not permitted.

Is there any other idea?
thank you

答:
How about defining a proxy parameter in the template for which you do not pass the value and is initialed to default new guid and use it in the variables later to generate the unique string? Something like this

```<code>{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
         "guidValue": {
            "type": "string",
            "defaultValue": "[newGuid()]"
        }
    },
    "variables": {
        "unique_string":"[uniqueString(parameters('guidValue'))]"
    },
    "resources":
    [
      .. your resources with names derived from variables('unique_string')
    ],
    "outputs": {
        "unique_string": {
            "type": "string",
            "value": "[variables('unique_string')]"
        }
    }
}
</code>```

Hope this helps?

Body:
I try to script an ARM template like this:

{
    "type": "Microsoft.EventHub/namespaces/ipfilterrules",
    "apiVersion": "2018-01-01-preview",
    "name": "[concat(parameters('name'), '/fr', copyIndex())]",
    "location": "[resourceGroup().location]",

    "properties": {
        "ipMask": "[parameters('ipMasks')[copyIndex()]]",
        "action": "Accept",
        "filterName": "[concat('fr', copyIndex())]"
    },
    "copy": {
        "name": "eventHubfirewallrulescopy",
        "count": "[length(parameters('ipMasks'))]"
}

What I really want to to is to feed "name" and "filtername" by the same GUID value. in order to have something like this:

{
    "type": "Microsoft.EventHub/namespaces/ipfilterrules",
    "apiVersion": "2018-01-01-preview",
    "name": "[concat(parameters('name'), 'd8fb1ab2-a6cb-439f-9354-918bd96d6ace')]",
    "location": "[resourceGroup().location]",

    "properties": {
        "ipMask": "[parameters('ipMasks')[copyIndex()]]",
        "action": "Accept",
        "filterName": "d8fb1ab2-a6cb-439f-9354-918bd96d6ace"
    },
    "copy": {
        "name": "eventHubfirewallrulescopy",
        "count": "[length(parameters('ipMasks'))]"
}

As you can see this is a multi deployement resource. So I need a new guid generated at each iteration.

I first thought to create a variable using guid() function, but it is not permitted.

Is there any other idea?
thank you

Body:
How about defining a proxy parameter in the template for which you do not pass the value and is initialed to default new guid and use it in the variables later to generate the unique string? Something like this

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
         "guidValue": {
            "type": "string",
            "defaultValue": "[newGuid()]"
        }
    },
    "variables": {
        "unique_string":"[uniqueString(parameters('guidValue'))]"
    },
    "resources":
    [
      .. your resources with names derived from variables('unique_string')
    ],
    "outputs": {
        "unique_string": {
            "type": "string",
            "value": "[variables('unique_string')]"
        }
    }
}

Hope this helps?


问:
How do I get the discount price for promo code or gift card?
I am trying to get the discount that is being calculated in the cart. I can get the coupon code with this: Mage::getSingleton('checkout/cart')->getQuote()->getCouponCode();
But I have yet to figure out how to get the amount that is discounted from the coupon code.

答:
```<code>  // get coupon amount
   $quote = Mage::getSingleton('checkout/session')->getQuote();

    foreach ($quote->getAllItems() as $item){

    echo $item->getDiscountAmount();

    }
   // get giftcard amount
   $giftcard = $quote->getGiftCardsAmountUsed();
</code>```


问:
Why isn't the "gets()" function declared when I include stdio.h?
```<code>#include <stdio.h>

int main() {
   char str[50];

   printf("Enter a string : ");
   gets(str);

   printf("You entered: %s", str);

   return (0);
}
</code>```

In my code, why isn't the gets() function declared? It shows me a bunch of errors such as:

```<code>In function ‘int main()’:
 error: ‘gets’ was not declared in this scope
gets(str);
    ^~~~
[Finished in 0.2s with exit code 1]
</code>```

I want to know why this kind of problem occurs?

答: gets has not been part of the C language for the past 9 years, and prior to that, was deprecated and extremely unsafe - not just difficult to use in a safe/correct manner, impossible. Whoever taught you C is not fit to be teaching.

Body:
#include <stdio.h>

int main() {
   char str[50];

   printf("Enter a string : ");
   gets(str);

   printf("You entered: %s", str);

   return (0);
}

In my code, why isn't the gets() function declared? It shows me a bunch of errors such as:

In function ‘int main()’:
 error: ‘gets’ was not declared in this scope
gets(str);
    ^~~~
[Finished in 0.2s with exit code 1]

I want to know why this kind of problem occurs?


问:
PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)
While running an app on the virtual device (AVD) created on Android studio (in Windows 10), I am getting an error and panic.

Emulator: PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT
Emulator: Process finished with exit code 1

While I have already defined my ANDROID_SDK_ROOT in the environment variables.

Can anyone please tell me how to resolve this problem?

答: In Korean version of Windows 10, this problem happened because my Windows user name was in Korean not in English. After the user name was made again in English, the problem was cleared.</p>


问:
Can I save label title in laravel?
Is there a way to save label title in laravel.

```<code><label for="name">Name</label>
</code>```

Suppose I want to save "Name" in database.

答:
You can use a hidden field and make its value the same as the label name.

<input name="label" value="Name" type="hidden">

Or you can use something like

```<code><form action="youraction" >
 <label for="male">Male</label>
 <input type="radio" name="gender" id="male" value="male"><br>
 <input type="submit" value="Submit">
</form>
</code>```

W3Schools - documentation

It will also depend on your use-case may be more information will be helpful.

Title: Can I save label title in laravel?

Body:
Is there a way to save label title in laravel.

Name

Suppose I want to save "Name" in database.

Body:
You can use a hidden field and make its value the same as the label name.

<input name="label" value="Name" type="hidden">

Or you can use something like

<form action="youraction" >
 <label for="male">Male</label>
 <input type="radio" name="gender" id="male" value="male"><br>
 <input type="submit" value="Submit">
</form>

W3Schools - documentation

It will also depend on your use-case may be more information will be helpful.


问:
Load binary into stm32f103c8t6 with OpenOCD and arm-none-eabi-gdb
I tried to load binary that is compiled from rust code, but it doesn't work.

First, I downloaded Rust code from https://github.com/rust-embedded/discovery.
Then, I built it.

```<code># I am in the `src/05-led-roulette` directory
rustup target add thumbv7m-none-eabi
cargo build --target thumbv7m-none-eabi
</code>```

It was successfully compiled.

After that, I successfully connected with stm32f103c8t6 using OpenOCD.
Then, I run this command.

```<code>arm-none-eabi-gdb -q target/thumbv7m-none-eabi/debug/led-roulette
</code>```

But it seemed like it didn't finish reading.

```<code>Reading symbols from target/thumbv7m-none-eabi/debug/led-roulette...
(gdb)
</code>```

(not done?!)

After that, I tried loadcommand, but it returned following sentences.

```<code>Start address 0x0, load size 0
Transfer rate: 0 bits in <1 sec.
</code>```

I have no idea about why it doesn't work.

Please help me.

答:
First see if your binary is good, then try telnet, then gdb.  Rust also multiplies the odds of failure, so start with something simple:

so.s

```<code>.thumb
.globl _start
_start:
.word 0x20001000
.word reset
.thumb_func
reset:
    ldr r0,some_addr
    ldr r1,[r0]
    add r1,r1,#1
    str r1,[r0]
    b .
    .align
some_addr: .word 0x20000000
</code>```

build it

```<code>arm-none-eabi-as so.s -o so.o
arm-none-eabi-ld -Ttext=0x08000000 so.o -o so.elf
arm-none-eabi-objdump -D so.elf
arm-none-eabi-objdump -D so.elf
</code>```

so.elf:     file format elf32-littlearm

Disassembly of section .text:

08000000 <_start>:
8000000:   20001000    andcs   r1, r0, r0
8000004:   08000009    stmdaeq r0, {r0, r3}

08000008 :
8000008:   4802        ldr r0, [pc, #8]    ; (8000014 <some_addr>)
800000a:   6801        ldr r1, [r0, #0]
800000c:   3101        adds    r1, #1
800000e:   6001        str r1, [r0, #0]
8000010:   e7fe        b.n 8000010 <reset+0x8>
8000012:   46c0        nop         ; (mov r8, r8)

08000014 <some_addr>:
8000014:   20000000    andcs   r0, r0, r0

for small programs (Read the st documentation) this can be based at address 0x08000000 or 0x00000000 for this part.  0x08000000 is preferred.  The vector table must be first in this case ignore the disassembly just look at the values

```<code> 8000000:   20001000    andcs   r1, r0, r0
 8000004:   08000009    stmdaeq r0, {r0, r3}
</code>```

The 0x08000009 is the reset address ORRed with one.  so 0x08000008 | 1 is 0x08000009. So that will at least boot and try to fetch code without a fault.

This code simply reads the word at address 0x20000000 and increments it, sram is not affected by a reset so we can keep resetting and seeing that value increment.

using whatever configs you have and interface, I combine the openocd one for the st part into a single file and carry that with the project along with ones for the various interfaces (stlinks of different versions and jlink).

```<code>openocd -f jlink.cfg -f target.cfg

Open On-Chip Debugger 0.9.0 (2019-04-28-23:34)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : JLink SWD mode enabled
swd
adapter speed: 1000 kHz
adapter_nsrst_delay: 100
none separate
cortex_m reset_config sysresetreq
Info : J-Link ARM-OB STM32 compiled Jun 30 2009 11:14:15
Info : J-Link caps 0x88ea5833
Info : J-Link hw version 70000
Info : J-Link hw type J-Link
Info : J-Link max mem block 15344
Info : J-Link configuration
Info : USB-Address: 0x0
Info : Kickstart power on JTAG-pin 19: 0x0
Info : Vref = 3.300 TCK = 1 TDI = 1 TDO = 1 TMS = 1 SRST = 1 TRST = 1
Info : J-Link JTAG Interface ready
Info : clock speed 1000 kHz
Info : SWD IDCODE 0x1ba01477
Info : stm32f1x.cpu: hardware has 6 breakpoints, 4 watchpoints
</code>```

If you don't see the watchpoints line if it returns to the console, it didn't work.

In another window

```<code>telnet localhost 4444
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Open On-Chip Debugger
>
</code>```

Now let's stop the chip and write our program. The psr, pc, etc values may be different depending than mine depending on what you had running.

```<code>> reset halt
target state: halted
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x08000010 msp: 0x20001000
> flash write_image erase so.elf
auto erase enabled
device id = 0x20036410
flash size = 64kbytes
wrote 1024 bytes from file so.elf in 0.437883s (2.284 KiB/s)
</code>```

Let's read it and see that it is there, should match the words from the disassembly

```<code>> mdw 0x08000000 20
0x08000000: 20001000 08000009 5000f04f 31016801 e7fe6001 ffffffff ffffffff ffffffff
0x08000020: ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
0x08000040: ffffffff ffffffff ffffffff ffffffff
</code>```

Assume this is random garbage and that is fine so long as we see it increment.

```<code>> mdw 0x20000000
0x20000000: 2e006816
> reset
> halt
target state: halted
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x08000012 msp: 0x20001000
> mdw 0x20000000
0x20000000: 2e006817
</code>```

So the value incremented  if you do a reset, then do a halt (not a reset halt in one command) then dump that memory location it should keep incrementing every time.

Now you can choose to take the gdb path (I don't have a use for gdb so don't have one installed) with this binary or examine your rust binary by first examining the vector table to see it is correct, without at least the reset vector being correct then you will fault and not run any code on the processor.  Can flash it using telnet or you can try gdb.

If gdb is having a problem with the file then perhaps you are using the wrong file.  or the file is incorrectly built.  did you try a simple program in that repository?  can you make a minimal program from that repository, an empty entry function or an infinite loop or a counter that counts forever?

Is this truly a gdb problem?  Is this an openocd problem? Is this a Rust tools problem? Is this a Rust binary problem?  Is this a bug in the docs and you are pointing gdb at the wrong file problem?  If the above works then openocd works, binutils at least works, the debugger/hardware works, it eliminates those and then becomes is this a rust thing, a gdb thing, using the wrong file thing, or something else?

Body:
I tried to load binary that is compiled from rust code, but it doesn't work.

First, I downloaded Rust code from https://github.com/rust-embedded/discovery.
Then, I built it.

# I am in the `src/05-led-roulette` directory
rustup target add thumbv7m-none-eabi
cargo build --target thumbv7m-none-eabi

It was successfully compiled.

After that, I successfully connected with stm32f103c8t6 using OpenOCD.
Then, I run this command.

arm-none-eabi-gdb -q target/thumbv7m-none-eabi/debug/led-roulette

But it seemed like it didn't finish reading.

Reading symbols from target/thumbv7m-none-eabi/debug/led-roulette...
(gdb)

(not done?!)

After that, I tried loadcommand, but it returned following sentences.

Start address 0x0, load size 0
Transfer rate: 0 bits in <1 sec.

I have no idea about why it doesn't work.

Please help me.

Body:
First see if your binary is good, then try telnet, then gdb.  Rust also multiplies the odds of failure, so start with something simple:

so.s

.thumb
.globl _start
_start:
.word 0x20001000
.word reset
.thumb_func
reset:
    ldr r0,some_addr
    ldr r1,[r0]
    add r1,r1,#1
    str r1,[r0]
    b .
    .align
some_addr: .word 0x20000000

build it

arm-none-eabi-as so.s -o so.o
arm-none-eabi-ld -Ttext=0x08000000 so.o -o so.elf
arm-none-eabi-objdump -D so.elf
arm-none-eabi-objdump -D so.elf

so.elf:     file format elf32-littlearm

Disassembly of section .text:

08000000 <_start>:
8000000:   20001000    andcs   r1, r0, r0
8000004:   08000009    stmdaeq r0, {r0, r3}

08000008 :
8000008:   4802        ldr r0, [pc, #8]    ; (8000014 <some_addr>)
800000a:   6801        ldr r1, [r0, #0]
800000c:   3101        adds    r1, #1
800000e:   6001        str r1, [r0, #0]
8000010:   e7fe        b.n 8000010 <reset+0x8>
8000012:   46c0        nop         ; (mov r8, r8)

08000014 <some_addr>:
8000014:   20000000    andcs   r0, r0, r0

for small programs (Read the st documentation) this can be based at address 0x08000000 or 0x00000000 for this part.  0x08000000 is preferred.  The vector table must be first in this case ignore the disassembly just look at the values

 8000000:   20001000    andcs   r1, r0, r0
 8000004:   08000009    stmdaeq r0, {r0, r3}

The 0x08000009 is the reset address ORRed with one.  so 0x08000008 | 1 is 0x08000009. So that will at least boot and try to fetch code without a fault.

This code simply reads the word at address 0x20000000 and increments it, sram is not affected by a reset so we can keep resetting and seeing that value increment.

using whatever configs you have and interface, I combine the openocd one for the st part into a single file and carry that with the project along with ones for the various interfaces (stlinks of different versions and jlink).

openocd -f jlink.cfg -f target.cfg

Open On-Chip Debugger 0.9.0 (2019-04-28-23:34)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : JLink SWD mode enabled
swd
adapter speed: 1000 kHz
adapter_nsrst_delay: 100
none separate
cortex_m reset_config sysresetreq
Info : J-Link ARM-OB STM32 compiled Jun 30 2009 11:14:15
Info : J-Link caps 0x88ea5833
Info : J-Link hw version 70000
Info : J-Link hw type J-Link
Info : J-Link max mem block 15344
Info : J-Link configuration
Info : USB-Address: 0x0
Info : Kickstart power on JTAG-pin 19: 0x0
Info : Vref = 3.300 TCK = 1 TDI = 1 TDO = 1 TMS = 1 SRST = 1 TRST = 1
Info : J-Link JTAG Interface ready
Info : clock speed 1000 kHz
Info : SWD IDCODE 0x1ba01477
Info : stm32f1x.cpu: hardware has 6 breakpoints, 4 watchpoints

If you don't see the watchpoints line if it returns to the console, it didn't work.

In another window

telnet localhost 4444
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Open On-Chip Debugger
>

Now let's stop the chip and write our program. The psr, pc, etc values may be different depending than mine depending on what you had running.

> reset halt
target state: halted
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x08000010 msp: 0x20001000
> flash write_image erase so.elf
auto erase enabled
device id = 0x20036410
flash size = 64kbytes
wrote 1024 bytes from file so.elf in 0.437883s (2.284 KiB/s)

Let's read it and see that it is there, should match the words from the disassembly

> mdw 0x08000000 20
0x08000000: 20001000 08000009 5000f04f 31016801 e7fe6001 ffffffff ffffffff ffffffff
0x08000020: ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
0x08000040: ffffffff ffffffff ffffffff ffffffff

Assume this is random garbage and that is fine so long as we see it increment.

> mdw 0x20000000
0x20000000: 2e006816
> reset
> halt
target state: halted
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x08000012 msp: 0x20001000
> mdw 0x20000000
0x20000000: 2e006817

So the value incremented  if you do a reset, then do a halt (not a reset halt in one command) then dump that memory location it should keep incrementing every time.

Now you can choose to take the gdb path (I don't have a use for gdb so don't have one installed) with this binary or examine your rust binary by first examining the vector table to see it is correct, without at least the reset vector being correct then you will fault and not run any code on the processor.  Can flash it using telnet or you can try gdb.

If gdb is having a problem with the file then perhaps you are using the wrong file.  or the file is incorrectly built.  did you try a simple program in that repository?  can you make a minimal program from that repository, an empty entry function or an infinite loop or a counter that counts forever?

Is this truly a gdb problem?  Is this an openocd problem? Is this a Rust tools problem? Is this a Rust binary problem?  Is this a bug in the docs and you are pointing gdb at the wrong file problem?  If the above works then openocd works, binutils at least works, the debugger/hardware works, it eliminates those and then becomes is this a rust thing, a gdb thing, using the wrong file thing, or something else?


问:
css margin: auto issue in footer
My problem is to split the space inside my footer bar in 3 part (each with same width)

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  text-align: center;
  /*zentriert ganzen Text im footer*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="footer-items">

  <div class="company-items">
    <h3 class="company">Company</h3>
    <ul>
      <li>Text1</li>
      <li>Text2</li>
      <li>Text3</li>
    </ul>
  </div>

  <div class="social-items">
    <h3 class="social">Social</h3>
    <ul>
      <li><a>Twitter</a></li>
      <li><a>Instagram</a></li>
      <li><a>Reddit</a></li>
    </ul>
  </div>

  <div class="other-items">
    <h3 class="text">Text4</h3>
    <ul>
      <li><a>other1</a></li>
      <li><a>other2</a></li>
    </ul>
  </div>

</div></code>```

If I try to do sth like margin-left: 33% for my 3 items in footer this is not gonna work.

thanks for your help

答:
put the width of div elements 33.33% ((100%)/number of columns) and set 0px margin for right and left.

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 100%;
  margin: auto;
  margin-right:0px;
  margin-left:0px;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  text-align: center;
  /*zentriert ganzen Text im footer*/
}

.div-box{
  width:33.33%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="footer-items">

  <div class="company-items div-box">
    <h3 class="company">Company</h3>
    <ul>
      <li>Text1</li>
      <li>Text2</li>
      <li>Text3</li>
    </ul>
  </div>

  <div class="social-items div-box">
    <h3 class="social">Social</h3>
    <ul>
      <li><a>Twitter</a></li>
      <li><a>Instagram</a></li>
      <li><a>Reddit</a></li>
    </ul>
  </div>

  <div class="other-items div-box">
    <h3 class="text">Text4</h3>
    <ul>
      <li><a>other1</a></li>
      <li><a>other2</a></li>
    </ul>
  </div>

</div></code>```

Title: css margin: auto issue in footer

Body:
My problem is to split the space inside my footer bar in 3 part (each with same width)

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  text-align: center;
  /*zentriert ganzen Text im footer*/
}

Company

Text1

Text2

Text3

Social

Twitter

Instagram

Reddit

Text4

other1

other2

If I try to do sth like margin-left: 33% for my 3 items in footer this is not gonna work.

thanks for your help

Body:
put the width of div elements 33.33% ((100%)/number of columns) and set 0px margin for right and left.

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 100%;
  margin: auto;
  margin-right:0px;
  margin-left:0px;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  text-align: center;
  /*zentriert ganzen Text im footer*/
}

.div-box{
  width:33.33%;
}

<div class="footer-items">

  <div class="company-items div-box">
    <h3 class="company">Company</h3>
    <ul>
      <li><a href="text1.html">Text1</a></li>
      <li><a href="text2.html">Text2</a></li>
      <li><a href="text3.html">Text3</a></li>
    </ul>
  </div>

  <div class="social-items div-box">
    <h3 class="social">Social</h3>
    <ul>
      <li><a>Twitter</a></li>
      <li><a>Instagram</a></li>
      <li><a>Reddit</a></li>
    </ul>
  </div>

  <div class="other-items div-box">
    <h3 class="text">Text4</h3>
    <ul>
      <li><a>other1</a></li>
      <li><a>other2</a></li>
    </ul>
  </div>

</div>


问:
Converting from Date-Time to GPS time
I want to convert an array of date-time strings (YYYY-MM-DD hh:mm:ss) to GPS seconds (seconds after 2000-01-01 12:00:00) in the python environment.

In order to get the GPS seconds for a single date in Linux BASH, I simply input date2sec datetimestring and it returns a number.

I could do this within a for-loop within python. But, how would I incorporate this within the python script, as it is an external script?

Or, is there another way to convert an array of date-time strings (or single date-time strings  incorporated into a for-loop) to GPS time without using date2sec?

答:
Updated Answer: uses Astropy library:

```<code>from astropy.time import Time

t = Time('2019-12-03 23:55:32', format='iso', scale='utc')
print(t.gps)
</code>```

Here you are setting the date in UTC and t.gps converts the datetime to GPS seconds.

Further research showed that directly using datetime objects doesn't take leap seconds into account.

other helpful links here:
How to get current date and time from GPS unsegment time in python

Title: Converting from Date-Time to GPS time

Body:
Updated Answer: uses Astropy library:

from astropy.time import Time

t = Time('2019-12-03 23:55:32', format='iso', scale='utc')
print(t.gps)

Here you are setting the date in UTC and t.gps converts the datetime to GPS seconds.

Further research showed that directly using datetime objects doesn't take leap seconds into account.

other helpful links here:
How to get current date and time from GPS unsegment time in python


问:
What is the relationship between HTTP connection and a request?
While I am configuring my nginx, I found two modules: ngx_http_limit_conn_module and ngx_http_limit_req_module
one is for limiting connection per defined key, and one for limiting request.

My question is what is the relationship (and difference) between
a HTTP connection and a request.
It seems that multiple HTTP requests can use one common HTTP connection, what is the principle under this?

答:
HTTP connections - client and server introduce themselves.

HTTP requests - client ask something from server.

Making a connection with server involves TCP handshaking and it is basically creating a socket connection with the server. To make a HTTP request you should be already established a connection with the server. If you established connection with a server you can make multiple request using the same connection(HTTP/1.0 by default one request per connection, HTTP/1.1 by default it is keep alive). As most of the web pages need multiple resources from the server(ex: 100 photos to load in the screen). It is a low burden to the server if we keep the connection and request those 100 images using the same connection(No need to go through the connection establishment process 100 times). That is why HTTP/1.0 came up with keep alive as default.


问:
Update database record using Java Spring JPA and crud
Trying to learn Java Spring by creating a simple project for storing football teams.
I am storing data to a database using JPA.
Currently i can save a "Team" to my database with my logged in user.
Now i wish to update the record for cases where team is changed or user makes mistake etc.

Can someone help me and provide the best approach?

1 Team Model class

```<code>@Data
@Entity
@Table(name="User_Team")
public class Team implements Serializable {

@OneToOne
private User user;

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;

@NotBlank(message="Team Name is required")
private  String teamName;

@NotBlank(message="Location is required")
private  String location;

@NotBlank(message="Nickname required")
private String nickName;

private String yearEstablished;

public Sport sport;

private Divison divison;

  }
</code>```

2. Team Repository

```<code>@Repository
public interface TeamRepository extends CrudRepository<Team, Long> {
Team findAllById(Long id);

   }
</code>```

3. Team Controller

```<code>@Slf4j
@Controller
@RequestMapping("/team")
@SessionAttributes("Team")

public class TeamController {

private TeamRepository teamRepository;

public TeamController(TeamRepository teamRepository) {
    this.teamRepository = teamRepository;
}

@Autowired
TeamRepository service;

@PostMapping
public String processOrder(@Valid Team team, Errors errors,
                           SessionStatus sessionStatus,
                           @AuthenticationPrincipal User user) {

    if (errors.hasErrors()) {
        return "team";
    }

    team.setUser(user);

    service.save(team);
    sessionStatus.setComplete();

    return "redirect:/team";
}

   @GetMapping
    public String displayTeam(Model model) {

      model.addAttribute("team", service.findAll());

    return "/team";
  }
  }
</code>```

4. Team Html

```<code> <!DOCTYPE html>
 <!--suppress ALL -->
 <html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org">
 <head>
 <title>Team</title>
 <link rel="stylesheet" th:href="@{/styles.css}" />
 </head>
 <body>
 <div class="hero-image">
<div class="hero-text">
    <h1 style="font-size:50px">Team</h1>
</div>
</div>

<div class="tab">

<button class="tablinks"><a href="team">Team Info</a></button>
<button class="tablinks"><a href="player">Players Info</a></button>
<button class="tablinks"><a href="fixtures">Fixtures</a></button>

</div>

<div id="Home" class="tabcontent">
<h3>Home</h3>
</div>

<div id="About" class="tabcontent">
<h3>Team Info</h3>
</div>

 <div id="Contact" class="tabcontent">
   <h3>Player Info</h3>
 </div>

<table>
    <tr>
        <th>Team name</th>
        <th>Location</th>
        <th>Nickname</th>
        <th>Year Formed</th>
        <th>Sport</th>
        <th>Division</th>
    </tr>
    <tr th:each = "about: ${team}">
        <td th:text="${about.teamName}"></td>
        <td th:text="${about.location}"></td>
        <td th:text="${about.nickName}"></td>
        <td th:text="${about.yearEstablished}"></td>
        <td th:text="${about.sport}"></td>
        <td th:text="${about.divison.displayValue}"></td>

    </tr>

    <!--<input type="file" name="pic" accept="image/*">
    <input type="submit">-->

</table>

 <button class="open-button" onclick="openForm()">Add your team</button>
 <div class="form-popup" id="myForm">
 <form method="POST" th:action="@{/team}" class="form-container" id="aboutForm">
    <label for="teamName">Team name: </label>
    <input type="text" name="teamName"/><br/>

    <label for="location">Location: </label>
    <input type="text" name="location"/><br/>

    <label for="nickName">Nickname: </label>
    <input type="text" name="nickName"/><br/>

    <label for="yearEstablished">Year Formed: </label>
    <input type="text" name="yearEstablished"/><br/>

    <label for="sport">Sport:</label>
    <select name="sport">
        <option th:each="colorOpt : ${T(sportsapp.sportsapp.Sport).values()}"
                th:value="${colorOpt}" th:text="${colorOpt.displayName}"></option>
    </select>

    <label for="divison">Divison:</label>
    <select name="divison">
        <option th:each="colorOpt : ${T(sportsapp.sportsapp.Divison).values()}"
                th:value="${colorOpt}" th:text="${colorOpt.displayValue}"></option>
    </select>

    <div class="mytest">
        <input type="submit" value="Add"/>
    </div>
    <input type="button" class="btn cancel" onclick="closeForm()" value="Close"/>

    </form>
    </div>
 <script>
  function openForm() {
    document.getElementById("myForm").style.display = "block";
  }

  function closeForm() {
    document.getElementById("myForm").style.display = "none";
  }
</script>

 </body>
 </html>
</code>```

答: A great example which covers my request is found here : https://www.baeldung.com/spring-boot-crud-thymeleaf</p>

Body:
Trying to learn Java Spring by creating a simple project for storing football teams.
I am storing data to a database using JPA.
Currently i can save a "Team" to my database with my logged in user.
Now i wish to update the record for cases where team is changed or user makes mistake etc.

Can someone help me and provide the best approach?

1 Team Model class

@Data
@Entity
@Table(name="User_Team")
public class Team implements Serializable {

@OneToOne
private User user;

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;

@NotBlank(message="Team Name is required")
private  String teamName;

@NotBlank(message="Location is required")
private  String location;

@NotBlank(message="Nickname required")
private String nickName;

private String yearEstablished;

public Sport sport;

private Divison divison;

  }

2. Team Repository

@Repository
public interface TeamRepository extends CrudRepository<Team, Long> {
Team findAllById(Long id);

   }

3. Team Controller

@Slf4j
@Controller
@RequestMapping("/team")
@SessionAttributes("Team")

public class TeamController {

private TeamRepository teamRepository;

public TeamController(TeamRepository teamRepository) {
    this.teamRepository = teamRepository;
}

@Autowired
TeamRepository service;

@PostMapping
public String processOrder(@Valid Team team, Errors errors,
                           SessionStatus sessionStatus,
                           @AuthenticationPrincipal User user) {

    if (errors.hasErrors()) {
        return "team";
    }

    team.setUser(user);

    service.save(team);
    sessionStatus.setComplete();

    return "redirect:/team";
}

   @GetMapping
    public String displayTeam(Model model) {

      model.addAttribute("team", service.findAll());

    return "/team";
  }
  }

4. Team Html

 <!DOCTYPE html>

 <title>Team</title>
 <link rel="stylesheet" th:href="@{/styles.css}" />

Team

<button class="tablinks">Team Info</button>
<button class="tablinks">Players Info</button>
<button class="tablinks">Fixtures</button>

Home

Team Info

Player Info

        Team name
        Location
        Nickname
        Year Formed
        Sport
        Division

 <button class="open-button" onclick="openForm()">Add your team</button>

 <form method="POST" th:action="@{/team}" class="form-container" id="aboutForm">
    Team name:
    <input type="text" name="teamName"/>

    Location:
    <input type="text" name="location"/>

    Nickname:
    <input type="text" name="nickName"/>

    Year Formed:
    <input type="text" name="yearEstablished"/>

    Sport:
    <select name="sport">
        <option th:each="colorOpt : ${T(sportsapp.sportsapp.Sport).values()}"
                th:value="${colorOpt}" th:text="${colorOpt.displayName}"></option>
    </select>

    Divison:
    <select name="divison">
        <option th:each="colorOpt : ${T(sportsapp.sportsapp.Divison).values()}"
                th:value="${colorOpt}" th:text="${colorOpt.displayValue}"></option>
    </select>

        <input type="submit" value="Add"/>

    <input type="button" class="btn cancel" onclick="closeForm()" value="Close"/>

    </form>


问:
Setting property to newly alloc'd object using accessor cause memory leak
I just want confirmation on whether or not the following causes a memory leak.

.h file

```<code>@property (nonatomic, retain) MyObject *foo;
</code>```

.m file

```<code>@synthesize foo;
...

self.foo = [[MyObject alloc] init];
</code>```

dealloc is setup as

```<code>[foo release];
</code>```

My understanding is that the implementation of the auto-generated accessor method looks like

```<code>-(void)setFoo:(MyObject *)newObject {
    if (foo != newObject) {
        [foo release];
        foo = [newObject retain];
    }
}
</code>```

Walking through self.foo = [[MyObject alloc] init]; now reads to me as, "allocated a new MyObject object whose retain count will be 1, pass it to setFoo:, foo will never be equal to myObject as it was newly allocated, so release the old value, increment the retain count of newObject making it 2 and assign it to foo"

dealloc releases foo therefore setting its retain count to 1, which means this object is leaked?

To do this safely we should write our code like

```<code>self.foo = [[[MyObject alloc] init] autorelease];
</code>```

Is my understanding correct?

EDIT

I realize this question is not really appropriate for SO, so feel free to point me to a better place to ask this type of question as well.

答: Yes, that is absolutely correct.</p>

Body:
I just want confirmation on whether or not the following causes a memory leak.

.h file

@property (nonatomic, retain) MyObject *foo;

.m file

@synthesize foo;
...

self.foo = [[MyObject alloc] init];

dealloc is setup as

[foo release];

My understanding is that the implementation of the auto-generated accessor method looks like

-(void)setFoo:(MyObject *)newObject {
    if (foo != newObject) {
        [foo release];
        foo = [newObject retain];
    }
}

Walking through self.foo = [[MyObject alloc] init]; now reads to me as, "allocated a new MyObject object whose retain count will be 1, pass it to setFoo:, foo will never be equal to myObject as it was newly allocated, so release the old value, increment the retain count of newObject making it 2 and assign it to foo"

dealloc releases foo therefore setting its retain count to 1, which means this object is leaked?

To do this safely we should write our code like

self.foo = [[[MyObject alloc] init] autorelease];

Is my understanding correct?

EDIT

I realize this question is not really appropriate for SO, so feel free to point me to a better place to ask this type of question as well.

Body: Yes, that is absolutely correct.


问:
Loop not going further
I'm pretty new to VBA and programming in general.
This is what I'm trying to do:

I have a database starting on row 21 of my worksheet (storing a name, second name, job). I'm trying to use a for loop, to create a new worksheet for every name in the database - for example (1 - William), (2 - John) ...

When we add a new member to our database and run our macro - It should add the a new sheet (but don't change anything to the existing ones), so with other words just skip (1 - William) and (2 - John) but adds (3 - Kera).

So far it's creating the 2 first worksheets, but when I add someone to my database - the new worksheet isn't added.

Could any of you experts help me with this issue, and brake down what I'm doing wrong?

```<code>Sub test()
Dim i As Long, LastRow As Long
LastRow = Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row

Dim blnFound As Boolean
blnFound = False

For i = 21 To LastRow

For x = 1 To Worksheets.Count
    If Worksheets(x).Name = ((i -21) + 1) & " - " & Worksheets("Database").Cells(i, 3).Value Then
        blnFound = True
    End If
Next

    If blnFound = False Then
        Worksheets.Add.Move After:=Sheets(1)
        ActiveSheet.Name = ((i - 21) + 1) & " - " & Worksheets("Database").Cells(i, 3).Value
    End If

Next i

End Sub
</code>```

答:
I hope you this will help you:</p>

```<code>Sub CreateNewSheetFromRange()

    Dim mySht As Worksheet
    Dim mySheet As Worksheet
    Dim BeginRow As Long
    Dim myStr As String

    Dim r As New Collection
    Dim Pos As Integer
    On Error Resume Next
    For a = 1 To Sheets.Count

        'To List Your Sheet With Name Begin With Number & " - "
        'If you don't care how many time time the same value repeat,
        'you can disobey this for loop
        Pos = InStr(Sheets(a).Name, " - ")
        If Pos > 0 Then
           r.Add Sheets(a).Name, Mid(Sheets(a).Name, Pos + 3)
        End If
        On Error GoTo 0

    Next

    BeginRow = 21

    Do While True
       On Error Resume Next
       myStr = ((BeginRow - 21) + 1) & " - " & Worksheets("Data").Cells(BeginRow, 3).Value

       If Worksheets("Data").Cells(BeginRow, 3).Value = "" Then
          Exit Do
       End If

       'If you hope avoid your repeated cells value to create new sheet
       'perform this
       myVal = r.Item(Worksheets("Data").Cells(BeginRow, 3).Value)
       'If you don't care about repeated value, you change this with:
       'set mySht=worksheets(myStr)

       If Err.Description <> "" Then
          On Error GoTo 0
          Set mySheet = Sheets.Add(After:=Sheets(Sheets.Count))
          'If you don't care about repeated value, remove this r.add
           r.Add myStr, Worksheets("Data").Cells(BeginRow, 3).Value
          mySheet.Name = myStr
          a = 1
       End If

       BeginRow = BeginRow + 1
    Loop
End Sub
</code>```

Title: Loop not going further

Body:
I'm pretty new to VBA and programming in general.
This is what I'm trying to do:

I have a database starting on row 21 of my worksheet (storing a name, second name, job). I'm trying to use a for loop, to create a new worksheet for every name in the database - for example (1 - William), (2 - John) ...

When we add a new member to our database and run our macro - It should add the a new sheet (but don't change anything to the existing ones), so with other words just skip (1 - William) and (2 - John) but adds (3 - Kera).

So far it's creating the 2 first worksheets, but when I add someone to my database - the new worksheet isn't added.

Could any of you experts help me with this issue, and brake down what I'm doing wrong?

Sub test()
Dim i As Long, LastRow As Long
LastRow = Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row

Dim blnFound As Boolean
blnFound = False

For i = 21 To LastRow

For x = 1 To Worksheets.Count
    If Worksheets(x).Name = ((i -21) + 1) & " - " & Worksheets("Database").Cells(i, 3).Value Then
        blnFound = True
    End If
Next

    If blnFound = False Then
        Worksheets.Add.Move After:=Sheets(1)
        ActiveSheet.Name = ((i - 21) + 1) & " - " & Worksheets("Database").Cells(i, 3).Value
    End If

Next i

End Sub

Body:
I hope you this will help you:

Sub CreateNewSheetFromRange()

    Dim mySht As Worksheet
    Dim mySheet As Worksheet
    Dim BeginRow As Long
    Dim myStr As String

    Dim r As New Collection
    Dim Pos As Integer
    On Error Resume Next
    For a = 1 To Sheets.Count

        'To List Your Sheet With Name Begin With Number & " - "
        'If you don't care how many time time the same value repeat,
        'you can disobey this for loop
        Pos = InStr(Sheets(a).Name, " - ")
        If Pos > 0 Then
           r.Add Sheets(a).Name, Mid(Sheets(a).Name, Pos + 3)
        End If
        On Error GoTo 0

    Next

    BeginRow = 21

    Do While True
       On Error Resume Next
       myStr = ((BeginRow - 21) + 1) & " - " & Worksheets("Data").Cells(BeginRow, 3).Value

       If Worksheets("Data").Cells(BeginRow, 3).Value = "" Then
          Exit Do
       End If

       'If you hope avoid your repeated cells value to create new sheet
       'perform this
       myVal = r.Item(Worksheets("Data").Cells(BeginRow, 3).Value)
       'If you don't care about repeated value, you change this with:
       'set mySht=worksheets(myStr)

       If Err.Description <> "" Then
          On Error GoTo 0
          Set mySheet = Sheets.Add(After:=Sheets(Sheets.Count))
          'If you don't care about repeated value, remove this r.add
           r.Add myStr, Worksheets("Data").Cells(BeginRow, 3).Value
          mySheet.Name = myStr
          a = 1
       End If

       BeginRow = BeginRow + 1
    Loop
End Sub


问:
Returning Boolean value error when traversing a list
I am trying to find if a list is a strictly increasing sequenced if 1 and only 1 element from it is removed.  This works for some lists but does not work for others when there isn't any apparent difference between the lists.  And for large lists, it exceeds the execution time limit.  This is my code:

```<code>def almostIncreasingSequence(sequence):

    for i in range(len(sequence)):
        new_seq = sequence.copy()
        del new_seq[i]

        if all(i < j for i, j in zip(new_seq, new_seq[1:])):
            output = True
        else:
            output = False

    return output
</code>```

I'm creating a copy of the input list.  Then, I'm removing the element i and then returning True or False depending on whether the list is a strictly increasing sequence.  I am creating the copy of the list inside the for-loop to make sure that I am removing only one element.  These are some of the test runs where the code does not return the appropriate value:

```<code>Input:
sequence: [10, 1, 2, 3, 4, 5]
Output: false
Expected Output: true

Input:
sequence: [1, 2, 5, 3, 5]
Output: false
Expected Output: true
</code>```

And in this test case, the code exceeds the execution time limit:

```<code>Input:
sequence: [-9996, -9995, -9994, -9993, -9991, -9989, -9987, -9986, -9985, -9983, -9982, -9980, -9978, -9977, -9976, -9975, -9974, -9972, -9968, -9966, -9965, -9961, -9957, -9956, -9955, -9954, -9952, -9948, -9942, -9939, -9938, -9936, -9935, -9932, -9931, -9927, -9925, -9923, -9922, -9921, -9920, -9919, -9918, -9908, -9905, -9902, -9901, -9900, -9899, -9897, -9896, -9894, -9888, -9886, -9880, -9878, -9877, -9876, -9874, -9872, -9871, -9870, -9869, -9868, -9867, -9865, -9857, -9856, -9855, -9854, -9853, -9852, -9851, -9849, -9848, -9846, -9845, -9843, -9842, -9841, -9840, -9837, -9834, -9828, -9826, -9824, -9823, -9820, -9816, -9814, -9812, -9811, -9810, -9809, -9807, -9806, -9804, -9803, -9801, -9800]
Output: undefined
Expected Output: false
</code>```

答:
You are returning the value of the last check, i.e. when you remove the last item in the list. Change it to return True in the first match or False if nothing matched

```<code>def almostIncreasingSequence(sequence):

    for i in range(len(sequence)):
        new_seq = sequence.copy()
        del new_seq[i]

        if all(i < j for i, j in zip(new_seq, new_seq[1:])):
            return True

    return False
</code>```

Body:
I am trying to find if a list is a strictly increasing sequenced if 1 and only 1 element from it is removed.  This works for some lists but does not work for others when there isn't any apparent difference between the lists.  And for large lists, it exceeds the execution time limit.  This is my code:

def almostIncreasingSequence(sequence):

    for i in range(len(sequence)):
        new_seq = sequence.copy()
        del new_seq[i]

        if all(i < j for i, j in zip(new_seq, new_seq[1:])):
            output = True
        else:
            output = False

    return output

I'm creating a copy of the input list.  Then, I'm removing the element i and then returning True or False depending on whether the list is a strictly increasing sequence.  I am creating the copy of the list inside the for-loop to make sure that I am removing only one element.  These are some of the test runs where the code does not return the appropriate value:

Input:
sequence: [10, 1, 2, 3, 4, 5]
Output: false
Expected Output: true

Input:
sequence: [1, 2, 5, 3, 5]
Output: false
Expected Output: true

And in this test case, the code exceeds the execution time limit:

Input:
sequence: [-9996, -9995, -9994, -9993, -9991, -9989, -9987, -9986, -9985, -9983, -9982, -9980, -9978, -9977, -9976, -9975, -9974, -9972, -9968, -9966, -9965, -9961, -9957, -9956, -9955, -9954, -9952, -9948, -9942, -9939, -9938, -9936, -9935, -9932, -9931, -9927, -9925, -9923, -9922, -9921, -9920, -9919, -9918, -9908, -9905, -9902, -9901, -9900, -9899, -9897, -9896, -9894, -9888, -9886, -9880, -9878, -9877, -9876, -9874, -9872, -9871, -9870, -9869, -9868, -9867, -9865, -9857, -9856, -9855, -9854, -9853, -9852, -9851, -9849, -9848, -9846, -9845, -9843, -9842, -9841, -9840, -9837, -9834, -9828, -9826, -9824, -9823, -9820, -9816, -9814, -9812, -9811, -9810, -9809, -9807, -9806, -9804, -9803, -9801, -9800]
Output: undefined
Expected Output: false

Body:
You are returning the value of the last check, i.e. when you remove the last item in the list. Change it to return True in the first match or False if nothing matched

def almostIncreasingSequence(sequence):

    for i in range(len(sequence)):
        new_seq = sequence.copy()
        del new_seq[i]

        if all(i < j for i, j in zip(new_seq, new_seq[1:])):
            return True

    return False


问:
Do you need to use keyboard shortcuts to comply with WCAG 2.1 AA?
I have been reading all the guidelines and I am slightly confused. Do all links on then navigation bar need to have a keyboard shortcut in order to comply with WCAG 2.1 AA?  The guidelines seem to mention more what how to comply if you use them but doesn't state you have to use them so I am confused.

Thanks in advance.

答: You need to make sure that default system behavior of keyboard shortcuts is not overridden by your website/application. If you do override the shortcut key, you need to let the user know of it and provide a mechanism to change those shortcut keys to user choice. </p>


问:
Use "arp -a" to retreive MAC address of corresponding IP Adress
I was trying to convert the MAC address of my phone to it's IP address.

```<code>var arpStream = ExecuteCommandLine("arp", "-a");
List<string> result = new List<string>();
   while (!arpStream.EndOfStream)
  {
      var line = arpStream.ReadLine().Trim();
      result.Add(line);
  }
</code>```

Using the above code, I store it in a list in the following form:

```<code>  192.168.137.1         2e-bb-58-0a-2f-34     dynamic
  192.168.137.44        a8-3e-0e-61-3f-db     dynamic
  192.168.137.91        d4-63-c6-b2-ac-38     dynamic
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.252           01-00-5e-00-00-fc     static
</code>```

What I can't figure out is, how to retrieve a specific IP for the given MAC.
Assume that my phone is the device with the physical address: a8-3e-0e-61-3f-db, how can I store it's IP as a string somewhere?

答:
```<code>String s = "";
for (int i = 3; i < result.Count(); i++)
{
                s = Convert.ToString(result[i]);
                if (s.Contains(macAddress))
                {
                    break;
                }
}
char[] ip = new char[15];
StringBuilder ipaddr = new StringBuilder();
for (int i = 0; s[i].CompareTo(' ') != 0; i++)
{
                ipaddr.Append(s[i]);
}
return ipaddr;
</code>```

I used each entry in the result list as a string and looked for my MAC as a substring inside all of the entries.

Body:
I was trying to convert the MAC address of my phone to it's IP address.

var arpStream = ExecuteCommandLine("arp", "-a");
List<string> result = new List<string>();
   while (!arpStream.EndOfStream)
  {
      var line = arpStream.ReadLine().Trim();
      result.Add(line);
  }

Using the above code, I store it in a list in the following form:

  192.168.137.1         2e-bb-58-0a-2f-34     dynamic
  192.168.137.44        a8-3e-0e-61-3f-db     dynamic
  192.168.137.91        d4-63-c6-b2-ac-38     dynamic
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.252           01-00-5e-00-00-fc     static

What I can't figure out is, how to retrieve a specific IP for the given MAC.
Assume that my phone is the device with the physical address: a8-3e-0e-61-3f-db, how can I store it's IP as a string somewhere?

Body:
String s = "";
for (int i = 3; i < result.Count(); i++)
{
                s = Convert.ToString(result[i]);
                if (s.Contains(macAddress))
                {
                    break;
                }
}
char[] ip = new char[15];
StringBuilder ipaddr = new StringBuilder();
for (int i = 0; s[i].CompareTo(' ') != 0; i++)
{
                ipaddr.Append(s[i]);
}
return ipaddr;

I used each entry in the result list as a string and looked for my MAC as a substring inside all of the entries.


问:
How to fail setup in Locust?
I'm doing a verification in my Locust setup and if that fails, I would like locust to exit immediately.

To do that, I'm raising an exception, but locust continues with the tests until time limit is reached.

I'd like for it to not even start the tests if setup fails. Is there a way to do that?

Locust code

```<code>class MyLocust(Locust):
    task_set = MyTaskSet

    def setup(self):
        if True:
            raise ValueError('Setup failed')
</code>```

stdout / stderr:

locust -f MyTest.py --no-web -c 10 -r 10 -t 5s

INFO/locust.main: Run time limit set to 5 seconds
INFO/locust.main: Starting Locust 0.11.0
INFO/locust.runners: Hatching and swarming 10 clients at the rate 10 clients/s...
    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

ERROR/stderr: Traceback (most recent call last):
ERROR/stderr:
ERROR/stderr: File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/runners.py", line 114, in start_locust
    locust().run(runner=self)
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/core.py", line 192, in __init__
    super(HttpLocust, self).__init__()
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/core.py", line 143, in __init__
    self.setup()
ERROR/stderr:
ERROR/stderr: File "/MyTest.py", line 220, in setup
    raise ValueError('Setup failed')
ERROR/stderr:
ERROR/stderr: ValueError: Setup failed
ERROR/stderr:
ERROR/stderr: 2019-09-25T21:43:39Z
ERROR/stderr:
ERROR/stderr: <Greenlet at 0x12c8c2950: start_locust(<class 'MyTest.LoadTest'>)> failed with ValueError
INFO/locust.runners: All locusts hatched: LoadTest: 10
    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

INFO/locust.main: Time limit reached. Stopping Locust.
INFO/locust.main: Shutting down (exit code 0), bye.
INFO/locust.main: Cleaning up runner...
INFO/locust.main: Running teardowns...
```

As you can see from ^ only exits when time limit is reached, even though setup failed.

答:
If you want stop single locust,use below code. locust.exceptions will help for stop single locust operation.

```<code>from locust.exception import StopLocust

class MyLocust(Locust):
    task_set = MyTaskSet

    def setup(self):
        if True:
            raise StopLocust()
</code>```

If you want stop all locust,use below code.

```<code>from locust.main import runners

class MyLocust(Locust):
        task_set = MyTaskSet

        def setup(self):
            if True:
                raise runners.locust_runner.quit()
</code>```

Title: How to fail setup in Locust?

Body:
I'm doing a verification in my Locust setup and if that fails, I would like locust to exit immediately.

To do that, I'm raising an exception, but locust continues with the tests until time limit is reached.

I'd like for it to not even start the tests if setup fails. Is there a way to do that?

Locust code

class MyLocust(Locust):
    task_set = MyTaskSet

    def setup(self):
        if True:
            raise ValueError('Setup failed')

stdout / stderr:

locust -f MyTest.py --no-web -c 10 -r 10 -t 5s

INFO/locust.main: Run time limit set to 5 seconds
INFO/locust.main: Starting Locust 0.11.0
INFO/locust.runners: Hatching and swarming 10 clients at the rate 10 clients/s...
    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

ERROR/stderr: Traceback (most recent call last):
ERROR/stderr:
ERROR/stderr: File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/runners.py", line 114, in start_locust
    locust().run(runner=self)
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/core.py", line 192, in __init__
    super(HttpLocust, self).__init__()
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/core.py", line 143, in __init__
    self.setup()
ERROR/stderr:
ERROR/stderr: File "/MyTest.py", line 220, in setup
    raise ValueError('Setup failed')
ERROR/stderr:
ERROR/stderr: ValueError: Setup failed
ERROR/stderr:
ERROR/stderr: 2019-09-25T21:43:39Z
ERROR/stderr:
ERROR/stderr: <Greenlet at 0x12c8c2950: start_locust(<class 'MyTest.LoadTest'>)> failed with ValueError
INFO/locust.runners: All locusts hatched: LoadTest: 10
    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

INFO/locust.main: Time limit reached. Stopping Locust.
INFO/locust.main: Shutting down (exit code 0), bye.
INFO/locust.main: Cleaning up runner...
INFO/locust.main: Running teardowns...

As you can see from ^ only exits when time limit is reached, even though setup failed.

Body:
If you want stop single locust,use below code. locust.exceptions will help for stop single locust operation.

from locust.exception import StopLocust

class MyLocust(Locust):
    task_set = MyTaskSet

    def setup(self):
        if True:
            raise StopLocust()

If you want stop all locust,use below code.

from locust.main import runners

class MyLocust(Locust):
        task_set = MyTaskSet

        def setup(self):
            if True:
                raise runners.locust_runner.quit()


问:
How to call another function's results
```<code>def most_frequency_occ(chars,inputString):
    count = 0
    for ind_char in inputString:
        ind_char = ind_char.lower()
        if chars == ind_char:
             count += 1
    return count

def general(inputString):
    maxOccurences = 0
    for chars in inputString:
        most_frequency_occ(chars, inputString)
</code>```

This is my current code. I'm trying to find the most frequent occurring letter in general. I created another function called most_frequency_occ that finds a specific character in the string that occurs the most often, but how do I generalize it into finding the frequent letter in a string without specifying a specific character and only using loops, without any build in string functions either.

For example:

```<code>print(general('aqweasdaza'))
</code>```

should print 4 as "a" occurs the most frequently, occurring 4 times.

答:
There are multiple ways you find the most common letter in a string.

One easy to understand and cross-language way of doing this would be:

initialize an array of 26 integers set to 0.

go over each letter one by one of your string, if the first letter is an B (B=2), you can increment the second value of the array

Find the largest value in your array, return the corresponding letter.

Since you are using python, you could use dictionaries since it would be less work to implement.

A word of caution, it sounds like you are doing a school assignment. If your school has a plagiarism checker that checks the internet, you might be caught for academic dishonesty if you copy paste code from the internet.

Title: How to call another function's results

Body:
def most_frequency_occ(chars,inputString):
    count = 0
    for ind_char in inputString:
        ind_char = ind_char.lower()
        if chars == ind_char:
             count += 1
    return count

def general(inputString):
    maxOccurences = 0
    for chars in inputString:
        most_frequency_occ(chars, inputString)

This is my current code. I'm trying to find the most frequent occurring letter in general. I created another function called most_frequency_occ that finds a specific character in the string that occurs the most often, but how do I generalize it into finding the frequent letter in a string without specifying a specific character and only using loops, without any build in string functions either.

For example:

print(general('aqweasdaza'))

should print 4 as "a" occurs the most frequently, occurring 4 times.