qid
int64 469
74.7M
| question
stringlengths 36
37.8k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 5
31.5k
| response_k
stringlengths 10
31.6k
|
---|---|---|---|---|---|
7,728,977 | I am trying to add a Chinese language to my application written in Django and I have a really hard time with that. I have spent half a day trying different approaches, no success.
My application supports few languages, this is part of **settings.py** file:
```
TIME_ZONE = 'Europe/Dublin'
LANGUAGE_CODE = 'en'
LOCALES = (
#English
('en', u'English'),
#Norwegian
('no', u'Norsk'),
#Finish
('fi', u'Suomi'),
#Simplified Chinese
('zh-CN', u'简体中文'),
#Traditional Chinese
('zh-TW', u'繁體中文'),
#Japanese
('ja', u'日本語'),
)
```
At the moment all (but Chinese) languages work perfectly. This is a content of **locale directory**:
```
$ ls locale/
en
fi
ja
no
zh_CN
zh_TW
```
In every directory I have LC\_MESSAGES directory with \*.mo and \*.po files.
\*.po files are created by script written in Python, which converts \*.ODS to a text file.
\*.mo files are created by **python manage.py compilemessages** command.
Language can be selected by user from the proper form in "Preferences" section in my application.
Django does not load Chinese translation. That is the problem. Both simplified and traditional does not work. I have tried different variations of language and locale codes in settings.py and in locale directory: zh-CN, zh-cn, zh\_CN, zh\_cn. No success.
Perhaps I made a simple mistake? I have added Polish language just for test and everything went fine. Basically I did the same. I have added ('pl', u'Polish') tuple to the settings.py and "locale/pl" with \*.po and \*.mo and LC\_MESSAGES directory...
Do you know what might be wrong? | 2011/10/11 | [
"https://Stackoverflow.com/questions/7728977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989862/"
] | You will need to use lower case for your locale language codes for it to work properly. i.e. use
```
LANGUAGES = (
('zh-cn', u'简体中文'), # instead of 'zh-CN'
('zh-tw', u'繁體中文'), # instead of 'zh-TW'
)
```
See the language codes specified in <https://code.djangoproject.com/browser/django/trunk/django/conf/global_settings.py>. You will see that it uses `zh-tw` instead of `zh-TW`.
Finally, the language directories storing the \*.po and \*.mo files in your locales folder needs to be named `zh_CN` and `zh_TW` respectively for the translations to work properly. | I had the same problem [Django-1.6.1] and solved it by renaming the locale directories for Chinese from zh-cn (or zh\_cn) to zh\_CN (underscore and uppercase CN).
Strangely enough Django requires a "zh-cn" as LANGUAGE\_CODE or url with an i18n\_pattern respectively.
Non-documented goodness btw.
Hope that helps. |
7,728,977 | I am trying to add a Chinese language to my application written in Django and I have a really hard time with that. I have spent half a day trying different approaches, no success.
My application supports few languages, this is part of **settings.py** file:
```
TIME_ZONE = 'Europe/Dublin'
LANGUAGE_CODE = 'en'
LOCALES = (
#English
('en', u'English'),
#Norwegian
('no', u'Norsk'),
#Finish
('fi', u'Suomi'),
#Simplified Chinese
('zh-CN', u'简体中文'),
#Traditional Chinese
('zh-TW', u'繁體中文'),
#Japanese
('ja', u'日本語'),
)
```
At the moment all (but Chinese) languages work perfectly. This is a content of **locale directory**:
```
$ ls locale/
en
fi
ja
no
zh_CN
zh_TW
```
In every directory I have LC\_MESSAGES directory with \*.mo and \*.po files.
\*.po files are created by script written in Python, which converts \*.ODS to a text file.
\*.mo files are created by **python manage.py compilemessages** command.
Language can be selected by user from the proper form in "Preferences" section in my application.
Django does not load Chinese translation. That is the problem. Both simplified and traditional does not work. I have tried different variations of language and locale codes in settings.py and in locale directory: zh-CN, zh-cn, zh\_CN, zh\_cn. No success.
Perhaps I made a simple mistake? I have added Polish language just for test and everything went fine. Basically I did the same. I have added ('pl', u'Polish') tuple to the settings.py and "locale/pl" with \*.po and \*.mo and LC\_MESSAGES directory...
Do you know what might be wrong? | 2011/10/11 | [
"https://Stackoverflow.com/questions/7728977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989862/"
] | You will need to use lower case for your locale language codes for it to work properly. i.e. use
```
LANGUAGES = (
('zh-cn', u'简体中文'), # instead of 'zh-CN'
('zh-tw', u'繁體中文'), # instead of 'zh-TW'
)
```
See the language codes specified in <https://code.djangoproject.com/browser/django/trunk/django/conf/global_settings.py>. You will see that it uses `zh-tw` instead of `zh-TW`.
Finally, the language directories storing the \*.po and \*.mo files in your locales folder needs to be named `zh_CN` and `zh_TW` respectively for the translations to work properly. | In .po file, add zh-cn or zh-tw in "Language: \n", which becomes "Language: zh-en\n" or "Language: zh-tw\n"
Compile the messages and runserver again. |
7,728,977 | I am trying to add a Chinese language to my application written in Django and I have a really hard time with that. I have spent half a day trying different approaches, no success.
My application supports few languages, this is part of **settings.py** file:
```
TIME_ZONE = 'Europe/Dublin'
LANGUAGE_CODE = 'en'
LOCALES = (
#English
('en', u'English'),
#Norwegian
('no', u'Norsk'),
#Finish
('fi', u'Suomi'),
#Simplified Chinese
('zh-CN', u'简体中文'),
#Traditional Chinese
('zh-TW', u'繁體中文'),
#Japanese
('ja', u'日本語'),
)
```
At the moment all (but Chinese) languages work perfectly. This is a content of **locale directory**:
```
$ ls locale/
en
fi
ja
no
zh_CN
zh_TW
```
In every directory I have LC\_MESSAGES directory with \*.mo and \*.po files.
\*.po files are created by script written in Python, which converts \*.ODS to a text file.
\*.mo files are created by **python manage.py compilemessages** command.
Language can be selected by user from the proper form in "Preferences" section in my application.
Django does not load Chinese translation. That is the problem. Both simplified and traditional does not work. I have tried different variations of language and locale codes in settings.py and in locale directory: zh-CN, zh-cn, zh\_CN, zh\_cn. No success.
Perhaps I made a simple mistake? I have added Polish language just for test and everything went fine. Basically I did the same. I have added ('pl', u'Polish') tuple to the settings.py and "locale/pl" with \*.po and \*.mo and LC\_MESSAGES directory...
Do you know what might be wrong? | 2011/10/11 | [
"https://Stackoverflow.com/questions/7728977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989862/"
] | I had the same problem [Django-1.6.1] and solved it by renaming the locale directories for Chinese from zh-cn (or zh\_cn) to zh\_CN (underscore and uppercase CN).
Strangely enough Django requires a "zh-cn" as LANGUAGE\_CODE or url with an i18n\_pattern respectively.
Non-documented goodness btw.
Hope that helps. | Not sure if you were able to resolve this later, but the problem is with the language directory names in the locale directory. This happens with all languages with a dash in their short-code. The solution is to rename the Chinese directories by replacing the dashes with underscores:
zh-cn --> zh\_cn
zh-tw --> zh\_tw
Hope this helps. |
7,728,977 | I am trying to add a Chinese language to my application written in Django and I have a really hard time with that. I have spent half a day trying different approaches, no success.
My application supports few languages, this is part of **settings.py** file:
```
TIME_ZONE = 'Europe/Dublin'
LANGUAGE_CODE = 'en'
LOCALES = (
#English
('en', u'English'),
#Norwegian
('no', u'Norsk'),
#Finish
('fi', u'Suomi'),
#Simplified Chinese
('zh-CN', u'简体中文'),
#Traditional Chinese
('zh-TW', u'繁體中文'),
#Japanese
('ja', u'日本語'),
)
```
At the moment all (but Chinese) languages work perfectly. This is a content of **locale directory**:
```
$ ls locale/
en
fi
ja
no
zh_CN
zh_TW
```
In every directory I have LC\_MESSAGES directory with \*.mo and \*.po files.
\*.po files are created by script written in Python, which converts \*.ODS to a text file.
\*.mo files are created by **python manage.py compilemessages** command.
Language can be selected by user from the proper form in "Preferences" section in my application.
Django does not load Chinese translation. That is the problem. Both simplified and traditional does not work. I have tried different variations of language and locale codes in settings.py and in locale directory: zh-CN, zh-cn, zh\_CN, zh\_cn. No success.
Perhaps I made a simple mistake? I have added Polish language just for test and everything went fine. Basically I did the same. I have added ('pl', u'Polish') tuple to the settings.py and "locale/pl" with \*.po and \*.mo and LC\_MESSAGES directory...
Do you know what might be wrong? | 2011/10/11 | [
"https://Stackoverflow.com/questions/7728977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989862/"
] | For Django 1.7 and up, you'll need to do the following:
`zh-hans` in your config, and make sure that your directory is named `zh_Hans`.
And for traditional Chinese:
`zh-hant` in your config, and your directory should be named `zh_Hant`.
Here is an example of how the `auth` contributor package lays out its translations in the locale directory: <https://github.com/django/django/tree/master/django/contrib/auth/locale>
Basically, for our Chinese language codes, the `-` is replaced with a `_`, and the first letter of the second work is capitalized.
Source code for this logic is here: [https://github.com/django/django/blob/7a42cfcfdc94c1e7cd653f3140b9eb30492bae4f/django/utils/translation/**init**.py#L272-L285](https://github.com/django/django/blob/7a42cfcfdc94c1e7cd653f3140b9eb30492bae4f/django/utils/translation/__init__.py#L272-L285)
and just to be thorough, here is the method:
```
def to_locale(language, to_lower=False):
"""
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
True, the last component is lower-cased (en_us).
"""
p = language.find('-')
if p >= 0:
if to_lower:
return language[:p].lower() + '_' + language[p + 1:].lower()
else:
# Get correct locale for sr-latn
if len(language[p + 1:]) > 2:
return language[:p].lower() + '_' + language[p + 1].upper() + language[p + 2:].lower()
return language[:p].lower() + '_' + language[p + 1:].upper()
else:
return language.lower()
```
Note that `en-us` is turned into `en_US`, based on the source code above, because `us` is 2 characters or less. | Not sure if you were able to resolve this later, but the problem is with the language directory names in the locale directory. This happens with all languages with a dash in their short-code. The solution is to rename the Chinese directories by replacing the dashes with underscores:
zh-cn --> zh\_cn
zh-tw --> zh\_tw
Hope this helps. |
7,728,977 | I am trying to add a Chinese language to my application written in Django and I have a really hard time with that. I have spent half a day trying different approaches, no success.
My application supports few languages, this is part of **settings.py** file:
```
TIME_ZONE = 'Europe/Dublin'
LANGUAGE_CODE = 'en'
LOCALES = (
#English
('en', u'English'),
#Norwegian
('no', u'Norsk'),
#Finish
('fi', u'Suomi'),
#Simplified Chinese
('zh-CN', u'简体中文'),
#Traditional Chinese
('zh-TW', u'繁體中文'),
#Japanese
('ja', u'日本語'),
)
```
At the moment all (but Chinese) languages work perfectly. This is a content of **locale directory**:
```
$ ls locale/
en
fi
ja
no
zh_CN
zh_TW
```
In every directory I have LC\_MESSAGES directory with \*.mo and \*.po files.
\*.po files are created by script written in Python, which converts \*.ODS to a text file.
\*.mo files are created by **python manage.py compilemessages** command.
Language can be selected by user from the proper form in "Preferences" section in my application.
Django does not load Chinese translation. That is the problem. Both simplified and traditional does not work. I have tried different variations of language and locale codes in settings.py and in locale directory: zh-CN, zh-cn, zh\_CN, zh\_cn. No success.
Perhaps I made a simple mistake? I have added Polish language just for test and everything went fine. Basically I did the same. I have added ('pl', u'Polish') tuple to the settings.py and "locale/pl" with \*.po and \*.mo and LC\_MESSAGES directory...
Do you know what might be wrong? | 2011/10/11 | [
"https://Stackoverflow.com/questions/7728977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989862/"
] | I had the same problem [Django-1.6.1] and solved it by renaming the locale directories for Chinese from zh-cn (or zh\_cn) to zh\_CN (underscore and uppercase CN).
Strangely enough Django requires a "zh-cn" as LANGUAGE\_CODE or url with an i18n\_pattern respectively.
Non-documented goodness btw.
Hope that helps. | In .po file, add zh-cn or zh-tw in "Language: \n", which becomes "Language: zh-en\n" or "Language: zh-tw\n"
Compile the messages and runserver again. |
7,728,977 | I am trying to add a Chinese language to my application written in Django and I have a really hard time with that. I have spent half a day trying different approaches, no success.
My application supports few languages, this is part of **settings.py** file:
```
TIME_ZONE = 'Europe/Dublin'
LANGUAGE_CODE = 'en'
LOCALES = (
#English
('en', u'English'),
#Norwegian
('no', u'Norsk'),
#Finish
('fi', u'Suomi'),
#Simplified Chinese
('zh-CN', u'简体中文'),
#Traditional Chinese
('zh-TW', u'繁體中文'),
#Japanese
('ja', u'日本語'),
)
```
At the moment all (but Chinese) languages work perfectly. This is a content of **locale directory**:
```
$ ls locale/
en
fi
ja
no
zh_CN
zh_TW
```
In every directory I have LC\_MESSAGES directory with \*.mo and \*.po files.
\*.po files are created by script written in Python, which converts \*.ODS to a text file.
\*.mo files are created by **python manage.py compilemessages** command.
Language can be selected by user from the proper form in "Preferences" section in my application.
Django does not load Chinese translation. That is the problem. Both simplified and traditional does not work. I have tried different variations of language and locale codes in settings.py and in locale directory: zh-CN, zh-cn, zh\_CN, zh\_cn. No success.
Perhaps I made a simple mistake? I have added Polish language just for test and everything went fine. Basically I did the same. I have added ('pl', u'Polish') tuple to the settings.py and "locale/pl" with \*.po and \*.mo and LC\_MESSAGES directory...
Do you know what might be wrong? | 2011/10/11 | [
"https://Stackoverflow.com/questions/7728977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989862/"
] | For Django 1.7 and up, you'll need to do the following:
`zh-hans` in your config, and make sure that your directory is named `zh_Hans`.
And for traditional Chinese:
`zh-hant` in your config, and your directory should be named `zh_Hant`.
Here is an example of how the `auth` contributor package lays out its translations in the locale directory: <https://github.com/django/django/tree/master/django/contrib/auth/locale>
Basically, for our Chinese language codes, the `-` is replaced with a `_`, and the first letter of the second work is capitalized.
Source code for this logic is here: [https://github.com/django/django/blob/7a42cfcfdc94c1e7cd653f3140b9eb30492bae4f/django/utils/translation/**init**.py#L272-L285](https://github.com/django/django/blob/7a42cfcfdc94c1e7cd653f3140b9eb30492bae4f/django/utils/translation/__init__.py#L272-L285)
and just to be thorough, here is the method:
```
def to_locale(language, to_lower=False):
"""
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
True, the last component is lower-cased (en_us).
"""
p = language.find('-')
if p >= 0:
if to_lower:
return language[:p].lower() + '_' + language[p + 1:].lower()
else:
# Get correct locale for sr-latn
if len(language[p + 1:]) > 2:
return language[:p].lower() + '_' + language[p + 1].upper() + language[p + 2:].lower()
return language[:p].lower() + '_' + language[p + 1:].upper()
else:
return language.lower()
```
Note that `en-us` is turned into `en_US`, based on the source code above, because `us` is 2 characters or less. | I had the same problem [Django-1.6.1] and solved it by renaming the locale directories for Chinese from zh-cn (or zh\_cn) to zh\_CN (underscore and uppercase CN).
Strangely enough Django requires a "zh-cn" as LANGUAGE\_CODE or url with an i18n\_pattern respectively.
Non-documented goodness btw.
Hope that helps. |
7,728,977 | I am trying to add a Chinese language to my application written in Django and I have a really hard time with that. I have spent half a day trying different approaches, no success.
My application supports few languages, this is part of **settings.py** file:
```
TIME_ZONE = 'Europe/Dublin'
LANGUAGE_CODE = 'en'
LOCALES = (
#English
('en', u'English'),
#Norwegian
('no', u'Norsk'),
#Finish
('fi', u'Suomi'),
#Simplified Chinese
('zh-CN', u'简体中文'),
#Traditional Chinese
('zh-TW', u'繁體中文'),
#Japanese
('ja', u'日本語'),
)
```
At the moment all (but Chinese) languages work perfectly. This is a content of **locale directory**:
```
$ ls locale/
en
fi
ja
no
zh_CN
zh_TW
```
In every directory I have LC\_MESSAGES directory with \*.mo and \*.po files.
\*.po files are created by script written in Python, which converts \*.ODS to a text file.
\*.mo files are created by **python manage.py compilemessages** command.
Language can be selected by user from the proper form in "Preferences" section in my application.
Django does not load Chinese translation. That is the problem. Both simplified and traditional does not work. I have tried different variations of language and locale codes in settings.py and in locale directory: zh-CN, zh-cn, zh\_CN, zh\_cn. No success.
Perhaps I made a simple mistake? I have added Polish language just for test and everything went fine. Basically I did the same. I have added ('pl', u'Polish') tuple to the settings.py and "locale/pl" with \*.po and \*.mo and LC\_MESSAGES directory...
Do you know what might be wrong? | 2011/10/11 | [
"https://Stackoverflow.com/questions/7728977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989862/"
] | For Django 1.7 and up, you'll need to do the following:
`zh-hans` in your config, and make sure that your directory is named `zh_Hans`.
And for traditional Chinese:
`zh-hant` in your config, and your directory should be named `zh_Hant`.
Here is an example of how the `auth` contributor package lays out its translations in the locale directory: <https://github.com/django/django/tree/master/django/contrib/auth/locale>
Basically, for our Chinese language codes, the `-` is replaced with a `_`, and the first letter of the second work is capitalized.
Source code for this logic is here: [https://github.com/django/django/blob/7a42cfcfdc94c1e7cd653f3140b9eb30492bae4f/django/utils/translation/**init**.py#L272-L285](https://github.com/django/django/blob/7a42cfcfdc94c1e7cd653f3140b9eb30492bae4f/django/utils/translation/__init__.py#L272-L285)
and just to be thorough, here is the method:
```
def to_locale(language, to_lower=False):
"""
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
True, the last component is lower-cased (en_us).
"""
p = language.find('-')
if p >= 0:
if to_lower:
return language[:p].lower() + '_' + language[p + 1:].lower()
else:
# Get correct locale for sr-latn
if len(language[p + 1:]) > 2:
return language[:p].lower() + '_' + language[p + 1].upper() + language[p + 2:].lower()
return language[:p].lower() + '_' + language[p + 1:].upper()
else:
return language.lower()
```
Note that `en-us` is turned into `en_US`, based on the source code above, because `us` is 2 characters or less. | In .po file, add zh-cn or zh-tw in "Language: \n", which becomes "Language: zh-en\n" or "Language: zh-tw\n"
Compile the messages and runserver again. |
19,923,838 | I have the following lists:
```
[1,2,3]
[1]
[1,2,3,4]
```
From the above, I would like to generate a list containing:
```
[[1,1,1],[1,1,2],[1,1,3],[1,1,4],
[2,1,1], [2,1,2], [2,1,3], [2,1,4],
[3,1,2], [3,1,3],[3,1,4]]
```
What is this process called?
Generate a factorial of python lists?
Is there a built-in library that does this? | 2013/11/12 | [
"https://Stackoverflow.com/questions/19923838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2982246/"
] | Using [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product):
```
>>> import itertools
>>> [list(xs) for xs in itertools.product([1,2,3], [1], [1,2,3,4])]
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]]
``` | [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product)
```
>>> lists = [[1,2,3], [1], [1,2,3,4]]
>>> from itertools import product
>>> map(list, product(*lists))
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]]
```
Note: the usage of `map` allows me to convert the otherwise tuple results of `product`'s iteration into lists easily. |
19,923,838 | I have the following lists:
```
[1,2,3]
[1]
[1,2,3,4]
```
From the above, I would like to generate a list containing:
```
[[1,1,1],[1,1,2],[1,1,3],[1,1,4],
[2,1,1], [2,1,2], [2,1,3], [2,1,4],
[3,1,2], [3,1,3],[3,1,4]]
```
What is this process called?
Generate a factorial of python lists?
Is there a built-in library that does this? | 2013/11/12 | [
"https://Stackoverflow.com/questions/19923838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2982246/"
] | Using [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product):
```
>>> import itertools
>>> [list(xs) for xs in itertools.product([1,2,3], [1], [1,2,3,4])]
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]]
``` | ```
inputList = [[1,2,3], [1], [1,2,3,4]]
import itertools
print [list(item) for item in itertools.product(*inputList)]
```
**Output**
```
[[1, 1, 1],
[1, 1, 2],
[1, 1, 3],
[1, 1, 4],
[2, 1, 1],
[2, 1, 2],
[2, 1, 3],
[2, 1, 4],
[3, 1, 1],
[3, 1, 2],
[3, 1, 3],
[3, 1, 4]]
``` |
19,923,838 | I have the following lists:
```
[1,2,3]
[1]
[1,2,3,4]
```
From the above, I would like to generate a list containing:
```
[[1,1,1],[1,1,2],[1,1,3],[1,1,4],
[2,1,1], [2,1,2], [2,1,3], [2,1,4],
[3,1,2], [3,1,3],[3,1,4]]
```
What is this process called?
Generate a factorial of python lists?
Is there a built-in library that does this? | 2013/11/12 | [
"https://Stackoverflow.com/questions/19923838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2982246/"
] | Using [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product):
```
>>> import itertools
>>> [list(xs) for xs in itertools.product([1,2,3], [1], [1,2,3,4])]
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]]
``` | As suggested in the other answers `itertools.product` is the way to go here, but for completeness and as an illustration of what `itertools.product` does here is a solution using a list comprehension:
```
result = [[x,y,z] for x in [1,2,3] for y in [1] for z in [1,2,3,4]]
```
Here is the same thing using normal for loops which may make it a bit more readable:
```
result = []
for x in [1,2,3]:
for y in [1]:
for z in [1,2,3,4]:
result.append([x, y, z])
``` |
19,923,838 | I have the following lists:
```
[1,2,3]
[1]
[1,2,3,4]
```
From the above, I would like to generate a list containing:
```
[[1,1,1],[1,1,2],[1,1,3],[1,1,4],
[2,1,1], [2,1,2], [2,1,3], [2,1,4],
[3,1,2], [3,1,3],[3,1,4]]
```
What is this process called?
Generate a factorial of python lists?
Is there a built-in library that does this? | 2013/11/12 | [
"https://Stackoverflow.com/questions/19923838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2982246/"
] | [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product)
```
>>> lists = [[1,2,3], [1], [1,2,3,4]]
>>> from itertools import product
>>> map(list, product(*lists))
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]]
```
Note: the usage of `map` allows me to convert the otherwise tuple results of `product`'s iteration into lists easily. | As suggested in the other answers `itertools.product` is the way to go here, but for completeness and as an illustration of what `itertools.product` does here is a solution using a list comprehension:
```
result = [[x,y,z] for x in [1,2,3] for y in [1] for z in [1,2,3,4]]
```
Here is the same thing using normal for loops which may make it a bit more readable:
```
result = []
for x in [1,2,3]:
for y in [1]:
for z in [1,2,3,4]:
result.append([x, y, z])
``` |
19,923,838 | I have the following lists:
```
[1,2,3]
[1]
[1,2,3,4]
```
From the above, I would like to generate a list containing:
```
[[1,1,1],[1,1,2],[1,1,3],[1,1,4],
[2,1,1], [2,1,2], [2,1,3], [2,1,4],
[3,1,2], [3,1,3],[3,1,4]]
```
What is this process called?
Generate a factorial of python lists?
Is there a built-in library that does this? | 2013/11/12 | [
"https://Stackoverflow.com/questions/19923838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2982246/"
] | ```
inputList = [[1,2,3], [1], [1,2,3,4]]
import itertools
print [list(item) for item in itertools.product(*inputList)]
```
**Output**
```
[[1, 1, 1],
[1, 1, 2],
[1, 1, 3],
[1, 1, 4],
[2, 1, 1],
[2, 1, 2],
[2, 1, 3],
[2, 1, 4],
[3, 1, 1],
[3, 1, 2],
[3, 1, 3],
[3, 1, 4]]
``` | As suggested in the other answers `itertools.product` is the way to go here, but for completeness and as an illustration of what `itertools.product` does here is a solution using a list comprehension:
```
result = [[x,y,z] for x in [1,2,3] for y in [1] for z in [1,2,3,4]]
```
Here is the same thing using normal for loops which may make it a bit more readable:
```
result = []
for x in [1,2,3]:
for y in [1]:
for z in [1,2,3,4]:
result.append([x, y, z])
``` |
1,962,795 | How to detect if a PNG image has transparent alpha channel or not using PIL?
```
img = Image.open('example.png', 'r')
has_alpha = img.mode == 'RGBA'
```
With above code we know whether a PNG image has alpha channel not not but how to get the alpha value?
I didn't find a 'transparency' key in img.info dictionary as described at [PIL's website](http://www.pythonware.com/library/pil/handbook/format-png.htm)
I'm using Ubuntu and zlib1g, zlibc packages are already installed. | 2009/12/26 | [
"https://Stackoverflow.com/questions/1962795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192767/"
] | To get the alpha layer of an RGBA image all you need to do is:
```
red, green, blue, alpha = img.split()
```
or
```
alpha = img.split()[-1]
```
And there is a method to set the alpha layer:
```
img.putalpha(alpha)
```
The transparency key is only used to define the transparency index in the palette mode (P). If you want to cover the palette mode transparency case as well and cover all cases you could do this
```
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
alpha = img.convert('RGBA').split()[-1]
```
Note: The convert method is needed when the image.mode is LA, because of a bug in PIL. | The `img.info` is about the image as a whole -- the alpha-value in an RGBA image is per-pixel, so of course it won't be in `img.info`. The `getpixel` method of the image object, given a coordinate as argument, returns a tuple with the values of the (four, in this case) bands for that pixel -- the tuple's last value will then be A, the alpha value. |
1,962,795 | How to detect if a PNG image has transparent alpha channel or not using PIL?
```
img = Image.open('example.png', 'r')
has_alpha = img.mode == 'RGBA'
```
With above code we know whether a PNG image has alpha channel not not but how to get the alpha value?
I didn't find a 'transparency' key in img.info dictionary as described at [PIL's website](http://www.pythonware.com/library/pil/handbook/format-png.htm)
I'm using Ubuntu and zlib1g, zlibc packages are already installed. | 2009/12/26 | [
"https://Stackoverflow.com/questions/1962795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192767/"
] | You can get the alpha data out of whole image in one go by converting image to string with 'A' mode e.g this example get alpha data out of image and saves it as grey scale image :)
```
from PIL import Image
imFile="white-arrow.png"
im = Image.open(imFile, 'r')
print im.mode == 'RGBA'
rgbData = im.tostring("raw", "RGB")
print len(rgbData)
alphaData = im.tostring("raw", "A")
print len(alphaData)
alphaImage = Image.fromstring("L", im.size, alphaData)
alphaImage.save(imFile+".alpha.png")
``` | The `img.info` is about the image as a whole -- the alpha-value in an RGBA image is per-pixel, so of course it won't be in `img.info`. The `getpixel` method of the image object, given a coordinate as argument, returns a tuple with the values of the (four, in this case) bands for that pixel -- the tuple's last value will then be A, the alpha value. |
1,962,795 | How to detect if a PNG image has transparent alpha channel or not using PIL?
```
img = Image.open('example.png', 'r')
has_alpha = img.mode == 'RGBA'
```
With above code we know whether a PNG image has alpha channel not not but how to get the alpha value?
I didn't find a 'transparency' key in img.info dictionary as described at [PIL's website](http://www.pythonware.com/library/pil/handbook/format-png.htm)
I'm using Ubuntu and zlib1g, zlibc packages are already installed. | 2009/12/26 | [
"https://Stackoverflow.com/questions/1962795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192767/"
] | To get the alpha layer of an RGBA image all you need to do is:
```
red, green, blue, alpha = img.split()
```
or
```
alpha = img.split()[-1]
```
And there is a method to set the alpha layer:
```
img.putalpha(alpha)
```
The transparency key is only used to define the transparency index in the palette mode (P). If you want to cover the palette mode transparency case as well and cover all cases you could do this
```
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
alpha = img.convert('RGBA').split()[-1]
```
Note: The convert method is needed when the image.mode is LA, because of a bug in PIL. | ```
# python 2.6+
import operator, itertools
def get_alpha_channel(image):
"Return the alpha channel as a sequence of values"
# first, which band is the alpha channel?
try:
alpha_index= image.getbands().index('A')
except ValueError:
return None # no alpha channel, presumably
alpha_getter= operator.itemgetter(alpha_index)
return itertools.imap(alpha_getter, image.getdata())
``` |
1,962,795 | How to detect if a PNG image has transparent alpha channel or not using PIL?
```
img = Image.open('example.png', 'r')
has_alpha = img.mode == 'RGBA'
```
With above code we know whether a PNG image has alpha channel not not but how to get the alpha value?
I didn't find a 'transparency' key in img.info dictionary as described at [PIL's website](http://www.pythonware.com/library/pil/handbook/format-png.htm)
I'm using Ubuntu and zlib1g, zlibc packages are already installed. | 2009/12/26 | [
"https://Stackoverflow.com/questions/1962795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192767/"
] | You can get the alpha data out of whole image in one go by converting image to string with 'A' mode e.g this example get alpha data out of image and saves it as grey scale image :)
```
from PIL import Image
imFile="white-arrow.png"
im = Image.open(imFile, 'r')
print im.mode == 'RGBA'
rgbData = im.tostring("raw", "RGB")
print len(rgbData)
alphaData = im.tostring("raw", "A")
print len(alphaData)
alphaImage = Image.fromstring("L", im.size, alphaData)
alphaImage.save(imFile+".alpha.png")
``` | ```
# python 2.6+
import operator, itertools
def get_alpha_channel(image):
"Return the alpha channel as a sequence of values"
# first, which band is the alpha channel?
try:
alpha_index= image.getbands().index('A')
except ValueError:
return None # no alpha channel, presumably
alpha_getter= operator.itemgetter(alpha_index)
return itertools.imap(alpha_getter, image.getdata())
``` |
1,962,795 | How to detect if a PNG image has transparent alpha channel or not using PIL?
```
img = Image.open('example.png', 'r')
has_alpha = img.mode == 'RGBA'
```
With above code we know whether a PNG image has alpha channel not not but how to get the alpha value?
I didn't find a 'transparency' key in img.info dictionary as described at [PIL's website](http://www.pythonware.com/library/pil/handbook/format-png.htm)
I'm using Ubuntu and zlib1g, zlibc packages are already installed. | 2009/12/26 | [
"https://Stackoverflow.com/questions/1962795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192767/"
] | To get the alpha layer of an RGBA image all you need to do is:
```
red, green, blue, alpha = img.split()
```
or
```
alpha = img.split()[-1]
```
And there is a method to set the alpha layer:
```
img.putalpha(alpha)
```
The transparency key is only used to define the transparency index in the palette mode (P). If you want to cover the palette mode transparency case as well and cover all cases you could do this
```
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
alpha = img.convert('RGBA').split()[-1]
```
Note: The convert method is needed when the image.mode is LA, because of a bug in PIL. | You can get the alpha data out of whole image in one go by converting image to string with 'A' mode e.g this example get alpha data out of image and saves it as grey scale image :)
```
from PIL import Image
imFile="white-arrow.png"
im = Image.open(imFile, 'r')
print im.mode == 'RGBA'
rgbData = im.tostring("raw", "RGB")
print len(rgbData)
alphaData = im.tostring("raw", "A")
print len(alphaData)
alphaImage = Image.fromstring("L", im.size, alphaData)
alphaImage.save(imFile+".alpha.png")
``` |
1,962,795 | How to detect if a PNG image has transparent alpha channel or not using PIL?
```
img = Image.open('example.png', 'r')
has_alpha = img.mode == 'RGBA'
```
With above code we know whether a PNG image has alpha channel not not but how to get the alpha value?
I didn't find a 'transparency' key in img.info dictionary as described at [PIL's website](http://www.pythonware.com/library/pil/handbook/format-png.htm)
I'm using Ubuntu and zlib1g, zlibc packages are already installed. | 2009/12/26 | [
"https://Stackoverflow.com/questions/1962795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192767/"
] | To get the alpha layer of an RGBA image all you need to do is:
```
red, green, blue, alpha = img.split()
```
or
```
alpha = img.split()[-1]
```
And there is a method to set the alpha layer:
```
img.putalpha(alpha)
```
The transparency key is only used to define the transparency index in the palette mode (P). If you want to cover the palette mode transparency case as well and cover all cases you could do this
```
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
alpha = img.convert('RGBA').split()[-1]
```
Note: The convert method is needed when the image.mode is LA, because of a bug in PIL. | I tried this:
```
from PIL import Image
import operator, itertools
def get_alpha_channel(image):
try:
alpha_index = image.getbands().index('A')
except ValueError:
# no alpha channel, so convert to RGBA
image = image.convert('RGBA')
alpha_index = image.getbands().index('A')
alpha_getter = operator.itemgetter(alpha_index)
return itertools.imap(alpha_getter, image.getdata())
```
This returned the result that I was expecting. However, I did some calculation to determine the mean and standard deviation, and the results came out slightly different from imagemagick's `fx:mean` function.
Perhaps the conversion changed some of the values? I'm unsure, but it seems relatively trivial. |
1,962,795 | How to detect if a PNG image has transparent alpha channel or not using PIL?
```
img = Image.open('example.png', 'r')
has_alpha = img.mode == 'RGBA'
```
With above code we know whether a PNG image has alpha channel not not but how to get the alpha value?
I didn't find a 'transparency' key in img.info dictionary as described at [PIL's website](http://www.pythonware.com/library/pil/handbook/format-png.htm)
I'm using Ubuntu and zlib1g, zlibc packages are already installed. | 2009/12/26 | [
"https://Stackoverflow.com/questions/1962795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192767/"
] | You can get the alpha data out of whole image in one go by converting image to string with 'A' mode e.g this example get alpha data out of image and saves it as grey scale image :)
```
from PIL import Image
imFile="white-arrow.png"
im = Image.open(imFile, 'r')
print im.mode == 'RGBA'
rgbData = im.tostring("raw", "RGB")
print len(rgbData)
alphaData = im.tostring("raw", "A")
print len(alphaData)
alphaImage = Image.fromstring("L", im.size, alphaData)
alphaImage.save(imFile+".alpha.png")
``` | I tried this:
```
from PIL import Image
import operator, itertools
def get_alpha_channel(image):
try:
alpha_index = image.getbands().index('A')
except ValueError:
# no alpha channel, so convert to RGBA
image = image.convert('RGBA')
alpha_index = image.getbands().index('A')
alpha_getter = operator.itemgetter(alpha_index)
return itertools.imap(alpha_getter, image.getdata())
```
This returned the result that I was expecting. However, I did some calculation to determine the mean and standard deviation, and the results came out slightly different from imagemagick's `fx:mean` function.
Perhaps the conversion changed some of the values? I'm unsure, but it seems relatively trivial. |
63,769,426 | I am trying to run a an HTTP Server written in Golang inside of a docker container and I keep getting connection refused. Everything is being run inside of an Ubuntu 20.04 Server VM running on my Windows 10 machine.
The Go server code:
```
package main
import "github.com/lkelly93/scheduler/internal/server"
func main() {
server := server.NewHTTPServer()
server.Start(3000)
}
```
```
package server
import (
"context"
"fmt"
"net/http"
)
type HTTPServer interface {
Start(port int) error
Stop() error
}
func NewHTTPServer() HTTPServer {
return &httpServer{}
}
type httpServer struct {
server *http.Server
}
func (server *httpServer) Start(port int) error {
serveMux := newServeMux()
server.server = &http.Server {
Addr: fmt.Sprintf(":%d", port),
Handler: serveMux,
}
return server.server.ListenAndServe()
}
func (server *httpServer) Stop() error {
return server.server.Shutdown(context.Background())
}
```
My Dockerfile:
```
FROM ubuntu:20.04
RUN apt-get update -y
#Install needed packages
RUN apt-get install software-properties-common -y
RUN apt-get install python3 -y
RUN apt-get update -y
RUN apt-get install python3-pip -y
RUN apt-get install default-jre -y
#Install language dependacies
#Python
RUN pip3 install numpy
#Reduce VM size
# RUN rm -rf /var/lib/apt/lists/*
#Setup working DIRs
RUN mkdir secure
RUN mkdir secure/runner_files
COPY scheduler /secure
WORKDIR /secure
EXPOSE 3000
CMD ["./scheduler"] <-- The go server is compiled into a binary called scheduler
```
I build the given Dockerfile and then run:
```
docker run -d --name scheduler -p 3000:3000 scheduler:latest
```
Then I grab the container's address with:
```
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' scheduler
->172.17.0.2
```
Finally I use cURL to send an http request:
```
curl http://172.17.0.2:3000/execute/python --data '{"Code":"print(\"Hello\")"}'
```
I am getting
```
curl: (7) Failed to connect to 172.17.0.2 port 3000: Connection refused
```
but should be getting
```
{"Stdout":"Hello\n"}%
```
If I run the Go server on the Ubuntu VM I have no issues calling it from my Win10 machine but I can't seem to call the Go server when it exists inside of a docker container from the Ubuntu machine.
The Go code is more complicated then just that but it's too much to post everything here, feel free to look at the whole repo at <https://github.com/lkelly93/scheduler>.
Eventually it will be the backend to a website I want to make that runs code. Something like LeetCode or Repl.it.
Thanks!
Edit:
```
docker container ls -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2a56a973040f scheduler:latest "./scheduler" 37 seconds ago Up 36 seconds 0.0.0.0:3000->3000/tcp scheduler
```
docker container logs 2a56a973040f gave no output.
Edit 2:
```
docker run -it --net container:2a56a973040f nicolaka/netshoot ss -lnt
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 4096 *:3000 *:*
```
Edit 3:
After reading through the man pages I found that if I had the tag --network=host to my image and then run.
```
curl http://localhost:3000/execute/python --data '{"Code":"print(\"Hello\")"}'
```
I get the correct output. While this works, I would like to have multiple docker images running side by side. So I would prefer to use IP address to address them all. So I don't think this is a permanent fix. | 2020/09/06 | [
"https://Stackoverflow.com/questions/63769426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10665648/"
] | To fix this on my server I set the IP address to 0.0.0.0:4000.
I'm using gin so the example would look lik:
```
r := gin.Default()
r.run("0.0.0.0:4000")
```
After this I was finally able to access it through my browser. | You've published the port, which forwards the port from the docker host to the container. Therefore you want to connect to http://localhost:3000. Connecting to container IP may fail with desktop installs since docker runs inside of a VM and those private IP's are only visible in the VM.
If you happen to be running `docker-machine` (this is the case with older docker toolbox installs), then you'll need to get the IP of the VM. Run `echo $DOCKER_HOST` to see the IP address and adjust the port to port 3000. |
63,769,426 | I am trying to run a an HTTP Server written in Golang inside of a docker container and I keep getting connection refused. Everything is being run inside of an Ubuntu 20.04 Server VM running on my Windows 10 machine.
The Go server code:
```
package main
import "github.com/lkelly93/scheduler/internal/server"
func main() {
server := server.NewHTTPServer()
server.Start(3000)
}
```
```
package server
import (
"context"
"fmt"
"net/http"
)
type HTTPServer interface {
Start(port int) error
Stop() error
}
func NewHTTPServer() HTTPServer {
return &httpServer{}
}
type httpServer struct {
server *http.Server
}
func (server *httpServer) Start(port int) error {
serveMux := newServeMux()
server.server = &http.Server {
Addr: fmt.Sprintf(":%d", port),
Handler: serveMux,
}
return server.server.ListenAndServe()
}
func (server *httpServer) Stop() error {
return server.server.Shutdown(context.Background())
}
```
My Dockerfile:
```
FROM ubuntu:20.04
RUN apt-get update -y
#Install needed packages
RUN apt-get install software-properties-common -y
RUN apt-get install python3 -y
RUN apt-get update -y
RUN apt-get install python3-pip -y
RUN apt-get install default-jre -y
#Install language dependacies
#Python
RUN pip3 install numpy
#Reduce VM size
# RUN rm -rf /var/lib/apt/lists/*
#Setup working DIRs
RUN mkdir secure
RUN mkdir secure/runner_files
COPY scheduler /secure
WORKDIR /secure
EXPOSE 3000
CMD ["./scheduler"] <-- The go server is compiled into a binary called scheduler
```
I build the given Dockerfile and then run:
```
docker run -d --name scheduler -p 3000:3000 scheduler:latest
```
Then I grab the container's address with:
```
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' scheduler
->172.17.0.2
```
Finally I use cURL to send an http request:
```
curl http://172.17.0.2:3000/execute/python --data '{"Code":"print(\"Hello\")"}'
```
I am getting
```
curl: (7) Failed to connect to 172.17.0.2 port 3000: Connection refused
```
but should be getting
```
{"Stdout":"Hello\n"}%
```
If I run the Go server on the Ubuntu VM I have no issues calling it from my Win10 machine but I can't seem to call the Go server when it exists inside of a docker container from the Ubuntu machine.
The Go code is more complicated then just that but it's too much to post everything here, feel free to look at the whole repo at <https://github.com/lkelly93/scheduler>.
Eventually it will be the backend to a website I want to make that runs code. Something like LeetCode or Repl.it.
Thanks!
Edit:
```
docker container ls -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2a56a973040f scheduler:latest "./scheduler" 37 seconds ago Up 36 seconds 0.0.0.0:3000->3000/tcp scheduler
```
docker container logs 2a56a973040f gave no output.
Edit 2:
```
docker run -it --net container:2a56a973040f nicolaka/netshoot ss -lnt
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 4096 *:3000 *:*
```
Edit 3:
After reading through the man pages I found that if I had the tag --network=host to my image and then run.
```
curl http://localhost:3000/execute/python --data '{"Code":"print(\"Hello\")"}'
```
I get the correct output. While this works, I would like to have multiple docker images running side by side. So I would prefer to use IP address to address them all. So I don't think this is a permanent fix. | 2020/09/06 | [
"https://Stackoverflow.com/questions/63769426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10665648/"
] | To fix this on my server I set the IP address to 0.0.0.0:4000.
I'm using gin so the example would look lik:
```
r := gin.Default()
r.run("0.0.0.0:4000")
```
After this I was finally able to access it through my browser. | After doing more googling I followed [this](https://docs.docker.com/network/network-tutorial-standalone/) guide and created my own "user-defined bridge network".
If I launch my container and attach it to this network then it works! I would love it if someone could explain why though! |
34,406,283 | I am trying to write a web application with Python using the Fitbit API. I need to authenticate the user with OAuth 2.0 in the browser. Right now I'm trying to use [python-fitbit](https://github.com/orcasgit/python-fitbit), though I'm not sure there's a better way to do this. Here is my code:
```
import fitbit
client = fitbit.FitbitOauth2Client('client_id', 'client_secret')
res = client.make_request("https://api.fitbit.com/1/user/-/activities.json", None, method='GET')
```
When I run it, I get `ValueError: Missing access token.` What am I doing wrong here? I feel totally in over my head with this. | 2015/12/21 | [
"https://Stackoverflow.com/questions/34406283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5702451/"
] | To be able to add group layers to ArcGIS online you need to add the layers to ArcMap and publish them to ArcGIS server. The ArcMap document name will become the group name in ArcGIS online (the name can be edited in ArcGIS Online). If you want sub groups then you can group the layers in ArcMap. In ArcGIS online you add the data as an ArcGIS server web service. | Grouping layers are apparently not supported in ArcGIS Online webmap. The link you followed is instructions to create a web scene. |
34,406,283 | I am trying to write a web application with Python using the Fitbit API. I need to authenticate the user with OAuth 2.0 in the browser. Right now I'm trying to use [python-fitbit](https://github.com/orcasgit/python-fitbit), though I'm not sure there's a better way to do this. Here is my code:
```
import fitbit
client = fitbit.FitbitOauth2Client('client_id', 'client_secret')
res = client.make_request("https://api.fitbit.com/1/user/-/activities.json", None, method='GET')
```
When I run it, I get `ValueError: Missing access token.` What am I doing wrong here? I feel totally in over my head with this. | 2015/12/21 | [
"https://Stackoverflow.com/questions/34406283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5702451/"
] | Except for work-arounds like grouping in ArcMap as fantomen mentioned, this doesn't seem to be supported; however, there is a request for it on ArcGIS Ideas: <https://community.esri.com/ideas/9987>
You can "vote up" that idea to show Esri that you would like to see it implemented. | Grouping layers are apparently not supported in ArcGIS Online webmap. The link you followed is instructions to create a web scene. |
34,406,283 | I am trying to write a web application with Python using the Fitbit API. I need to authenticate the user with OAuth 2.0 in the browser. Right now I'm trying to use [python-fitbit](https://github.com/orcasgit/python-fitbit), though I'm not sure there's a better way to do this. Here is my code:
```
import fitbit
client = fitbit.FitbitOauth2Client('client_id', 'client_secret')
res = client.make_request("https://api.fitbit.com/1/user/-/activities.json", None, method='GET')
```
When I run it, I get `ValueError: Missing access token.` What am I doing wrong here? I feel totally in over my head with this. | 2015/12/21 | [
"https://Stackoverflow.com/questions/34406283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5702451/"
] | Except for work-arounds like grouping in ArcMap as fantomen mentioned, this doesn't seem to be supported; however, there is a request for it on ArcGIS Ideas: <https://community.esri.com/ideas/9987>
You can "vote up" that idea to show Esri that you would like to see it implemented. | To be able to add group layers to ArcGIS online you need to add the layers to ArcMap and publish them to ArcGIS server. The ArcMap document name will become the group name in ArcGIS online (the name can be edited in ArcGIS Online). If you want sub groups then you can group the layers in ArcMap. In ArcGIS online you add the data as an ArcGIS server web service. |
34,406,283 | I am trying to write a web application with Python using the Fitbit API. I need to authenticate the user with OAuth 2.0 in the browser. Right now I'm trying to use [python-fitbit](https://github.com/orcasgit/python-fitbit), though I'm not sure there's a better way to do this. Here is my code:
```
import fitbit
client = fitbit.FitbitOauth2Client('client_id', 'client_secret')
res = client.make_request("https://api.fitbit.com/1/user/-/activities.json", None, method='GET')
```
When I run it, I get `ValueError: Missing access token.` What am I doing wrong here? I feel totally in over my head with this. | 2015/12/21 | [
"https://Stackoverflow.com/questions/34406283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5702451/"
] | To be able to add group layers to ArcGIS online you need to add the layers to ArcMap and publish them to ArcGIS server. The ArcMap document name will become the group name in ArcGIS online (the name can be edited in ArcGIS Online). If you want sub groups then you can group the layers in ArcMap. In ArcGIS online you add the data as an ArcGIS server web service. | Grouping layers in ArcGIS Online is now possible with the new Map Viewer (which is not in beta anymore). For more info: <https://www.esri.com/arcgis-blog/products/arcgis-online/mapping/try-out-layer-groups-with-map-viewer-beta/> and <https://www.esri.com/arcgis-blog/products/arcgis-online/announcements/whats-new-arcgis-online-april-2021/#mapviewer> |
34,406,283 | I am trying to write a web application with Python using the Fitbit API. I need to authenticate the user with OAuth 2.0 in the browser. Right now I'm trying to use [python-fitbit](https://github.com/orcasgit/python-fitbit), though I'm not sure there's a better way to do this. Here is my code:
```
import fitbit
client = fitbit.FitbitOauth2Client('client_id', 'client_secret')
res = client.make_request("https://api.fitbit.com/1/user/-/activities.json", None, method='GET')
```
When I run it, I get `ValueError: Missing access token.` What am I doing wrong here? I feel totally in over my head with this. | 2015/12/21 | [
"https://Stackoverflow.com/questions/34406283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5702451/"
] | Except for work-arounds like grouping in ArcMap as fantomen mentioned, this doesn't seem to be supported; however, there is a request for it on ArcGIS Ideas: <https://community.esri.com/ideas/9987>
You can "vote up" that idea to show Esri that you would like to see it implemented. | Grouping layers in ArcGIS Online is now possible with the new Map Viewer (which is not in beta anymore). For more info: <https://www.esri.com/arcgis-blog/products/arcgis-online/mapping/try-out-layer-groups-with-map-viewer-beta/> and <https://www.esri.com/arcgis-blog/products/arcgis-online/announcements/whats-new-arcgis-online-april-2021/#mapviewer> |
58,311,868 | I want to print each element registered in my "student\_list" array. But Python prints the memory location of each of my values. I am totally new to OOP using python. Any help or comments are highly appreciated.
```
class Student():
def __init__(self, name, grade_level, subject, grade):
self.name = name
self.grade_level = grade_level
self.subject = subject
self.grade = grade
@classmethod
def student_input(cls):
return cls(
input("Name: "),
input("Garde Level: "),
input("Subject: "),
int(input("Grade: ")),
)
def student_info(self):
print("************************")
print("Name: " + self.name+"\n"+"Grade Level: "+self.grade_level +
"\n"+"Subject: "+self.subject + "\n"+"Grade: "+str(self.grade))
print("************************")
student_list = []
print("**********************")
user1 = Student.student_input()
student_list.append(user1)
print("**********************")
user2 = Student.student_input()
student_list.append(user2)
print("**********************")
print(user1.student_info)
for student in student_list:
print(student)
```
Output:
-------
```
PS C:\Users\D3L10\Documents\PythonML\iPythonProj> python .\schoolSystem.py
**********************
Name: Andy
Garde Level: Freshman
Subject: Physics
Grade: 92
**********************
Name: James
Garde Level: Sophmore
Subject: Algebra
Grade: 82
**********************
<bound method Student.student_info of <__main__.Student object at 0x00580610>>
<__main__.Student object at 0x00580610>
<__main__.Student object at 0x00819DB0>
``` | 2019/10/09 | [
"https://Stackoverflow.com/questions/58311868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12191247/"
] | Replace your method student\_info by the dunder method **str** as follow.
```
def __str__(self):
return f"""
************************\n
Name: {self.name}\n
Grade Level: {self.grade_level}\n
Subject: {self.subject} \n
Grade: {self.grade}\n
************************"""
``` | You need to give your class a `__str__` or `__repr__` method or it won't know how to present itself as a string. If you simply rename your existing `student_info` method to one of these it will work just by doing `print(user1)`
Also, the reason `print(user1.student_info)` didn't do what you expected is because you are asking it to print the method itself not the result of the method. It should be `print(user1.student_info())` |
58,311,868 | I want to print each element registered in my "student\_list" array. But Python prints the memory location of each of my values. I am totally new to OOP using python. Any help or comments are highly appreciated.
```
class Student():
def __init__(self, name, grade_level, subject, grade):
self.name = name
self.grade_level = grade_level
self.subject = subject
self.grade = grade
@classmethod
def student_input(cls):
return cls(
input("Name: "),
input("Garde Level: "),
input("Subject: "),
int(input("Grade: ")),
)
def student_info(self):
print("************************")
print("Name: " + self.name+"\n"+"Grade Level: "+self.grade_level +
"\n"+"Subject: "+self.subject + "\n"+"Grade: "+str(self.grade))
print("************************")
student_list = []
print("**********************")
user1 = Student.student_input()
student_list.append(user1)
print("**********************")
user2 = Student.student_input()
student_list.append(user2)
print("**********************")
print(user1.student_info)
for student in student_list:
print(student)
```
Output:
-------
```
PS C:\Users\D3L10\Documents\PythonML\iPythonProj> python .\schoolSystem.py
**********************
Name: Andy
Garde Level: Freshman
Subject: Physics
Grade: 92
**********************
Name: James
Garde Level: Sophmore
Subject: Algebra
Grade: 82
**********************
<bound method Student.student_info of <__main__.Student object at 0x00580610>>
<__main__.Student object at 0x00580610>
<__main__.Student object at 0x00819DB0>
``` | 2019/10/09 | [
"https://Stackoverflow.com/questions/58311868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12191247/"
] | Method call should be performed with `()`
Code:
```
class Student():
def __init__(self, name, grade_level, subject, grade):
self.name = name
self.grade_level = grade_level
self.subject = subject
self.grade = grade
@classmethod
def student_input(cls):
return cls(
input("Name: "),
input("Garde Level: "),
input("Subject: "),
int(input("Grade: ")),
)
def student_info(self):
print("************************")
print("Name: " + self.name+"\n"+"Grade Level: "+self.grade_level +
"\n"+"Subject: "+self.subject + "\n"+"Grade: "+str(self.grade))
print("************************")
student_list = []
print("**********************")
user1 = Student.student_input()
student_list.append(user1)
print("**********************")
user2 = Student.student_input()
student_list.append(user2)
print("**********************")
print(user1.student_info) # where you failed, not compliying with method call syntax in python
print(user1.student_info()) # correct way to obtain your print.
```
Output:
```
**********************
Name: >? Foo
Garde Level: >? 7
Subject: >? Bart
Grade: >? 8
**********************
Name: >? Fooz
Garde Level: >? 9
Subject: >? pijzef
Grade: >? 3
**********************
<bound method Student.student_info of <__main__.Student object at 0x0000012BF97138C8>>
************************
Name: Foo
Grade Level: 7
Subject: Bart
Grade: 8
************************
None
```
---
Otherwise, as stated in other answers, provide a **srt** method and only print the object. Python will infer a `objet.__str__()` call.
This is more "OOP-ic" | You need to give your class a `__str__` or `__repr__` method or it won't know how to present itself as a string. If you simply rename your existing `student_info` method to one of these it will work just by doing `print(user1)`
Also, the reason `print(user1.student_info)` didn't do what you expected is because you are asking it to print the method itself not the result of the method. It should be `print(user1.student_info())` |
56,643,451 | 1) I am new to Python and love to learn its core. I have downloaded the python software package and discovered the python.exe application inside. I double clicked it and a balck and white window popped up.
[](https://i.stack.imgur.com/XoM6R.png)
Should I call it a python Interpreter or python Shell?
2) I am learning python online. I came across the terms python tty, python shell and python interpreter. I am satisfied by calling that screen inside the window as a tty(TeleTYpewriter) because we could use only keyboard to work inside and no mouse. But actually that screen has got some intelligence responding to our request. Is python tty an apt term for it?
3) In UNIX, shell is an user interface and command line interpreter, so does python interpreter and python shell are the same. | 2019/06/18 | [
"https://Stackoverflow.com/questions/56643451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5068291/"
] | Temporary tables write to disk, so there's I/O costs for both reading and writing. Also most sites don't manage their temporary tables properly and they end up on the default temporary tablespace, which is the same TEMP tablespace everybody uses for sorting, etc. So there's potential for resource contention there.
Materialized views are intended for materializing aspects of our data set which are commonly reused by many different queries. That's why the most common use case is for storing higher level aggregates of low level data. That doesn't sound like the use case you have here. And lo!
>
> I'm doing a complete refresh of MVs and not a incremental refresh
>
>
>
So nope.
>
> Then I have around 15 intermediate steps, where I'm combining dimension tables, performing some aggregation and implementing business logic.
>
>
>
This is a terribly procedural way of querying data. Sometimes there's no way of avoiding this, especially in certain data warehouse scenarios. However, it doesn't follow that we need to materialize the outputs of those queries. An alternative approach is to use WITH clauses. The output from one WITH subquery can feed into lower subqueries.
```
with sq1 as (
select whatever
, count(*) as t1_tot
from t1
group by whatever
) , sq2 as (
select sq1.whatever
, max(t2.blah) as max_blah
from sq1
join t2 on t2.whatever = sq1.whatever
) , sq3 as (
select sq2.whatever
,(t3.meh + t3.huh) as qty
from sq2
join t3 on t3.whatever = sq2.whatever
where t3.something >= sq2.max_blah
)
select sq1.whatever
,sq1.t1_tot
,sq2.max_blah
,sq3.qty
from sq1
join sq2 on sq2.whatever = sq1.whatever
join sq3 on sq3.whatever = sq1.whatever
```
Not saying it won't be a monstrous query, the terror of the department. But it will probably perform way better than your MViews ot GTTs. (Oracle may choose to materialize those intermediate result sets but [we can use hints to affect that](http://dbaora.com/with-clause-and-hints-materialize-and-inline/).)
You may even find from taking this approach that some of your steps are unnecessary and you can combine several steps into one query. Certainly in real life I would write my toy statement above as one query not a join of three subqueries. | From what you said, I'd say that using (global or private, depending on database version you use) temporary tables is a better choice. Why? Because you are "calculating" something, storing results of those calculations into some tables, reusing them for additional processing. All of that - if it can't be done without *temporary* tables - is to be done with tables.
Materialized view is, as its name says, a *view*. It is a result of some query, but - opposed to "normal" views, it actually takes space. Can be refreshed (either on demand, when source data is changed, or based on a schedule). Yes, it has its advantages, though I can't see any in what you are currently doing. |
54,643,668 | I have a test case where I'd like to be able to run a python file with arguments.
I have 2 files.
app.py
```
def process_data(arg1,arg2,arg3):
return {'msg':'ok'}
if __name__ == "__main__":
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
process_data(arg1,arg2,arg3)
```
test\_cases.py
```
class TestCase(unittest.TestCase):
def test_case1(self):
expected_output = {'msg':'ok'}
with os.popen("echo python app.py arg1 arg2 arg3") as o:
output = o.read()
output = output.strip()
self.assertEqual(output, expected_output)
if __name__ == "__main__":
unittest.main()
```
expected result is {'msg':'ok'} however the variable output returns nothing. | 2019/02/12 | [
"https://Stackoverflow.com/questions/54643668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11048996/"
] | Here is on `hover` of `Child` Element rest of `Child` is filter
```css
.parent .child:not(:hover) {
color:#00ffff;
-webkit-filter: grayscale(1);
-moz-filter: grayscale(1);
-ms-filter: grayscale(1);
filter: grayscale(1);
opacity: .75;
}
```
```html
<div class="parent">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="child">Child 3</div>
</div>
```
and using parent `Hover`
```css
.parent:hover .child:not(:hover) {
color:#00ffff;
-webkit-filter: grayscale(1);
-moz-filter: grayscale(1);
-ms-filter: grayscale(1);
filter: grayscale(1);
opacity: .75;
}
```
```html
<div class="parent">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="child">Child 3</div>
</div>
``` | Use `.class:not(:hover)` which filters all elements with class `.class` but not hovered |
57,072,531 | Added a Point field in one of my model to load map.to migrate the changes in model ,in pycharm terminal python manage.py makemigrations run okay. but python manage.py migrate raise ValueError('Cannot use object with type %s for a spatial lookup parameter.' % type(obj).**name**)
.
i think the reason could be changes in Django 2.2.I even tried using MultiPolygon field ,PointField .
settings.py
```
CORE_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.postgres',
'django.contrib.gis'
]
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
```
models.py
```
from django.contrib.gis.db import models
longitude = models.FloatField("Outlet Longitude", default=0.0, blank=False, help_text="Longitude")
latitude = models.FloatField("Outlet Latitude", default=0.0, blank=False, help_text="Latitude")
location = models.PointField()
```
i just want to load map . | 2019/07/17 | [
"https://Stackoverflow.com/questions/57072531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5577656/"
] | In my case, it was a problem that I entered the tuple value as the default value, so the error occurred.
1. Delete the migration information in the migrations folder of the model.
2. Set the default values as follows.
```
from django.contrib.gis.geos import Point
location = gis_models.PointField(default=Point(0, 0), blank=True)
```
3. python manage.py makemigrations
4. python manage.py migrate | To load the map using postgis you can do the following:
```py
from django.contrib.gis.db import models as gis_models
location = gis_models.PointField(
"Location in Map", geography=True, blank=True, null=True,
srid=4326, help_text="Point(longitude latitude)")
```
Suggestion : Try using proper alias when importing models from a different app |
27,470,494 | I'm not quite sure why the following doesn't work. I tried to send a dictionary object to a function, test a few things and make the dict null if certain criteria was met. I don't know why.
A simple version of what I tried to do:
```
def destroy_bad_variables(a):
# test if a is a bad variable, nullify if true
#del a # doesn't work.
a = None
print a # this says its null
def change(a):
a['car'] = 9
b = {'bar':3, 'foo':8}
print b
change(b)
print "change(b):", b
destroy_bad_variables(b)
print "destroy_bad_variables(b):", b
```
It produces the following output:
```
{'foo': 8, 'bar': 3}
change(b): {'car': 9, 'foo': 8, 'bar': 3}
None
destroy_bad_variables(b): {'car': 9, 'foo': 8, 'bar': 3}
```
The dict can be modified by a function as is expected, but for some reason it can't be set to None. Why is this? Is there some good reason for this seemingly inconsistent behaviour? Forgive my ignorance, none of the books I've read on python explain this. As I understand it dicts are "mutable", the function should null the dict object and not some copy of it.
I know I can work around it by setting b = destroy(b) and returning None from destroy(), but I don't understand why the above doesn't work. | 2014/12/14 | [
"https://Stackoverflow.com/questions/27470494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4282588/"
] | When you say
```
a = None
```
you are making `a` refer to `None`, which was earlier pointing to the dictionary object. But when you do
```
a['car'] = 9
```
`a` is still a reference to the dictionary object and so, you are actually adding a new key `car` to the dictionary object only. That is why it works.
So, the correct way to clear the dictionary is to use [`dict.clear`](https://docs.python.org/2/library/stdtypes.html#dict.clear) method, like this
```
a.clear()
``` | the thing why its not working:
```
>>> a=[1,2,3,4]
>>> def destroy(a):
... del a # here a is local to destroy only
...
>>> destroy(a)
>>> a
[1, 2, 3, 4]
``` |
27,470,494 | I'm not quite sure why the following doesn't work. I tried to send a dictionary object to a function, test a few things and make the dict null if certain criteria was met. I don't know why.
A simple version of what I tried to do:
```
def destroy_bad_variables(a):
# test if a is a bad variable, nullify if true
#del a # doesn't work.
a = None
print a # this says its null
def change(a):
a['car'] = 9
b = {'bar':3, 'foo':8}
print b
change(b)
print "change(b):", b
destroy_bad_variables(b)
print "destroy_bad_variables(b):", b
```
It produces the following output:
```
{'foo': 8, 'bar': 3}
change(b): {'car': 9, 'foo': 8, 'bar': 3}
None
destroy_bad_variables(b): {'car': 9, 'foo': 8, 'bar': 3}
```
The dict can be modified by a function as is expected, but for some reason it can't be set to None. Why is this? Is there some good reason for this seemingly inconsistent behaviour? Forgive my ignorance, none of the books I've read on python explain this. As I understand it dicts are "mutable", the function should null the dict object and not some copy of it.
I know I can work around it by setting b = destroy(b) and returning None from destroy(), but I don't understand why the above doesn't work. | 2014/12/14 | [
"https://Stackoverflow.com/questions/27470494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4282588/"
] | When you say
```
a = None
```
you are making `a` refer to `None`, which was earlier pointing to the dictionary object. But when you do
```
a['car'] = 9
```
`a` is still a reference to the dictionary object and so, you are actually adding a new key `car` to the dictionary object only. That is why it works.
So, the correct way to clear the dictionary is to use [`dict.clear`](https://docs.python.org/2/library/stdtypes.html#dict.clear) method, like this
```
a.clear()
``` | You're not destroying anything, you're just changing `a`'s value to `None` in `destroy`'s local scope.
Why are you not simply using:
```
some_dictionary = None
```
To remove reference to `some_dictionary`? The garbage collector will do the destruction when no one references `some_dictionary` anymore.
In your code:
```
b = None # replaced: destroy(b)
``` |
67,510,784 | I'm gonna be honest, I have no clue what I'm looking at here.
Out of nowhere my Debug configuration in this VSCode project, a Discord bot, has been spitting out errors when I begin debugging. It doesn't do this when running the program normally, and debugging seems to be okay in other projects.
About 50% of the time, it'll end up connecting to Discord despite the errors and debugging works normally, but other times the program will hang and refuse to connect to Discord.
Here is the error text, and I apologize for dumping so much code but I don't know if any of this is significant:
```
'c:\Users\Lucas\.vscode\extensions\ms-python.python-2021.5.829140558\pythonFiles\lib\python\debugpy\launcher' '51717' '--' 'bot/bot.py'
pydev debugger: critical: unable to get real case for file. Details:
filename: bot
drive:
parts: ['bot']
(please create a ticket in the tracker to address this).
Traceback (most recent call last):
File "c:\Users\Lucas\.vscode\extensions\ms-python.python-2021.5.829140558\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 221, in _get_path_with_real_case
return _resolve_listing(drive, iter(parts))
File "c:\Users\Lucas\.vscode\extensions\ms-python.python-2021.5.829140558\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 184, in _resolve_listing
dir_contents = cache[resolved_lower] = os.listdir(resolved)
FileNotFoundError: [WinError 3] The system cannot find the path specified: ''
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Lucas\.vscode\extensions\ms-python.python-2021.5.829140558\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 226, in _get_path_with_real_case
return _resolve_listing(drive, iter(parts))
File "c:\Users\Lucas\.vscode\extensions\ms-python.python-2021.5.829140558\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 184, in _resolve_listing
dir_contents = cache[resolved_lower] = os.listdir(resolved)
FileNotFoundError: [WinError 3] The system cannot find the path specified: ''
pydev debugger: critical: unable to get real case for file. Details:
filename: bot
drive:
parts: ['bot']
(please create a ticket in the tracker to address this).
Traceback (most recent call last):
File "c:\Users\Lucas\.vscode\extensions\ms-python.python-2021.5.829140558\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 221, in _get_path_with_real_case
return _resolve_listing(drive, iter(parts))
File "c:\Users\Lucas\.vscode\extensions\ms-python.python-2021.5.829140558\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 184, in _resolve_listing
dir_contents = cache[resolved_lower] = os.listdir(resolved)
FileNotFoundError: [WinError 3] The system cannot find the path specified: ''
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Lucas\.vscode\extensions\ms-python.python-2021.5.829140558\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 226, in _get_path_with_real_case
return _resolve_listing(drive, iter(parts))
File "c:\Users\Lucas\.vscode\extensions\ms-python.python-2021.5.829140558\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 184, in _resolve_listing
dir_contents = cache[resolved_lower] = os.listdir(resolved)
FileNotFoundError: [WinError 3] The system cannot find the path specified: ''
```
I've posted a ticket on the [tracker](https://www.brainwy.com/tracker/PyDev/) mentioned in the error but I honestly have no clue what PyDev is or if there's a way to even just reinstall it and fix the issue.
Is there some kind of workaround? I don't really know what I'm asking purely because this is so unfamiliar to me, but this is just one of those errors that seems to happen spontaneously with no real reason at all. | 2021/05/12 | [
"https://Stackoverflow.com/questions/67510784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14688435/"
] | **Answer:**
Change `"program": "bot"` to `"program": "${workspaceFolder}\\bot.py"` in `./.vscode/launch.json`.
For most people the file name will not be `bot`, but `main` or `script` or whatever you have called the file of your Python Script. So you would use `"${workspaceFolder}\\main.py"` etc.
**Background:**
In a recent update of the pydev debugger I assume they have updated how file locations are parsed.
The `file name` (VS Code calls it `program`) you have used is `bot`, and this syntax no longer works.`./bot` which also used to work will no longer work but will throw a slightly different error. I am not sure if this change is a bug or an intended change.
Your Python debug configuration for your workspace in VS Code is found under `{workspaceFolder}/.vscode/launch.json` (if you don't already have a `launch.json`, create one).
You must change `"program": "bot"` to `"program": "${workspaceFolder}\\bot.py"` using `{workspaceFolder}\\` and the correct file name and location.
This assumes you are launching your workspace from its root directory. You can tell this by the starting directory when you open the integrated terminal. | ### Here's the reason for such error and a better way to fix it
>
> The error occurs because the python debugger executes files in the terminal from the current open folder (by default)
>
> But you can change this behavior, to use execute in the file's directory:
>
>
>
* Go to vscode settings (or use the shortcut key: **ctrl+comma** )
* then search for this `@ext:ms-python.python execute` in the settings
* you would see the settings "Execute in File Dir"
* then check the box, *to execute code in file's directory instead of the current open folder*
* go back to your code and re-run (i.e clicking the debugger run button)
>
> This eliminates the FileNotFoundError when you know your file is sitting in the right place, and you are pointing in the right direction.
>
>
> |
18,486,169 | Hi i have code like this
```
a = 7
def Add(number):
number+=1
print(number)
Add(a)
print(a)
```
and it prints
```
8
7
```
as I know it must to change it because function takes reference everytime in python whats problem and how can I solve it? | 2013/08/28 | [
"https://Stackoverflow.com/questions/18486169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | Did you try
$.cookie("name", null);
```
$.removeCookie('filter', { path: '/' });
``` | If you use a domain parameter when creating a cookie, this will work
```
$.removeCookie('cookie', { path: '/' , domain : 'yourdomain.com'});
``` |
18,486,169 | Hi i have code like this
```
a = 7
def Add(number):
number+=1
print(number)
Add(a)
print(a)
```
and it prints
```
8
7
```
as I know it must to change it because function takes reference everytime in python whats problem and how can I solve it? | 2013/08/28 | [
"https://Stackoverflow.com/questions/18486169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | Did you try
$.cookie("name", null);
```
$.removeCookie('filter', { path: '/' });
``` | I was having the same issue with jquery version 1.7.1 and jquery cookie version 1.4.1
This was driving me crazy so I decided to dive into the source code and I figured out what is wrong.
Here is the definition of $.removeCookie
```
$.removeCookie = function (key, options) {
if ($.cookie(key) === undefined) { // this line is the problem
return false;
}
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
```
As you can see when the function checks if the cookie exists it doesn't take the options object into account. So if you are on a different path than the cookie you're trying to remove the function will fail.
A Few Solutions:
Upgrade Jquery Cookies. The most recent version doesn't even do that sanity check.
or add this to you document ready
```
$.removeCookie = function (key, options) {
if ($.cookie(key, options) === undefined) { // this line is the fix
return false;
}
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
```
or when removing cookies do something like this:
```
$.cookie('cookie-name', '', { path: '/my/path', expires:-1 });
``` |
18,486,169 | Hi i have code like this
```
a = 7
def Add(number):
number+=1
print(number)
Add(a)
print(a)
```
and it prints
```
8
7
```
as I know it must to change it because function takes reference everytime in python whats problem and how can I solve it? | 2013/08/28 | [
"https://Stackoverflow.com/questions/18486169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | It might depend on what path your cookie is using. If you goto the chrome developer tools and check the path column under Resources > Cookies > Path.

You might be using the generic `/` for your path instead of `/Home/`. Give the code below a try.
To delete a cookie with jQuery set the value to null:
```
$.removeCookie('filter', { path: '/' });
``` | This simple way it works fine:
```
$.cookie("cookieName", "", { expires: -1 });
``` |
18,486,169 | Hi i have code like this
```
a = 7
def Add(number):
number+=1
print(number)
Add(a)
print(a)
```
and it prints
```
8
7
```
as I know it must to change it because function takes reference everytime in python whats problem and how can I solve it? | 2013/08/28 | [
"https://Stackoverflow.com/questions/18486169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | Did you try
$.cookie("name", null);
```
$.removeCookie('filter', { path: '/' });
``` | This simple way it works fine:
```
$.cookie("cookieName", "", { expires: -1 });
``` |
18,486,169 | Hi i have code like this
```
a = 7
def Add(number):
number+=1
print(number)
Add(a)
print(a)
```
and it prints
```
8
7
```
as I know it must to change it because function takes reference everytime in python whats problem and how can I solve it? | 2013/08/28 | [
"https://Stackoverflow.com/questions/18486169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | If you use a domain parameter when creating a cookie, this will work
```
$.removeCookie('cookie', { path: '/' , domain : 'yourdomain.com'});
``` | This simple way it works fine:
```
$.cookie("cookieName", "", { expires: -1 });
``` |
18,486,169 | Hi i have code like this
```
a = 7
def Add(number):
number+=1
print(number)
Add(a)
print(a)
```
and it prints
```
8
7
```
as I know it must to change it because function takes reference everytime in python whats problem and how can I solve it? | 2013/08/28 | [
"https://Stackoverflow.com/questions/18486169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | I was having the same issue with jquery version 1.7.1 and jquery cookie version 1.4.1
This was driving me crazy so I decided to dive into the source code and I figured out what is wrong.
Here is the definition of $.removeCookie
```
$.removeCookie = function (key, options) {
if ($.cookie(key) === undefined) { // this line is the problem
return false;
}
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
```
As you can see when the function checks if the cookie exists it doesn't take the options object into account. So if you are on a different path than the cookie you're trying to remove the function will fail.
A Few Solutions:
Upgrade Jquery Cookies. The most recent version doesn't even do that sanity check.
or add this to you document ready
```
$.removeCookie = function (key, options) {
if ($.cookie(key, options) === undefined) { // this line is the fix
return false;
}
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
```
or when removing cookies do something like this:
```
$.cookie('cookie-name', '', { path: '/my/path', expires:-1 });
``` | This simple way it works fine:
```
$.cookie("cookieName", "", { expires: -1 });
``` |
18,486,169 | Hi i have code like this
```
a = 7
def Add(number):
number+=1
print(number)
Add(a)
print(a)
```
and it prints
```
8
7
```
as I know it must to change it because function takes reference everytime in python whats problem and how can I solve it? | 2013/08/28 | [
"https://Stackoverflow.com/questions/18486169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | It might depend on what path your cookie is using. If you goto the chrome developer tools and check the path column under Resources > Cookies > Path.

You might be using the generic `/` for your path instead of `/Home/`. Give the code below a try.
To delete a cookie with jQuery set the value to null:
```
$.removeCookie('filter', { path: '/' });
``` | What works for me is setting the cookie to null before removing it:
`$.cookie("filter", null);
$.removeCookie("filter);` |
18,486,169 | Hi i have code like this
```
a = 7
def Add(number):
number+=1
print(number)
Add(a)
print(a)
```
and it prints
```
8
7
```
as I know it must to change it because function takes reference everytime in python whats problem and how can I solve it? | 2013/08/28 | [
"https://Stackoverflow.com/questions/18486169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | It might depend on what path your cookie is using. If you goto the chrome developer tools and check the path column under Resources > Cookies > Path.

You might be using the generic `/` for your path instead of `/Home/`. Give the code below a try.
To delete a cookie with jQuery set the value to null:
```
$.removeCookie('filter', { path: '/' });
``` | Did you try
$.cookie("name", null);
```
$.removeCookie('filter', { path: '/' });
``` |
18,486,169 | Hi i have code like this
```
a = 7
def Add(number):
number+=1
print(number)
Add(a)
print(a)
```
and it prints
```
8
7
```
as I know it must to change it because function takes reference everytime in python whats problem and how can I solve it? | 2013/08/28 | [
"https://Stackoverflow.com/questions/18486169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | It might depend on what path your cookie is using. If you goto the chrome developer tools and check the path column under Resources > Cookies > Path.

You might be using the generic `/` for your path instead of `/Home/`. Give the code below a try.
To delete a cookie with jQuery set the value to null:
```
$.removeCookie('filter', { path: '/' });
``` | If you use a domain parameter when creating a cookie, this will work
```
$.removeCookie('cookie', { path: '/' , domain : 'yourdomain.com'});
``` |
18,486,169 | Hi i have code like this
```
a = 7
def Add(number):
number+=1
print(number)
Add(a)
print(a)
```
and it prints
```
8
7
```
as I know it must to change it because function takes reference everytime in python whats problem and how can I solve it? | 2013/08/28 | [
"https://Stackoverflow.com/questions/18486169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715191/"
] | Did you try
$.cookie("name", null);
```
$.removeCookie('filter', { path: '/' });
``` | What works for me is setting the cookie to null before removing it:
`$.cookie("filter", null);
$.removeCookie("filter);` |
19,829,015 | I have a regular expression `'[\w_-]+'` which allows alphanumberic character or underscore.
I have a set of words in a python list which I don't want to allow
```
listIgnore = ['summary', 'config']
```
What changes need to be made in the regex?
P.S: I am new to regex | 2013/11/07 | [
"https://Stackoverflow.com/questions/19829015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165520/"
] | This question intrigued me, so I set about for an answer:
```
'^(?!summary)(?!config)[\w_-]+$'
```
Now this only works if you want to match the regex against a complete string:
```
>>> re.match('^(?!summary)(?!config)[\w_-]+$','config_test')
>>> (None)
>>> re.match('^(?!summary)(?!config)[\w_-]+$','confi_test')
>>> <_sre.SRE_Match object at 0x21d34a8>
```
So to use your list, just add in more `(?!<word here>)` for each word after `^` in your regex. These are called lookaheads. [Here's](http://www.regular-expressions.info/lookaround2.html) some good info.
If you're trying to match within a string (i.e. without the `^` and `$`) then I'm not sure it's possible. For instance the regex will just pick a subset of the string that doesn't match. Example: `ummary` for `summary`.
Obviously the more exclusions you pick the more inefficient it will get. There's probably better ways to do it. | ```
>>> line="This is a line containing a summary of config changes"
>>> listIgnore = ['summary', 'config']
>>> patterns = "|".join(listIgnore)
>>> print re.findall(r'\b(?!(?:' + patterns + r'))[\w_-]+', line)
['This', 'is', 'a', 'line', 'containing', 'a', 'of', 'changes']
``` |
47,223,782 | I've been trying my hand at some data visualization with Python and Matplot. In this case I'm trying to visualize the amount of data missing per column. I ran a short script to find all the missing values per column and the result in the array missing\_count. I now would like to show this in a bar chart using Matplot but I've run into this issue:
```
import matplotlib.pyplot as plt
import numpy as np
missing_count = np.array([33597, 0, 0, 0, 0, 0, 0, 12349, 0, 0, 12349, 0, 0, 0, 115946, 47696, 44069, 81604, 5416, 5416, 5416, 5416, 0, 73641, 74331, 187204, 128829, 184118, 116441, 183093, 153048, 187349, 89918, 89918, 89918, 89918, 89918, 89918, 51096, 51096, 51096, 51096, 51096, 51096, 51096, 51096, 51096, 51096])
n = len(missing_count)
index = np.arange(n)
fig, ax = plt.subplots()
r1 = ax.bar(index, n, 0.15, missing_count, color='r')
ax.set_ylabel('NULL values')
ax.set_title('Amount of NULL values per colum')
ax.set_xticks(index + width / 2)
ax.set_xticklabels(list(originalData.columns.values))
plt.show()
```
Resulting in this error:
```
ValueError Traceback (most recent call last)
<ipython-input-34-285ca1e9de68> in <module>()
10 fig, ax = plt.subplots()
11
---> 12 r1 = ax.bar(index, n, 0.15, missing_count, color='r')
13
14 ax.set_ylabel('NULL values')
C:\Users\Martien\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1895 warnings.warn(msg % (label_namer, func.__name__),
1896 RuntimeWarning, stacklevel=2)
-> 1897 return func(ax, *args, **kwargs)
1898 pre_doc = inner.__doc__
1899 if pre_doc is None:
C:\Users\Martien\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in bar(self, left, height, width, bottom, **kwargs)
2077 if len(height) != nbars:
2078 raise ValueError("incompatible sizes: argument 'height' "
-> 2079 "must be length %d or scalar" % nbars)
2080 if len(width) != nbars:
2081 raise ValueError("incompatible sizes: argument 'width' "
ValueError: incompatible sizes: argument 'height' must be length 48 or scalar
```
I've looked at a the Matplot documentation which tells me that height should be a scalar, but it does not reference or explain what this scalar is. There is also [this](https://matplotlib.org/examples/api/barchart_demo.html) example I've followed which does work when I run it.
I've run out of ideas as to why I get this error, all help would really be appreciated.
Edit: originalData is the original CSV file I read in, I only use it here to name my bars | 2017/11/10 | [
"https://Stackoverflow.com/questions/47223782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6182876/"
] | so, according to <https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.bar.html>
the second argument must be height
you're inputting `n` as the second argument which is a single number
try
```
r1 = ax.bar(index, missing_count, 0.15, color='r')
```
instead, which should get the job done.
Even better, be explicit about your argument names (tedious, and harder to keep clean, but a good ides when you have more than a few arguments)
```
r1 = ax.bar(x=index, height = missing_count, width = 0.15, color='r')
```
the second argument must be height; height corresponds to the count for any particular box. Say you had an array of zeros and ones
```
A = [0,0,0,0,1,1,1]
```
that would result in a bar plot with two bars, one would be 4 units high (since you have four zeros) the other would be 3 units high
the command
```
r1 = ax.bar([0,1], [4,3], 0.15, color='r')
```
would make a plot with a bar at zero and a bar at 1. The first bar would be 4 units high, the second would be 3 units high.
Translating to your code, `missing_count` corresponds to the COUNT of the array
that's not `A`, but instead `[Counter([0,0,0,0,1,1,1])[x] for x in Counter([0,0,0,0,1,1,1])]` | In the code `n` is scalar. You probably do not want the bar height to be constant, but rather the values from `missing_count`.
```
ax.bar(index, missing_count, 0.15, color='r')
``` |
58,723,914 | I've got a data object that was created by creating what I assume is a json object -
```
jsonobj = {}
jsonobj["recordnum"] = callpri
```
and then pushing that onto a list, as there is more than one of them -
```
myList = []
myList.append(jsonobj)
```
Then that gets passed back and forth between flask subroutines and Jinja2 templates, until it ends up a few steps later coming into the function where I need to access that data, and it comes in looking something like so -
```
techlist: [{'recordnum': '1', 'name': 'Person 1', 'phonenumber': '123-456-7890', 'email': 'person1@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '2', 'name': 'Person 2', 'phonenumber': '098-765-4321', 'email': 'person2@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '3', 'name': 'Person 3', 'phonenumber': '567-890-1234', 'email': 'person3@company.tld', 'maxnumtechs': 'ALL'}]
```
I tried a `for tech in techlist: print(tech['recordnum'])` type deal and got an error, so I started printing types for everything and it's all strings. The `for tech in techlist` is I think just splitting it all into words even, which is obviously not what I want at all.
I tried messing around with json.loads on techlist, but it complained about expecting an entry in double quotes or something along those lines. I'm totally stumped, and would really appreciate if someone could please tell me how to turn this string back into a list of dicts or a list of json objects, or whatever it takes for me to be able to iterate through the items and access specific fields.
**Response to comments about it working right:**
It's coming in as a string for me, and I think for the two of you it is working for, you're creating it as a list, so it would work correctly ... sadly, that's my problem, it's a string, not a list, so it's doing this -
```
(env) [me@box directory]$ cat test.py
techlist = "[{'recordnum': '1', 'name': 'Person 1', 'phonenumber': '123-456-7890', 'email': 'person1@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '2', 'name': 'Person 2', 'phonenumber': '098-765-4321', 'email': 'person2@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '3', 'name': 'Person 3', 'phonenumber': '567-890-1234', 'email': 'person3@company.tld', 'maxnumtechs': 'ALL'}]"
print(type(techlist))
for tech in techlist:
print(type(tech))
print(str(tech))
(env) [me@box directory]$
(env) [me@box directory]$
(env) [me@box directory]$ python test.py
<class 'str'>
<class 'str'>
[
<class 'str'>
{
<class 'str'>
'
<class 'str'>
r
<class 'str'>
e
<snip>
```
**Update:**
Trenton McKinney 's comment worked PERFECTLY, THANK YOU!! If you're so inclined as to post it as a answer I'll accept it as the solution. Thank you thank you thank you!! | 2019/11/06 | [
"https://Stackoverflow.com/questions/58723914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11274599/"
] | Something like this ?
**`Vote.group(:user_id).limit(10)`** | Can't think of an active record or SQL way of doing this.
But below is a pure Ruby solution:
For ruby 2.4 and above, you can use Hash#transform\_values on the `group_by` hash result like so (continuing from your query):
```
votes = Vote.where(votable_id: @comments_ids, votable_type:
'Comment').select(:votable_id, :user_id).group_by(&:votable_id)
top_voters = votes.transform_values do |val|
voters = val.map(&:user_id)
freq = voters.reduce(Hash.new(0)) {|h, v| h[v] += 1; h }
sorted_votes = voters.uniq.sort_by {|elem| -freq[elem] }
sorted_votes.take(10)
end
``` |
58,723,914 | I've got a data object that was created by creating what I assume is a json object -
```
jsonobj = {}
jsonobj["recordnum"] = callpri
```
and then pushing that onto a list, as there is more than one of them -
```
myList = []
myList.append(jsonobj)
```
Then that gets passed back and forth between flask subroutines and Jinja2 templates, until it ends up a few steps later coming into the function where I need to access that data, and it comes in looking something like so -
```
techlist: [{'recordnum': '1', 'name': 'Person 1', 'phonenumber': '123-456-7890', 'email': 'person1@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '2', 'name': 'Person 2', 'phonenumber': '098-765-4321', 'email': 'person2@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '3', 'name': 'Person 3', 'phonenumber': '567-890-1234', 'email': 'person3@company.tld', 'maxnumtechs': 'ALL'}]
```
I tried a `for tech in techlist: print(tech['recordnum'])` type deal and got an error, so I started printing types for everything and it's all strings. The `for tech in techlist` is I think just splitting it all into words even, which is obviously not what I want at all.
I tried messing around with json.loads on techlist, but it complained about expecting an entry in double quotes or something along those lines. I'm totally stumped, and would really appreciate if someone could please tell me how to turn this string back into a list of dicts or a list of json objects, or whatever it takes for me to be able to iterate through the items and access specific fields.
**Response to comments about it working right:**
It's coming in as a string for me, and I think for the two of you it is working for, you're creating it as a list, so it would work correctly ... sadly, that's my problem, it's a string, not a list, so it's doing this -
```
(env) [me@box directory]$ cat test.py
techlist = "[{'recordnum': '1', 'name': 'Person 1', 'phonenumber': '123-456-7890', 'email': 'person1@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '2', 'name': 'Person 2', 'phonenumber': '098-765-4321', 'email': 'person2@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '3', 'name': 'Person 3', 'phonenumber': '567-890-1234', 'email': 'person3@company.tld', 'maxnumtechs': 'ALL'}]"
print(type(techlist))
for tech in techlist:
print(type(tech))
print(str(tech))
(env) [me@box directory]$
(env) [me@box directory]$
(env) [me@box directory]$ python test.py
<class 'str'>
<class 'str'>
[
<class 'str'>
{
<class 'str'>
'
<class 'str'>
r
<class 'str'>
e
<snip>
```
**Update:**
Trenton McKinney 's comment worked PERFECTLY, THANK YOU!! If you're so inclined as to post it as a answer I'll accept it as the solution. Thank you thank you thank you!! | 2019/11/06 | [
"https://Stackoverflow.com/questions/58723914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11274599/"
] | ```rb
table = Vote.arel_table
Vote.where(votable_id: @comments_ids, votable_type: 'Comment')
.select(:votable_id, :user_id)
.group(:votable_id, :user_id, :id)
.order('table[:votable_id].count.desc')
.limit(10)
```
This should give you a list of the top ten votes. Using vanilla ruby with the `#group_by` will take a very long time if the collection is large. Using Arel will avoid any breaking changes in Rails 6.0 where raw sql will not be permitted in queries. I would previously use `.order('COUNT(votable_id) DESC')` but that throws errors and will be disallowed in Rails 6 | Can't think of an active record or SQL way of doing this.
But below is a pure Ruby solution:
For ruby 2.4 and above, you can use Hash#transform\_values on the `group_by` hash result like so (continuing from your query):
```
votes = Vote.where(votable_id: @comments_ids, votable_type:
'Comment').select(:votable_id, :user_id).group_by(&:votable_id)
top_voters = votes.transform_values do |val|
voters = val.map(&:user_id)
freq = voters.reduce(Hash.new(0)) {|h, v| h[v] += 1; h }
sorted_votes = voters.uniq.sort_by {|elem| -freq[elem] }
sorted_votes.take(10)
end
``` |
58,723,914 | I've got a data object that was created by creating what I assume is a json object -
```
jsonobj = {}
jsonobj["recordnum"] = callpri
```
and then pushing that onto a list, as there is more than one of them -
```
myList = []
myList.append(jsonobj)
```
Then that gets passed back and forth between flask subroutines and Jinja2 templates, until it ends up a few steps later coming into the function where I need to access that data, and it comes in looking something like so -
```
techlist: [{'recordnum': '1', 'name': 'Person 1', 'phonenumber': '123-456-7890', 'email': 'person1@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '2', 'name': 'Person 2', 'phonenumber': '098-765-4321', 'email': 'person2@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '3', 'name': 'Person 3', 'phonenumber': '567-890-1234', 'email': 'person3@company.tld', 'maxnumtechs': 'ALL'}]
```
I tried a `for tech in techlist: print(tech['recordnum'])` type deal and got an error, so I started printing types for everything and it's all strings. The `for tech in techlist` is I think just splitting it all into words even, which is obviously not what I want at all.
I tried messing around with json.loads on techlist, but it complained about expecting an entry in double quotes or something along those lines. I'm totally stumped, and would really appreciate if someone could please tell me how to turn this string back into a list of dicts or a list of json objects, or whatever it takes for me to be able to iterate through the items and access specific fields.
**Response to comments about it working right:**
It's coming in as a string for me, and I think for the two of you it is working for, you're creating it as a list, so it would work correctly ... sadly, that's my problem, it's a string, not a list, so it's doing this -
```
(env) [me@box directory]$ cat test.py
techlist = "[{'recordnum': '1', 'name': 'Person 1', 'phonenumber': '123-456-7890', 'email': 'person1@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '2', 'name': 'Person 2', 'phonenumber': '098-765-4321', 'email': 'person2@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '3', 'name': 'Person 3', 'phonenumber': '567-890-1234', 'email': 'person3@company.tld', 'maxnumtechs': 'ALL'}]"
print(type(techlist))
for tech in techlist:
print(type(tech))
print(str(tech))
(env) [me@box directory]$
(env) [me@box directory]$
(env) [me@box directory]$ python test.py
<class 'str'>
<class 'str'>
[
<class 'str'>
{
<class 'str'>
'
<class 'str'>
r
<class 'str'>
e
<snip>
```
**Update:**
Trenton McKinney 's comment worked PERFECTLY, THANK YOU!! If you're so inclined as to post it as a answer I'll accept it as the solution. Thank you thank you thank you!! | 2019/11/06 | [
"https://Stackoverflow.com/questions/58723914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11274599/"
] | If the data is not too big, you can do it like this:
```
Vote.where(votable_id: @comments_ids, votable_type: 'Comment')
.select(:votable_id, :user_id)
.group_by(&:votable_id)
.transform_values { |v| v.take(10) }
``` | Can't think of an active record or SQL way of doing this.
But below is a pure Ruby solution:
For ruby 2.4 and above, you can use Hash#transform\_values on the `group_by` hash result like so (continuing from your query):
```
votes = Vote.where(votable_id: @comments_ids, votable_type:
'Comment').select(:votable_id, :user_id).group_by(&:votable_id)
top_voters = votes.transform_values do |val|
voters = val.map(&:user_id)
freq = voters.reduce(Hash.new(0)) {|h, v| h[v] += 1; h }
sorted_votes = voters.uniq.sort_by {|elem| -freq[elem] }
sorted_votes.take(10)
end
``` |
58,723,914 | I've got a data object that was created by creating what I assume is a json object -
```
jsonobj = {}
jsonobj["recordnum"] = callpri
```
and then pushing that onto a list, as there is more than one of them -
```
myList = []
myList.append(jsonobj)
```
Then that gets passed back and forth between flask subroutines and Jinja2 templates, until it ends up a few steps later coming into the function where I need to access that data, and it comes in looking something like so -
```
techlist: [{'recordnum': '1', 'name': 'Person 1', 'phonenumber': '123-456-7890', 'email': 'person1@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '2', 'name': 'Person 2', 'phonenumber': '098-765-4321', 'email': 'person2@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '3', 'name': 'Person 3', 'phonenumber': '567-890-1234', 'email': 'person3@company.tld', 'maxnumtechs': 'ALL'}]
```
I tried a `for tech in techlist: print(tech['recordnum'])` type deal and got an error, so I started printing types for everything and it's all strings. The `for tech in techlist` is I think just splitting it all into words even, which is obviously not what I want at all.
I tried messing around with json.loads on techlist, but it complained about expecting an entry in double quotes or something along those lines. I'm totally stumped, and would really appreciate if someone could please tell me how to turn this string back into a list of dicts or a list of json objects, or whatever it takes for me to be able to iterate through the items and access specific fields.
**Response to comments about it working right:**
It's coming in as a string for me, and I think for the two of you it is working for, you're creating it as a list, so it would work correctly ... sadly, that's my problem, it's a string, not a list, so it's doing this -
```
(env) [me@box directory]$ cat test.py
techlist = "[{'recordnum': '1', 'name': 'Person 1', 'phonenumber': '123-456-7890', 'email': 'person1@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '2', 'name': 'Person 2', 'phonenumber': '098-765-4321', 'email': 'person2@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '3', 'name': 'Person 3', 'phonenumber': '567-890-1234', 'email': 'person3@company.tld', 'maxnumtechs': 'ALL'}]"
print(type(techlist))
for tech in techlist:
print(type(tech))
print(str(tech))
(env) [me@box directory]$
(env) [me@box directory]$
(env) [me@box directory]$ python test.py
<class 'str'>
<class 'str'>
[
<class 'str'>
{
<class 'str'>
'
<class 'str'>
r
<class 'str'>
e
<snip>
```
**Update:**
Trenton McKinney 's comment worked PERFECTLY, THANK YOU!! If you're so inclined as to post it as a answer I'll accept it as the solution. Thank you thank you thank you!! | 2019/11/06 | [
"https://Stackoverflow.com/questions/58723914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11274599/"
] | Something like this ?
**`Vote.group(:user_id).limit(10)`** | ```rb
table = Vote.arel_table
Vote.where(votable_id: @comments_ids, votable_type: 'Comment')
.select(:votable_id, :user_id)
.group(:votable_id, :user_id, :id)
.order('table[:votable_id].count.desc')
.limit(10)
```
This should give you a list of the top ten votes. Using vanilla ruby with the `#group_by` will take a very long time if the collection is large. Using Arel will avoid any breaking changes in Rails 6.0 where raw sql will not be permitted in queries. I would previously use `.order('COUNT(votable_id) DESC')` but that throws errors and will be disallowed in Rails 6 |
58,723,914 | I've got a data object that was created by creating what I assume is a json object -
```
jsonobj = {}
jsonobj["recordnum"] = callpri
```
and then pushing that onto a list, as there is more than one of them -
```
myList = []
myList.append(jsonobj)
```
Then that gets passed back and forth between flask subroutines and Jinja2 templates, until it ends up a few steps later coming into the function where I need to access that data, and it comes in looking something like so -
```
techlist: [{'recordnum': '1', 'name': 'Person 1', 'phonenumber': '123-456-7890', 'email': 'person1@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '2', 'name': 'Person 2', 'phonenumber': '098-765-4321', 'email': 'person2@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '3', 'name': 'Person 3', 'phonenumber': '567-890-1234', 'email': 'person3@company.tld', 'maxnumtechs': 'ALL'}]
```
I tried a `for tech in techlist: print(tech['recordnum'])` type deal and got an error, so I started printing types for everything and it's all strings. The `for tech in techlist` is I think just splitting it all into words even, which is obviously not what I want at all.
I tried messing around with json.loads on techlist, but it complained about expecting an entry in double quotes or something along those lines. I'm totally stumped, and would really appreciate if someone could please tell me how to turn this string back into a list of dicts or a list of json objects, or whatever it takes for me to be able to iterate through the items and access specific fields.
**Response to comments about it working right:**
It's coming in as a string for me, and I think for the two of you it is working for, you're creating it as a list, so it would work correctly ... sadly, that's my problem, it's a string, not a list, so it's doing this -
```
(env) [me@box directory]$ cat test.py
techlist = "[{'recordnum': '1', 'name': 'Person 1', 'phonenumber': '123-456-7890', 'email': 'person1@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '2', 'name': 'Person 2', 'phonenumber': '098-765-4321', 'email': 'person2@company.tld', 'maxnumtechs': 'ALL'}, {'recordnum': '3', 'name': 'Person 3', 'phonenumber': '567-890-1234', 'email': 'person3@company.tld', 'maxnumtechs': 'ALL'}]"
print(type(techlist))
for tech in techlist:
print(type(tech))
print(str(tech))
(env) [me@box directory]$
(env) [me@box directory]$
(env) [me@box directory]$ python test.py
<class 'str'>
<class 'str'>
[
<class 'str'>
{
<class 'str'>
'
<class 'str'>
r
<class 'str'>
e
<snip>
```
**Update:**
Trenton McKinney 's comment worked PERFECTLY, THANK YOU!! If you're so inclined as to post it as a answer I'll accept it as the solution. Thank you thank you thank you!! | 2019/11/06 | [
"https://Stackoverflow.com/questions/58723914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11274599/"
] | If the data is not too big, you can do it like this:
```
Vote.where(votable_id: @comments_ids, votable_type: 'Comment')
.select(:votable_id, :user_id)
.group_by(&:votable_id)
.transform_values { |v| v.take(10) }
``` | ```rb
table = Vote.arel_table
Vote.where(votable_id: @comments_ids, votable_type: 'Comment')
.select(:votable_id, :user_id)
.group(:votable_id, :user_id, :id)
.order('table[:votable_id].count.desc')
.limit(10)
```
This should give you a list of the top ten votes. Using vanilla ruby with the `#group_by` will take a very long time if the collection is large. Using Arel will avoid any breaking changes in Rails 6.0 where raw sql will not be permitted in queries. I would previously use `.order('COUNT(votable_id) DESC')` but that throws errors and will be disallowed in Rails 6 |
38,857,379 | I've been trying to write an interactive wrapper (for use in ipython) for a library that controls some hardware. Some calls are heavy on the IO so it makes sense to carry out the tasks in parallel. Using a ThreadPool (almost) works nicely:
```
from multiprocessing.pool import ThreadPool
class hardware():
def __init__(IPaddress):
connect_to_hardware(IPaddress)
def some_long_task_to_hardware(wtime):
wait(wtime)
result = 'blah'
return result
pool = ThreadPool(processes=4)
Threads=[]
h=[hardware(IP1),hardware(IP2),hardware(IP3),hardware(IP4)]
for tt in range(4):
task=pool.apply_async(h[tt].some_long_task_to_hardware,(1000))
threads.append(task)
alive = [True]*4
Try:
while any(alive) :
for tt in range(4): alive[tt] = not threads[tt].ready()
do_other_stuff_for_a_bit()
except:
#some command I cannot find that will stop the threads...
raise
for tt in range(4): print(threads[tt].get())
```
The problem comes if the user wants to stop the process or there is an IO error in `do_other_stuff_for_a_bit()`. Pressing `Ctrl`+`C` stops the main process but the worker threads carry on running until their current task is complete.
Is there some way to stop these threads without having to rewrite the library or have the user exit python? `pool.terminate()` and `pool.join()` that I have seen used in other examples do not seem to do the job.
The actual routine (instead of the simplified version above) uses logging and although all the worker threads are shut down at some point, I can see the processes that they started running carry on until complete (and being hardware I can see their effect by looking across the room).
This is in python 2.7.
**UPDATE:**
The solution seems to be to switch to using multiprocessing.Process instead of a thread pool. The test code I tried is to run foo\_pulse:
```
class foo(object):
def foo_pulse(self,nPulse,name): #just one method of *many*
print('starting pulse for '+name)
result=[]
for ii in range(nPulse):
print('on for '+name)
time.sleep(2)
print('off for '+name)
time.sleep(2)
result.append(ii)
return result,name
```
If you try running this using ThreadPool then ctrl-C does not stop foo\_pulse from running (even though it does kill the threads right away, the print statements keep on coming:
```
from multiprocessing.pool import ThreadPool
import time
def test(nPulse):
a=foo()
pool=ThreadPool(processes=4)
threads=[]
for rn in range(4) :
r=pool.apply_async(a.foo_pulse,(nPulse,'loop '+str(rn)))
threads.append(r)
alive=[True]*4
try:
while any(alive) : #wait until all threads complete
for rn in range(4):
alive[rn] = not threads[rn].ready()
time.sleep(1)
except : #stop threads if user presses ctrl-c
print('trying to stop threads')
pool.terminate()
print('stopped threads') # this line prints but output from foo_pulse carried on.
raise
else :
for t in threads : print(t.get())
```
However a version using multiprocessing.Process works as expected:
```
import multiprocessing as mp
import time
def test_pro(nPulse):
pros=[]
ans=[]
a=foo()
for rn in range(4) :
q=mp.Queue()
ans.append(q)
r=mp.Process(target=wrapper,args=(a,"foo_pulse",q),kwargs={'args':(nPulse,'loop '+str(rn))})
r.start()
pros.append(r)
try:
for p in pros : p.join()
print('all done')
except : #stop threads if user stops findRes
print('trying to stop threads')
for p in pros : p.terminate()
print('stopped threads')
else :
print('output here')
for q in ans :
print(q.get())
print('exit time')
```
Where I have defined a wrapper for the library foo (so that it did not need to be re-written). If the return value is not needed the neither is this wrapper :
```
def wrapper(a,target,q,args=(),kwargs={}):
'''Used when return value is wanted'''
q.put(getattr(a,target)(*args,**kwargs))
```
From the documentation I see no reason why a pool would not work (other than a bug). | 2016/08/09 | [
"https://Stackoverflow.com/questions/38857379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6353772/"
] | This is a very interesting use of parallelism.
However, if you are using `multiprocessing`, the goal is to have many processes running in parallel, as opposed to one process running many threads.
Consider these few changes to implement it using `multiprocessing`:
You have these functions that will run in parallel:
```
import time
import multiprocessing as mp
def some_long_task_from_library(wtime):
time.sleep(wtime)
class MyException(Exception): pass
def do_other_stuff_for_a_bit():
time.sleep(5)
raise MyException("Something Happened...")
```
Let's create and start the processes, say 4:
```
procs = [] # this is not a Pool, it is just a way to handle the
# processes instead of calling them p1, p2, p3, p4...
for _ in range(4):
p = mp.Process(target=some_long_task_from_library, args=(1000,))
p.start()
procs.append(p)
mp.active_children() # this joins all the started processes, and runs them.
```
The processes are running in parallel, presumably in a separate cpu core, but that is to the OS to decide. You can check in your system monitor.
In the meantime you run a process that will break, and you want to stop the running processes, not leaving them orphan:
```
try:
do_other_stuff_for_a_bit()
except MyException as exc:
print(exc)
print("Now stopping all processes...")
for p in procs:
p.terminate()
print("The rest of the process will continue")
```
If it doesn't make sense to continue with the main process when one or all of the subprocesses have terminated, you should handle the exit of the main program.
Hope it helps, and you can adapt bits of this for your library. | In answer to the question of why pool did not work then this is due to (as quoted in the [Documentation](https://docs.python.org/3.1/library/multiprocessing.html)) then **main** needs to be importable by the child processes and due to the nature of this project interactive python is being used.
At the same time it was not clear why ThreadPool would - although the clue is right there in the name. ThreadPool creates its pool of worker processes using multiprocessing.dummy which as noted [here](https://stackoverflow.com/questions/26432411/multiprocessing-dummy-in-python) is just a wrapper around the Threading module. Pool uses the multiprocessing.Process. This can be seen by this test:
```
p=ThreadPool(processes=3)
p._pool[0]
<DummyProcess(Thread23, started daemon 12345)> #no terminate() method
p=Pool(processes=3)
p._pool[0]
<Process(PoolWorker-1, started daemon)> #has handy terminate() method if needed
```
As threads do not have a terminate method the worker threads carry on running until they have completed their current task. Killing threads is messy (which is why I tried to use the multiprocessing module) but solutions are [here](https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python).
The one warning about the solution using the above:
```
def wrapper(a,target,q,args=(),kwargs={}):
'''Used when return value is wanted'''
q.put(getattr(a,target)(*args,**kwargs))
```
is that changes to attributes inside the instance of the object are not passed back up to the main program. As an example the class foo above can also have methods such as:
def addIP(newIP):
self.hardwareIP=newIP
A call to `r=mp.Process(target=a.addIP,args=(127.0.0.1))` does not update `a`.
The only way round this for a complex object seems to be shared memory using a custom `manager` which can give access to both the methods and attributes of object `a` For a very large complex object based on a library this may be best done using `dir(foo)` to populate the manager. If I can figure out how I'll update this answer with an example (for my future self as much as others). |
38,857,379 | I've been trying to write an interactive wrapper (for use in ipython) for a library that controls some hardware. Some calls are heavy on the IO so it makes sense to carry out the tasks in parallel. Using a ThreadPool (almost) works nicely:
```
from multiprocessing.pool import ThreadPool
class hardware():
def __init__(IPaddress):
connect_to_hardware(IPaddress)
def some_long_task_to_hardware(wtime):
wait(wtime)
result = 'blah'
return result
pool = ThreadPool(processes=4)
Threads=[]
h=[hardware(IP1),hardware(IP2),hardware(IP3),hardware(IP4)]
for tt in range(4):
task=pool.apply_async(h[tt].some_long_task_to_hardware,(1000))
threads.append(task)
alive = [True]*4
Try:
while any(alive) :
for tt in range(4): alive[tt] = not threads[tt].ready()
do_other_stuff_for_a_bit()
except:
#some command I cannot find that will stop the threads...
raise
for tt in range(4): print(threads[tt].get())
```
The problem comes if the user wants to stop the process or there is an IO error in `do_other_stuff_for_a_bit()`. Pressing `Ctrl`+`C` stops the main process but the worker threads carry on running until their current task is complete.
Is there some way to stop these threads without having to rewrite the library or have the user exit python? `pool.terminate()` and `pool.join()` that I have seen used in other examples do not seem to do the job.
The actual routine (instead of the simplified version above) uses logging and although all the worker threads are shut down at some point, I can see the processes that they started running carry on until complete (and being hardware I can see their effect by looking across the room).
This is in python 2.7.
**UPDATE:**
The solution seems to be to switch to using multiprocessing.Process instead of a thread pool. The test code I tried is to run foo\_pulse:
```
class foo(object):
def foo_pulse(self,nPulse,name): #just one method of *many*
print('starting pulse for '+name)
result=[]
for ii in range(nPulse):
print('on for '+name)
time.sleep(2)
print('off for '+name)
time.sleep(2)
result.append(ii)
return result,name
```
If you try running this using ThreadPool then ctrl-C does not stop foo\_pulse from running (even though it does kill the threads right away, the print statements keep on coming:
```
from multiprocessing.pool import ThreadPool
import time
def test(nPulse):
a=foo()
pool=ThreadPool(processes=4)
threads=[]
for rn in range(4) :
r=pool.apply_async(a.foo_pulse,(nPulse,'loop '+str(rn)))
threads.append(r)
alive=[True]*4
try:
while any(alive) : #wait until all threads complete
for rn in range(4):
alive[rn] = not threads[rn].ready()
time.sleep(1)
except : #stop threads if user presses ctrl-c
print('trying to stop threads')
pool.terminate()
print('stopped threads') # this line prints but output from foo_pulse carried on.
raise
else :
for t in threads : print(t.get())
```
However a version using multiprocessing.Process works as expected:
```
import multiprocessing as mp
import time
def test_pro(nPulse):
pros=[]
ans=[]
a=foo()
for rn in range(4) :
q=mp.Queue()
ans.append(q)
r=mp.Process(target=wrapper,args=(a,"foo_pulse",q),kwargs={'args':(nPulse,'loop '+str(rn))})
r.start()
pros.append(r)
try:
for p in pros : p.join()
print('all done')
except : #stop threads if user stops findRes
print('trying to stop threads')
for p in pros : p.terminate()
print('stopped threads')
else :
print('output here')
for q in ans :
print(q.get())
print('exit time')
```
Where I have defined a wrapper for the library foo (so that it did not need to be re-written). If the return value is not needed the neither is this wrapper :
```
def wrapper(a,target,q,args=(),kwargs={}):
'''Used when return value is wanted'''
q.put(getattr(a,target)(*args,**kwargs))
```
From the documentation I see no reason why a pool would not work (other than a bug). | 2016/08/09 | [
"https://Stackoverflow.com/questions/38857379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6353772/"
] | This is a very interesting use of parallelism.
However, if you are using `multiprocessing`, the goal is to have many processes running in parallel, as opposed to one process running many threads.
Consider these few changes to implement it using `multiprocessing`:
You have these functions that will run in parallel:
```
import time
import multiprocessing as mp
def some_long_task_from_library(wtime):
time.sleep(wtime)
class MyException(Exception): pass
def do_other_stuff_for_a_bit():
time.sleep(5)
raise MyException("Something Happened...")
```
Let's create and start the processes, say 4:
```
procs = [] # this is not a Pool, it is just a way to handle the
# processes instead of calling them p1, p2, p3, p4...
for _ in range(4):
p = mp.Process(target=some_long_task_from_library, args=(1000,))
p.start()
procs.append(p)
mp.active_children() # this joins all the started processes, and runs them.
```
The processes are running in parallel, presumably in a separate cpu core, but that is to the OS to decide. You can check in your system monitor.
In the meantime you run a process that will break, and you want to stop the running processes, not leaving them orphan:
```
try:
do_other_stuff_for_a_bit()
except MyException as exc:
print(exc)
print("Now stopping all processes...")
for p in procs:
p.terminate()
print("The rest of the process will continue")
```
If it doesn't make sense to continue with the main process when one or all of the subprocesses have terminated, you should handle the exit of the main program.
Hope it helps, and you can adapt bits of this for your library. | If for some reasons using threads is preferable, we can use [this](https://cuyu.github.io/python/2016/08/15/Terminate-multiprocess-in-Python-correctly-and-gracefully).
>
> We can send some siginal to the threads we want to terminate. The simplest siginal is global variable:
>
>
>
```
import time
from multiprocessing.pool import ThreadPool
_FINISH = False
def hang():
while True:
if _FINISH:
break
print 'hanging..'
time.sleep(10)
def main():
global _FINISH
pool = ThreadPool(processes=1)
pool.apply_async(hang)
time.sleep(10)
_FINISH = True
pool.terminate()
pool.join()
print 'main process exiting..'
if __name__ == '__main__':
main()
``` |
67,625,060 | I am following the tutorial of driverless: Driverless AI Standalone Python Scoring Pipeline, you can check it in the following link:
<http://docs.h2o.ai/driverless-ai/latest-stable/docs/userguide/scoring-standalone-python.html#tar-method-py>
I am performing:
**Running Python Scoring Process - Recommended**
but, when running the last step:
**DRIVERLESS\_AI\_LICENSE\_KEY = "pastekey here" SCORING\_PIPELINE\_INSTALL\_DEPENDENCIES = 0 /path/to/your/dai-env.sh ./run\_example.sh**
the following error happens:
>
> Traceback (most recent call last): File "example.py", line 7, in
>
> from scoring\_h2oai\_experiment\_5fd7ff9c\_b11a\_11eb\_b91f\_0242ac110002 import Scorer File
> "/usr/local/lib/python3.6/dist-packages/scoring\_h2oai\_experiment\_5fd7ff9c\_b11a\_11eb\_b91f\_0242ac110002/**init**.py",
> line 1, in
>
>
>
> ```
> from .scorer import Scorer File "/usr/local/lib/python3.6/dist-packages/scoring_h2oai_experiment_5fd7ff9c_b11a_11eb_b91f_0242ac110002/scorer.py",
>
> ```
>
> line 7, in
>
>
>
> ```
> from h2oaicore import application_context
>
> ```
>
> ModuleNotFoundError: No module named 'h2oaicore'
>
>
>
--
Hope you can help me, thanks in advance. | 2021/05/20 | [
"https://Stackoverflow.com/questions/67625060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15984094/"
] | In jQuery `val` is a method not a property so it needs to be `.val()`, not `.val`. Also, to read the selected value call `val()` on the `select` element directly, not on the collection of all available `option` elements. Try this:
```js
$(document).ready(function() {
var tipo = $("select").val();
if (tipo != 'Tutti') {
console.log('ciao');
} else {
console.log('Addio');
}
});
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="inputState" class="btn btn-outline-secondary" name="sesso">
<option class="dropdown-item" value="Tutti">Tutti</option>
<option class="dropdown-item" value="Confezionati">Confezionati</option>
</select>
``` | The other answers are sufficient if you only need the selected `value` however if you do need to access the selected `<option>` directly and it's properties/attributes you can use the `filter(':selected')` method on the collection of matched elements.
Below I demonstrate accessing the data of the selected option, on page load and whenever the selected option changes.
```js
$(document).ready(function() {
const $inputState = $('#inputState')
$inputState.change(function() {
// value of <select>
let theValue = $(this).val()
console.log("select value:", theValue)
// first selected <option> element
let $selectedOption = $(this).find('option').filter(':selected').first()
console.log("option value:", $selectedOption.val())
console.log("option data:", $selectedOption.data())
})
// trigger change on load
$inputState.change()
});
```
```html
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<select id="inputState" class="btn btn-outline-secondary" name="sesso">
<option class="dropdown-item" value="Tutti" data-option="14">Tutti</option>
<option class="dropdown-item" value="Confezionati" selected data-option="option data">Confezionati</option>
</select>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
``` |
67,625,060 | I am following the tutorial of driverless: Driverless AI Standalone Python Scoring Pipeline, you can check it in the following link:
<http://docs.h2o.ai/driverless-ai/latest-stable/docs/userguide/scoring-standalone-python.html#tar-method-py>
I am performing:
**Running Python Scoring Process - Recommended**
but, when running the last step:
**DRIVERLESS\_AI\_LICENSE\_KEY = "pastekey here" SCORING\_PIPELINE\_INSTALL\_DEPENDENCIES = 0 /path/to/your/dai-env.sh ./run\_example.sh**
the following error happens:
>
> Traceback (most recent call last): File "example.py", line 7, in
>
> from scoring\_h2oai\_experiment\_5fd7ff9c\_b11a\_11eb\_b91f\_0242ac110002 import Scorer File
> "/usr/local/lib/python3.6/dist-packages/scoring\_h2oai\_experiment\_5fd7ff9c\_b11a\_11eb\_b91f\_0242ac110002/**init**.py",
> line 1, in
>
>
>
> ```
> from .scorer import Scorer File "/usr/local/lib/python3.6/dist-packages/scoring_h2oai_experiment_5fd7ff9c_b11a_11eb_b91f_0242ac110002/scorer.py",
>
> ```
>
> line 7, in
>
>
>
> ```
> from h2oaicore import application_context
>
> ```
>
> ModuleNotFoundError: No module named 'h2oaicore'
>
>
>
--
Hope you can help me, thanks in advance. | 2021/05/20 | [
"https://Stackoverflow.com/questions/67625060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15984094/"
] | You are using val as property and it is a method.
```js
$(document).ready(function(){
var tipo = $("select").find("option").val();
if (tipo != 'Tutti'){
console.log($(this).find("option").val());
console.log('ciao');
}else{
console.log('Addio');
}
});
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="inputState" class="btn btn-outline-secondary" name="sesso">
<option class="dropdown-item" value="Tutti">Tutti</option>
<option class="dropdown-item" value="Confezionati">Confezionati</option>
</select>
``` | The other answers are sufficient if you only need the selected `value` however if you do need to access the selected `<option>` directly and it's properties/attributes you can use the `filter(':selected')` method on the collection of matched elements.
Below I demonstrate accessing the data of the selected option, on page load and whenever the selected option changes.
```js
$(document).ready(function() {
const $inputState = $('#inputState')
$inputState.change(function() {
// value of <select>
let theValue = $(this).val()
console.log("select value:", theValue)
// first selected <option> element
let $selectedOption = $(this).find('option').filter(':selected').first()
console.log("option value:", $selectedOption.val())
console.log("option data:", $selectedOption.data())
})
// trigger change on load
$inputState.change()
});
```
```html
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<select id="inputState" class="btn btn-outline-secondary" name="sesso">
<option class="dropdown-item" value="Tutti" data-option="14">Tutti</option>
<option class="dropdown-item" value="Confezionati" selected data-option="option data">Confezionati</option>
</select>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
``` |
65,047,093 | I need to write a python function that takes a string, and uses REGEX to check if the string contains:
1. At least 1 uppercase letter;
2. At least 2 numerical digits;
3. Exactly 2 special characters, !@#$&\*-\_.
4. A length of 6-8 characters;
Returns true if these exist and false otherwise. I'm good with the function, however, I'm having trouble with the regular expression.
What I have so far is: `[A-Z]+\d{2,}[!@#\$&\*-_\.]{2}`
I know this doesn't work, I'm really confused since I'm new to regex.
Thanks for your help! | 2020/11/28 | [
"https://Stackoverflow.com/questions/65047093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14602241/"
] | You can use
```
^(?=[^A-Z\r\n]*[A-Z])(?=[^\d\r\n]*\d[^\d\r\n]*\d)(?=.{6,8}$)[A-Z\d]*[!@#$&*_.-][A-Z\d]*[!@#$&*_.-][A-Z\d]*$
```
Note to escape the `\-` in the character class or place it at the start or end. Else it would denote a range.
**Explanation**
* `^` Start of string
* `(?=[^A-Z\r\n]*[A-Z])` Positive lookahead, assert a char A-Z
* `(?=[^\d\r\n]*\d[^\d\r\n]*\d)` Positive lookahead, assert 2 digits
* `(?=.{6,8}$)` Positive lookahead, assert 6 - 8 characters in total
* `[A-Z\d]*[!@#$&*_.-][A-Z\d]*[!@#$&*_.-][A-Z\d]*` Match 2 "special" characters
* `$` End of string (Or use `\Z` if there can no newline following)
[Regex demo](https://regex101.com/r/UBucd5/1) | This regex should work for you in python
```
^(?=.*[A-Z])(?=.*[0-9].*[0-9])(?=.*[!@#$%^&*()_+,.\\\/;':\"-].*[!@#$%^&*()_+,.\\\/;':\"-]).{6,8}$
```
Here is the test run in [regex101](https://regex101.com/r/iE4Q6F/3) |
38,577,719 | I used a bat to run a python script, and after 30 minutes it killed the process and reopened it. How can i make it in a Fedora linux sh? I used this:
```
title StartWorker 2
:loop
start "PYworker2" /i python worker.py -st 10
timeout /t 1800 >null
taskkill /fi "WINDOWTITLE EQ PYworker2"
goto loop
``` | 2016/07/25 | [
"https://Stackoverflow.com/questions/38577719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6637034/"
] | Try replacing the `console.log(graph);` call with:
```
lineReader.on('close', function () {
console.log(graph);
});
```
You see the empty object because your `log` happens before the file is read, as reading is `async`. | What you have there is some asynchronous code which you expect to be called completely synchroonously. First, you open the file, then the single lines are read (asynchronously) and for every line your seperate callback function (`lineReader.on('line', func);`) would be called asynchronously but all that has happened so far, is that the event was registered. Then, (before your callback was even executed once), you log the graph.
All you need to do is add an eventlistener for the end of your reader which should look something like so:
```
lineReader.on('close', function() {
console.log(graph);
}
```
Note that I haven't used these functions myself but this is what your problem looks like to me. Let me know if this works! |
48,621,750 | I'm trying to read json from a text file. I can convert the text file to json but some times it throws this error for some json data. `Extra data: line 2 column 1 (char 876): JSONDecodeError`.
Here is the error stacktrace.
```
Extra data: line 2 column 1 (char 876): JSONDecodeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 28, in lambda_handler
d = json.loads(got_text)
File "/var/lang/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/var/lang/lib/python3.6/json/decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 876)
```
Here is the code.
```
retr = s3_client.get_object(Bucket=bucket, Key=key)
bytestream = BytesIO(retr['Body'].read())
got_text = GzipFile(mode='rb', fileobj=bytestream).read().decode('utf-8')
print(got_text)
d = json.loads(got_text)
print("json output")
print(d)
```
Here is the json.
```
{
"_metadata": {
"bundled": [
"Segment.io"
],
"unbundled": []
},
"anonymousId": "98cc0c53-jkhjkhj-42d5-8ee1-08a6d6f4e774",
"context": {
"library": {
"name": "analytics.js",
"version": "3.2.5"
},
"page": {
"path": "/login",
"referrer": "http://localhost:8000/",
"search": "",
"title": "Sign in or Register | Your Platform Name Here",
"url": "http://localhost:8000/login"
},
"userAgent": "Mozilla/5.0 ",
"ip": "67.67.88.68"
},
"integrations": {},
"messageId": "ajs-dfbdfbdfbdb",
"properties": {
"path": "/login",
"referrer": "http://localhost:8000/",
"search": "",
"title": "Sign in or Register | Your Platform Name Here",
"url": "http://localhost:8000/login"
},
"receivedAt": "2018-02-05T09:21:02.539Z",
"sentAt": "2018-02-05T09:21:02.413Z",
"timestamp": "2018-02-05T09:21:02.535Z",
"type": "page",
"userId": "16",
"channel": "client",
"originalTimestamp": "2018-02-05T09:21:02.409Z",
"projectId": "dfbfbdfb",
"version": 2
}
```
What could be the problem? | 2018/02/05 | [
"https://Stackoverflow.com/questions/48621750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287157/"
] | Look like you have bad quotes in your JSON data. Just replace the invalid quotes with valid quotes and then convert it to a JSON object.
```
import json
d = '''{
"_metadata": {
"bundled": [
"Segment.io"
],
"unbundled": []
},
"anonymousId": "98cc0c53-jkhjkhj-42d5-8ee1-08a6d6f4e774",
"context": {
"library": {
"name": "analytics.js",
"version": "3.2.5"
},
"page": {
"path": "/login",
"referrer": "http://localhost:8000/",
"search": "",
"title": "Sign in or Register | Your Platform Name Here",
"url": "http://localhost:8000/login"
},
"userAgent": "Mozilla/5.0 ",
"ip": “67.67.688.68”
},
"integrations": {},
"messageId": "ajs-dfbdfbdfbdb”,
"properties": {
"path": "/login",
"referrer": "http://localhost:8000/",
"search": "",
"title": "Sign in or Register | Your Platform Name Here",
"url": "http://localhost:8000/login"
},
"receivedAt": "2018-02-05T09:21:02.539Z",
"sentAt": "2018-02-05T09:21:02.413Z",
"timestamp": "2018-02-05T09:21:02.535Z",
"type": "page",
"userId": "16",
"channel": "client",
"originalTimestamp": "2018-02-05T09:21:02.409Z",
"projectId": “dfbfbdfb”,
"version": 2
}
'''
d = d.replace("“", '"').replace("”", '"')
print json.loads(d)
```
**Output:**
```
{u'projectId': u'dfbfbdfb', u'timestamp': u'2018-02-05T09:21:02.535Z', u'version': 2, u'userId': u'16', u'integrations': {}, u'receivedAt': u'2018-02-05T09:21:02.539Z', u'_metadata': {u'bundled': [u'Segment.io'], u'unbundled': []}, u'anonymousId': u'98cc0c53-jkhjkhj-42d5-8ee1-08a6d6f4e774', u'originalTimestamp': u'2018-02-05T09:21:02.409Z', u'context': {u'userAgent': u'Mozilla/5.0 ', u'page': {u'url': u'http://localhost:8000/login', u'path': u'/login', u'search': u'', u'title': u'Sign in or Register | Your Platform Name Here', u'referrer': u'http://localhost:8000/'}, u'library': {u'version': u'3.2.5', u'name': u'analytics.js'}, u'ip': u'67.67.688.68'}, u'messageId': u'ajs-dfbdfbdfbdb', u'type': u'page', u'properties': {u'url': u'http://localhost:8000/login', u'path': u'/login', u'search': u'', u'title': u'Sign in or Register | Your Platform Name Here', u'referrer': u'http://localhost:8000/'}, u'channel': u'client', u'sentAt': u'2018-02-05T09:21:02.413Z'}
```
**In your case**
```
got_text = got_text.replace("“", '"').replace("”", '"')
d = json.loads(got_text)
``` | Pay attention to several strings that you have. JSON doesn't support `”` quotes that sometime appear in your JSON.
Lines with wrong quotes:
```
"projectId":“dfbfbdfb”,
"messageId":"ajs-dfbdfbdfbdb”,
"ip":“67.67.688.68”
```
Here is fixed JSON:
```
{
"_metadata": {
"bundled": [
"Segment.io"
],
"unbundled": []
},
"anonymousId": "98cc0c53-jkhjkhj-42d5-8ee1-08a6d6f4e774",
"context": {
"library": {
"name": "analytics.js",
"version": "3.2.5"
},
"page": {
"path": "/login",
"referrer": "http://localhost:8000/",
"search": "",
"title": "Sign in or Register | Your Platform Name Here",
"url": "http://localhost:8000/login"
},
"userAgent": "Mozilla/5.0 ",
"ip": "67.67.688.68"
},
"integrations": {},
"messageId": "ajs-dfbdfbdfbdb",
"properties": {
"path": "/login",
"referrer": "http://localhost:8000/",
"search": "",
"title": "Sign in or Register | Your Platform Name Here",
"url": "http://localhost:8000/login"
},
"receivedAt": "2018-02-05T09:21:02.539Z",
"sentAt": "2018-02-05T09:21:02.413Z",
"timestamp": "2018-02-05T09:21:02.535Z",
"type": "page",
"userId": "16",
"channel": "client",
"originalTimestamp": "2018-02-05T09:21:02.409Z",
"projectId": "dfbfbdfb",
"version": 2
}
``` |
37,926,746 | I would like to use a `ColorFunction` similar to that in [Mathematica](https://reference.wolfram.com/language/ref/ColorFunction.html) for my plots in python.
In other words, I would like to call `pyplot.plot(x, y, color=c)`, where `c` is a vector, defining the color of each data point.
Is there any way to achieve this using the matplotlib library? | 2016/06/20 | [
"https://Stackoverflow.com/questions/37926746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2670010/"
] | To the best of my knowledge, there is no equivalent in Matplotlib, but we can get the similar result following two steps: draw points with varied colors and draw the line.
Here is a demo.
[](https://i.stack.imgur.com/OaquV.png)
---
The source code,
```
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import random
fig, ax = plt.subplots()
nrof_points = 100
x = np.linspace(0, 10, nrof_points)
y = np.sin(x)
colors = cm.rainbow(np.linspace(0, 1, nrof_points)) # generate a bunch of colors
# draw points
for idx, point in enumerate(zip(x, y)):
ax.plot(point[0], point[1], 'o', color=colors[idx], markersize=10)
# draw the line
ax.plot(x, y, 'k')
plt.grid()
plt.show()
``` | While I agree with @SparkAndShine that there is no way to parameterize the color of *one* line, it is possible to color many lines to create a visual effect that is largely the same. This is at the heart of a demo in the [MatPlotLib documentation](https://matplotlib.org/3.2.1/gallery/lines_bars_and_markers/multicolored_line.html). However, this demo is not the simplest implementation of this principle. Here is an alternate demo based on @SparkAndShine's response:
[colored sine](https://i.stack.imgur.com/lRm4b.png) (can't post as image since I don't have the reputation)
---
Source code:
```
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
fig, ax = plt.subplots()
nrof_points = 100
x = np.linspace(0, 10, nrof_points)
y = np.sin(x)
colors = cm.rainbow(np.linspace(0, 1, nrof_points)) # generate a bunch of colors
# draw points
for idx in range(0,np.shape(x)[0]-2,1):
ax.plot(x[idx:idx+1+1], y[idx:idx+1+1], color=colors[idx])
# add a grid and show
plt.grid()
plt.show()
``` |
57,605,720 | I have two dictionaries. In reality they are much longer.
First:
```py
Data = { "AT" : [1,2,3,4], "BE" : [ 4,2,1,6], "DE" : [ 5,7,8,9] }
```
2nd dict:
```py
Data2 = { "AT" : ["AT1","AT2","AT3"], "BE" : ["BE1","BE2","BE3"], "DE" : ["DE1","DE2","DE3","DE4","DE5"] }
```
I now want a dictionary that assigns the values of the first to the values
of the 2nd dictionary (the values of the 2nd dictionary are the new keys.)
Something like:
```py
Result = { "AT1" : [1,2,3,4], "AT2" : [1,2,3,4], "AT3" : [1,2,3,4], "BE1" : [4,2,1,6], "BE2" : [4,2,1,6] and so on... }
```
I tried:
```py
search= {k : v for k, v in Data.itervalues()}
result = {search[v]: k for v in Data2.itervalues() for k in Data.itervalues()}
print(result)
```
I get a too many values to unpack error and despite that im not quite sure if this does what i want it to do :/
Error:
```
Traceback (most recent call last):
File "<ipython-input-18-e4ca3008cc18>", line 17, in <module>
search= {k : v for k, v in Data.itervalues()}
File "<ipython-input-18-e4ca3008cc18>", line 17, in <dictcomp>
search= {k : v for k, v in Data.itervalues()}
ValueError: too many values to unpack
```
Thanks for any help in advance. | 2019/08/22 | [
"https://Stackoverflow.com/questions/57605720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11873507/"
] | Here is a way to do it using a dictionary comprehension :
```
result = {y : Data[x] for x in Data2 for y in Data2[x]}
```
---
Output :
```
{'AT1': [1, 2, 3, 4],
'AT2': [1, 2, 3, 4],
'AT3': [1, 2, 3, 4],
'BE1': [4, 2, 1, 6],
'BE2': [4, 2, 1, 6],
'BE3': [4, 2, 1, 6],
'DE1': [5, 7, 8, 9],
'DE2': [5, 7, 8, 9],
'DE3': [5, 7, 8, 9],
'DE4': [5, 7, 8, 9],
'DE5': [5, 7, 8, 9]}
``` | Way without using comprehension.
```
result = {}
for k,v in Data2.items():
for _v in v:
result[_v]=Data[k]
print(result)
``` |
17,267,140 | Im new to python so please forgive my Noob-ness. Im trying to create a status bar at the bottom of my app window, but it seems every time I use the pack() and grid() methods together in the same file, the main app window doesn't open. When I comment out the line that says statusbar.pack(side = BOTTOM, fill = X) my app window opens up fine but if I leave it in it doesn't, and also if I comment out any lines that use the grid method the window opens with the status bar. It seems like I can only use either pack() or grid() but not both. I know I should be able to use both methods. Any suggestions? Here's the code:
```
from Tkinter import *
import tkMessageBox
def Quit():
answer = tkMessageBox.askokcancel('Quit', 'Are you sure?')
if answer:
app.destroy()
app = Tk()
app.geometry('700x500+400+200')
app.title('Title')
label_1 = Label(text = "Enter number")
label_1.grid(row = 0, column = 0)
text_box1 = DoubleVar()
input1 = Entry(app, textvariable = text_box1)
input1.grid(row = 0, column = 2)
statusbar = Label(app, text = "", bd = 1, relief = SUNKEN, anchor = W)
statusbar.pack(side = BOTTOM, fill = X)
startButton = Button(app, text = "Start", command = StoreValues).grid(row = 9, column = 2, padx = 15, pady = 15)
app.mainloop()
```
Any help is appreciated! Thanks! | 2013/06/24 | [
"https://Stackoverflow.com/questions/17267140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725494/"
] | You cannot use both `pack` and `grid` on widgets that have the same master. The first one will adjust the size of the widget. The other will see the change, and resize everything to fit it's own constraints. The first will see these changes and resize everything again to fit *its* constraints. The other will see the changes, and so on ad infinitum. They will be stuck in an eternal struggle for supremacy.
While it is technically possible if you really, *really* know what you're doing, for all intents and purposes you can't mix them *in the same container*. You can mix them all you want in your app as a whole, but for a given container (typically, a frame), you can use only one to manage the direct contents of the container.
A very common technique is to divide your GUI into pieces. In your case you have a bottom statusbar, and a top "main" area. So, pack the statusbar along the bottom and create a frame that you pack above it for the main part of the GUI. Then, everything else has the main frame as its parent, and inside that frame you can use grid or pack or whatever you want. | Yeah thats right. In following example, i have divided my program into 2 frames. frame1 caters towards menu/toolbar and uses pack() methods wherein frame2 is used to make login page credentials and uses grid() methods.
```
from tkinter import *
def donothing():
print ('IT WORKED')
root=Tk()
root.title(string='LOGIN PAGE')
frame1=Frame(root)
frame1.pack(side=TOP,fill=X)
frame2=Frame(root)
frame2.pack(side=TOP, fill=X)
m=Menu(frame1)
root.config(menu=m)
submenu=Menu(m)
m.add_cascade(label='File',menu=submenu)
submenu.add_command(label='New File', command=donothing)
submenu.add_command(label='Open', command=donothing)
submenu.add_separator()
submenu.add_command(label='Exit', command=frame1.quit)
editmenu=Menu(m)
m.add_cascade(label='Edit', menu=editmenu)
editmenu.add_command(label='Cut',command=donothing)
editmenu.add_command(label='Copy',command=donothing)
editmenu.add_command(label='Paste',command=donothing)
editmenu.add_separator()
editmenu.add_command(label='Exit', command=frame1.quit)
# **** ToolBar *******
toolbar=Frame(frame1,bg='grey')
toolbar.pack(side=TOP,fill=X)
btn1=Button(toolbar, text='Print', command=donothing)
btn2=Button(toolbar, text='Paste', command=donothing)
btn3=Button(toolbar, text='Cut', command=donothing)
btn4=Button(toolbar, text='Copy', command=donothing)
btn1.pack(side=LEFT,padx=2)
btn2.pack(side=LEFT,padx=2)
btn3.pack(side=LEFT,padx=2)
btn4.pack(side=LEFT,padx=2)
# ***** LOGIN CREDENTIALS ******
label=Label(frame2,text='WELCOME TO MY PAGE',fg='red',bg='white')
label.grid(row=3,column=1)
label1=Label(frame2,text='Name')
label2=Label(frame2,text='Password')
label1.grid(row=4,column=0,sticky=E)
label2.grid(row=5,column=0,sticky=E)
entry1=Entry(frame2)
entry2=Entry(frame2)
entry1.grid(row=4,column=1)
entry2.grid(row=5,column=1)
chk=Checkbutton(frame2,text='KEEP ME LOGGED IN')
chk.grid(row=6,column=1)
btn=Button(frame2,text='SUBMIT')
btn.grid(row=7,column=1)
# **** StatusBar ******************
status= Label(root,text='Loading',bd=1,relief=SUNKEN,anchor=W)
status.pack(side=BOTTOM, fill=X)
``` |
17,267,140 | Im new to python so please forgive my Noob-ness. Im trying to create a status bar at the bottom of my app window, but it seems every time I use the pack() and grid() methods together in the same file, the main app window doesn't open. When I comment out the line that says statusbar.pack(side = BOTTOM, fill = X) my app window opens up fine but if I leave it in it doesn't, and also if I comment out any lines that use the grid method the window opens with the status bar. It seems like I can only use either pack() or grid() but not both. I know I should be able to use both methods. Any suggestions? Here's the code:
```
from Tkinter import *
import tkMessageBox
def Quit():
answer = tkMessageBox.askokcancel('Quit', 'Are you sure?')
if answer:
app.destroy()
app = Tk()
app.geometry('700x500+400+200')
app.title('Title')
label_1 = Label(text = "Enter number")
label_1.grid(row = 0, column = 0)
text_box1 = DoubleVar()
input1 = Entry(app, textvariable = text_box1)
input1.grid(row = 0, column = 2)
statusbar = Label(app, text = "", bd = 1, relief = SUNKEN, anchor = W)
statusbar.pack(side = BOTTOM, fill = X)
startButton = Button(app, text = "Start", command = StoreValues).grid(row = 9, column = 2, padx = 15, pady = 15)
app.mainloop()
```
Any help is appreciated! Thanks! | 2013/06/24 | [
"https://Stackoverflow.com/questions/17267140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725494/"
] | You cannot use both `pack` and `grid` on widgets that have the same master. The first one will adjust the size of the widget. The other will see the change, and resize everything to fit it's own constraints. The first will see these changes and resize everything again to fit *its* constraints. The other will see the changes, and so on ad infinitum. They will be stuck in an eternal struggle for supremacy.
While it is technically possible if you really, *really* know what you're doing, for all intents and purposes you can't mix them *in the same container*. You can mix them all you want in your app as a whole, but for a given container (typically, a frame), you can use only one to manage the direct contents of the container.
A very common technique is to divide your GUI into pieces. In your case you have a bottom statusbar, and a top "main" area. So, pack the statusbar along the bottom and create a frame that you pack above it for the main part of the GUI. Then, everything else has the main frame as its parent, and inside that frame you can use grid or pack or whatever you want. | For single widgets, the answer is no: you cannot use both `pack()` and `grid()` inside one widget. But you can use both for different widgets, even if they are all inside the same widget. For instance:
```py
my_canvas=tk.Canvas(window1,width=540,height=420,bd=0)
my_canvas.create_image(270,210,image=bg,anchor="center")
my_canvas.pack(fill="both",expand=True)
originallbl = tk.Label(my_canvas, text="Original", width=15).grid(row=1,column=1)
original = tk.Entry(my_canvas, width=15).grid(row=1,column=2)
```
I used `pack()` in order to set canvas, I used `grid()` in order to set labels, buttons, etc. in the same canvas |
17,267,140 | Im new to python so please forgive my Noob-ness. Im trying to create a status bar at the bottom of my app window, but it seems every time I use the pack() and grid() methods together in the same file, the main app window doesn't open. When I comment out the line that says statusbar.pack(side = BOTTOM, fill = X) my app window opens up fine but if I leave it in it doesn't, and also if I comment out any lines that use the grid method the window opens with the status bar. It seems like I can only use either pack() or grid() but not both. I know I should be able to use both methods. Any suggestions? Here's the code:
```
from Tkinter import *
import tkMessageBox
def Quit():
answer = tkMessageBox.askokcancel('Quit', 'Are you sure?')
if answer:
app.destroy()
app = Tk()
app.geometry('700x500+400+200')
app.title('Title')
label_1 = Label(text = "Enter number")
label_1.grid(row = 0, column = 0)
text_box1 = DoubleVar()
input1 = Entry(app, textvariable = text_box1)
input1.grid(row = 0, column = 2)
statusbar = Label(app, text = "", bd = 1, relief = SUNKEN, anchor = W)
statusbar.pack(side = BOTTOM, fill = X)
startButton = Button(app, text = "Start", command = StoreValues).grid(row = 9, column = 2, padx = 15, pady = 15)
app.mainloop()
```
Any help is appreciated! Thanks! | 2013/06/24 | [
"https://Stackoverflow.com/questions/17267140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725494/"
] | Yeah thats right. In following example, i have divided my program into 2 frames. frame1 caters towards menu/toolbar and uses pack() methods wherein frame2 is used to make login page credentials and uses grid() methods.
```
from tkinter import *
def donothing():
print ('IT WORKED')
root=Tk()
root.title(string='LOGIN PAGE')
frame1=Frame(root)
frame1.pack(side=TOP,fill=X)
frame2=Frame(root)
frame2.pack(side=TOP, fill=X)
m=Menu(frame1)
root.config(menu=m)
submenu=Menu(m)
m.add_cascade(label='File',menu=submenu)
submenu.add_command(label='New File', command=donothing)
submenu.add_command(label='Open', command=donothing)
submenu.add_separator()
submenu.add_command(label='Exit', command=frame1.quit)
editmenu=Menu(m)
m.add_cascade(label='Edit', menu=editmenu)
editmenu.add_command(label='Cut',command=donothing)
editmenu.add_command(label='Copy',command=donothing)
editmenu.add_command(label='Paste',command=donothing)
editmenu.add_separator()
editmenu.add_command(label='Exit', command=frame1.quit)
# **** ToolBar *******
toolbar=Frame(frame1,bg='grey')
toolbar.pack(side=TOP,fill=X)
btn1=Button(toolbar, text='Print', command=donothing)
btn2=Button(toolbar, text='Paste', command=donothing)
btn3=Button(toolbar, text='Cut', command=donothing)
btn4=Button(toolbar, text='Copy', command=donothing)
btn1.pack(side=LEFT,padx=2)
btn2.pack(side=LEFT,padx=2)
btn3.pack(side=LEFT,padx=2)
btn4.pack(side=LEFT,padx=2)
# ***** LOGIN CREDENTIALS ******
label=Label(frame2,text='WELCOME TO MY PAGE',fg='red',bg='white')
label.grid(row=3,column=1)
label1=Label(frame2,text='Name')
label2=Label(frame2,text='Password')
label1.grid(row=4,column=0,sticky=E)
label2.grid(row=5,column=0,sticky=E)
entry1=Entry(frame2)
entry2=Entry(frame2)
entry1.grid(row=4,column=1)
entry2.grid(row=5,column=1)
chk=Checkbutton(frame2,text='KEEP ME LOGGED IN')
chk.grid(row=6,column=1)
btn=Button(frame2,text='SUBMIT')
btn.grid(row=7,column=1)
# **** StatusBar ******************
status= Label(root,text='Loading',bd=1,relief=SUNKEN,anchor=W)
status.pack(side=BOTTOM, fill=X)
``` | For single widgets, the answer is no: you cannot use both `pack()` and `grid()` inside one widget. But you can use both for different widgets, even if they are all inside the same widget. For instance:
```py
my_canvas=tk.Canvas(window1,width=540,height=420,bd=0)
my_canvas.create_image(270,210,image=bg,anchor="center")
my_canvas.pack(fill="both",expand=True)
originallbl = tk.Label(my_canvas, text="Original", width=15).grid(row=1,column=1)
original = tk.Entry(my_canvas, width=15).grid(row=1,column=2)
```
I used `pack()` in order to set canvas, I used `grid()` in order to set labels, buttons, etc. in the same canvas |
61,712,062 | I am trying to make Python play a video which is embedded in a website (<https://harsh10822.wixsite.com/intro>).
I tried using ID,xpath etc etc but It didn't workout.
There is a similar Question to mine here ([How to click on the play button of a youtube video embedded within smtebook through selenium and python](https://stackoverflow.com/questions/51764056/how-to-click-on-the-play-button-of-a-youtube-video-embedded-within-smtebook-thro)) But I couldn't figure out how to apply the code.
If You could help me out by providing the code,I will be really happy.
Thankyou | 2020/05/10 | [
"https://Stackoverflow.com/questions/61712062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12158094/"
] | This should work.
```
driver = webdriver.Firefox()
driver.get('https://harsh10822.wixsite.com/intro')
time.sleep(5)
video = driver.find_element_by_id('video-player-comp-ka1067od')
video.click()
```
Waiting is important in this case, because embedded video doesn't load instantly with the page so selenium needs to wait. You can change 5 seconds to any number that works for you. | Make sure that particular web driver is downloaded and placed in the directory wherein your code is saved. And for reference you can refer to Tech With Tim selenium tutorials.
```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
video=input()
driver=webdriver.Chrome()
driver.get("https://youtube.com")
search=driver.find_element_by_id("search")
time.sleep(2)
search.send_keys(video,Keys.RETURN)
time.sleep(2)
play=driver.find_element_by_id("video-title")
play.send_keys(Keys.RETURN)
``` |
61,712,062 | I am trying to make Python play a video which is embedded in a website (<https://harsh10822.wixsite.com/intro>).
I tried using ID,xpath etc etc but It didn't workout.
There is a similar Question to mine here ([How to click on the play button of a youtube video embedded within smtebook through selenium and python](https://stackoverflow.com/questions/51764056/how-to-click-on-the-play-button-of-a-youtube-video-embedded-within-smtebook-thro)) But I couldn't figure out how to apply the code.
If You could help me out by providing the code,I will be really happy.
Thankyou | 2020/05/10 | [
"https://Stackoverflow.com/questions/61712062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12158094/"
] | See: [How to click on the play button of a youtube video embedded within smtebook through selenium and python](https://stackoverflow.com/questions/51764056/how-to-click-on-the-play-button-of-a-youtube-video-embedded-within-smtebook-thro)
But this uses a slightly different technique instead of `WebDriverWait` or sleeping for a fixed number of seconds, which can be wasteful if you are sleeping for longer than necessary.
Instead, use a call to `driver.implicitly_wait(10)`. Then any calls that attempt to locate elements will implicitly wait for up to 10 seconds for the element to appear before timing out but will wait no longer than necessary. It's just a question of knowing which elements to look for and where:
```
driver = webdriver.Firefox()
driver.implicitly_wait(10) # wait for up to 10 seconds before timeout for any find operation
driver.get('https://harsh10822.wixsite.com/intro')
driver.switch_to.frame(driver.find_element_by_xpath('//iframe[starts-with(@src, "https://www.youtube.com/embed")]')) # switch to iframe
button = driver.find_element_by_xpath('//button[@aria-label="Play"]') # look for button
button.click()
``` | Make sure that particular web driver is downloaded and placed in the directory wherein your code is saved. And for reference you can refer to Tech With Tim selenium tutorials.
```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
video=input()
driver=webdriver.Chrome()
driver.get("https://youtube.com")
search=driver.find_element_by_id("search")
time.sleep(2)
search.send_keys(video,Keys.RETURN)
time.sleep(2)
play=driver.find_element_by_id("video-title")
play.send_keys(Keys.RETURN)
``` |
12,203,676 | I am writing a program which deals a lot with timezones and crossing them. The two things I deal with most are creating a datetime object from "now" and then localizing a naive datetime object.
To create a datetime object from now in the pacific timezone, I am currently doing this (python 2.7.2+)
```
from datetime import datetime
import pytz
la = pytz.timezone("America/Los_Angeles")
now = datetime.now(la)
```
Is this correct with regards to DST? If not, I suppose I should be doing:
```
now2 = la.localize(datetime.now())
```
My question is why? Can anyone show me a case where the first is wrong and the seconds is right?
As for my seconds question, suppose I had a naive date and time from some user input for 9/1/2012 at 8:00am in Los Angeles, CA. Is the right way to make the datetime like this:
```
la.localize(datetime(2012, 9, 1, 8, 0))
```
If not, how should I be building these datetimes? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12203676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1340015/"
] | The first solution is correct with regards to DST, and the second solution is bad.
I'll give an example. Here in Europe, when running this code:
```
from datetime import datetime
import pytz # $ pip install pytz
la = pytz.timezone("America/Los_Angeles")
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
now = datetime.now(la)
now2 = la.localize(datetime.now())
now3 = datetime.now()
print(now.strftime(fmt))
print(now2.strftime(fmt))
print(now3.strftime(fmt))
```
I get the following:
```
2012-08-30 12:34:06 PDT-0700
2012-08-30 21:34:06 PDT-0700
2012-08-30 21:34:06
```
`datetime.now(la)` creates a datetime with the current time in LA, plus the timezone information for LA.
`la.localize(datetime.now())` adds timezone information to the naive datetime, but does no timezone conversion; it just assumes the time was already in this timezone.
`datetime.now()` creates a naive datetime (without timezone information) with the local time.
As long as you are in LA, you will not see the difference, but if your code ever runs somewhere else, it will probably not do what you wanted.
Apart from that, if you ever need to deal seriously with timezones, it is better to have all your times in UTC, saving yourself a lot of trouble with DST. | The [pytz website](http://pytz.sourceforge.net/) says:
>
> Unfortunately using the tzinfo argument of the standard datetime
> constructors ‘’does not work’’ with pytz for many timezones.
>
>
>
So you should not use `datetime.now(la)`. I don't know the specifics, but some timezones operate on more exotic rules then we are used to, and python's datetime code can't handle them. By using pytz's code, they should be handled correctly since that's pytz's purpose. It may also have issues for the times that occur twice thanks to jumping times in daylight savings.
As for the second question, that's exactly what the documentation shows, so you should be good. |
12,203,676 | I am writing a program which deals a lot with timezones and crossing them. The two things I deal with most are creating a datetime object from "now" and then localizing a naive datetime object.
To create a datetime object from now in the pacific timezone, I am currently doing this (python 2.7.2+)
```
from datetime import datetime
import pytz
la = pytz.timezone("America/Los_Angeles")
now = datetime.now(la)
```
Is this correct with regards to DST? If not, I suppose I should be doing:
```
now2 = la.localize(datetime.now())
```
My question is why? Can anyone show me a case where the first is wrong and the seconds is right?
As for my seconds question, suppose I had a naive date and time from some user input for 9/1/2012 at 8:00am in Los Angeles, CA. Is the right way to make the datetime like this:
```
la.localize(datetime(2012, 9, 1, 8, 0))
```
If not, how should I be building these datetimes? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12203676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1340015/"
] | From the [pytz documentation](http://pytz.sourceforge.net/):
>
> The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.
>
>
>
So ideally you should be using `utcnow` instead of `now`.
Assuming for some reason that your hands are tied and you need to work with local times, you can still run into a problem with trying to localize the current time if you're doing it during the daylight saving transition window. The same `datetime` might occur twice, once during daylight time and again during standard time, and the `localize` method doesn't know how to settle the conflict unless you tell it explicitly with the `is_dst` parameter.
So to get the current UTC time:
```
utc = pytz.timezone('UTC')
now = utc.localize(datetime.datetime.utcnow())
```
And to convert it to your local time (but only when you must):
```
la = pytz.timezone('America/Los_Angeles')
local_time = now.astimezone(la)
```
Edit: as pointed out in the comments by [@J.F. Sebastian](https://stackoverflow.com/users/4279/j-f-sebastian), your first example using `datetime.now(tz)` will work in all cases. Your second example fails during the fall transition as I outlined above. I still advocate using UTC instead of local time for everything except display. | The [pytz website](http://pytz.sourceforge.net/) says:
>
> Unfortunately using the tzinfo argument of the standard datetime
> constructors ‘’does not work’’ with pytz for many timezones.
>
>
>
So you should not use `datetime.now(la)`. I don't know the specifics, but some timezones operate on more exotic rules then we are used to, and python's datetime code can't handle them. By using pytz's code, they should be handled correctly since that's pytz's purpose. It may also have issues for the times that occur twice thanks to jumping times in daylight savings.
As for the second question, that's exactly what the documentation shows, so you should be good. |
12,203,676 | I am writing a program which deals a lot with timezones and crossing them. The two things I deal with most are creating a datetime object from "now" and then localizing a naive datetime object.
To create a datetime object from now in the pacific timezone, I am currently doing this (python 2.7.2+)
```
from datetime import datetime
import pytz
la = pytz.timezone("America/Los_Angeles")
now = datetime.now(la)
```
Is this correct with regards to DST? If not, I suppose I should be doing:
```
now2 = la.localize(datetime.now())
```
My question is why? Can anyone show me a case where the first is wrong and the seconds is right?
As for my seconds question, suppose I had a naive date and time from some user input for 9/1/2012 at 8:00am in Los Angeles, CA. Is the right way to make the datetime like this:
```
la.localize(datetime(2012, 9, 1, 8, 0))
```
If not, how should I be building these datetimes? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12203676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1340015/"
] | **This works:**
```
# naive datetime
d = datetime.datetime(2016, 11, 5, 16, 43, 45)
utc = pytz.UTC # UTC timezone
pst = pytz.timezone('America/Los_Angeles') # LA timezone
# Convert to UTC timezone aware datetime
d = utc.localize(d)
>>> datetime.datetime(2016, 11, 5, 16, 43, 45, tzinfo=<UTC>)
# show as in LA time zone (not converting here)
d.astimezone(pst)
>>> datetime.datetime(2016, 11, 5, 9, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
# we get Pacific Daylight Time: PDT
# add 1 day to UTC date
d = d + datetime.timedelta(days=1)
>>> datetime.datetime(2016, 11, 6, 16, 43, 45, tzinfo=<UTC>)
d.astimezone(pst) # now cast to LA time zone
>>> datetime.datetime(2016, 11, 6, 8, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
# Daylight saving is applied -> we get Pacific Standard Time PST
```
**This DOES NOT work:**
```
# naive datetime
d = datetime.datetime(2016, 11, 5, 16, 43, 45)
utc = pytz.UTC # UTC timezone
pst = pytz.timezone('America/Los_Angeles') # LA timezone
# convert to UTC timezone aware datetime
d = utc.localize(d)
>>> datetime.datetime(2016, 11, 5, 16, 43, 45, tzinfo=<UTC>)
# convert to 'America/Los_Angeles' timezone: DON'T DO THIS
d = d.astimezone(pst)
>>> datetime.datetime(2016, 11, 5, 9, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
# we are in Pacific Daylight Time PDT
# add 1 day to LA local date: DON'T DO THAT
d = d + datetime.timedelta(days=1)
>>> datetime.datetime(2016, 11, 6, 9, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
# Daylight Saving is NOT respected, we are still in PDT time, not PST
```
**Conclusion:**
`datetime.timedelta()` **DOES NOT** account for daylight saving.
Do your time add/subtract in UTC timezone ALWAYS.
Cast to local time only for output / display. | The [pytz website](http://pytz.sourceforge.net/) says:
>
> Unfortunately using the tzinfo argument of the standard datetime
> constructors ‘’does not work’’ with pytz for many timezones.
>
>
>
So you should not use `datetime.now(la)`. I don't know the specifics, but some timezones operate on more exotic rules then we are used to, and python's datetime code can't handle them. By using pytz's code, they should be handled correctly since that's pytz's purpose. It may also have issues for the times that occur twice thanks to jumping times in daylight savings.
As for the second question, that's exactly what the documentation shows, so you should be good. |
12,203,676 | I am writing a program which deals a lot with timezones and crossing them. The two things I deal with most are creating a datetime object from "now" and then localizing a naive datetime object.
To create a datetime object from now in the pacific timezone, I am currently doing this (python 2.7.2+)
```
from datetime import datetime
import pytz
la = pytz.timezone("America/Los_Angeles")
now = datetime.now(la)
```
Is this correct with regards to DST? If not, I suppose I should be doing:
```
now2 = la.localize(datetime.now())
```
My question is why? Can anyone show me a case where the first is wrong and the seconds is right?
As for my seconds question, suppose I had a naive date and time from some user input for 9/1/2012 at 8:00am in Los Angeles, CA. Is the right way to make the datetime like this:
```
la.localize(datetime(2012, 9, 1, 8, 0))
```
If not, how should I be building these datetimes? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12203676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1340015/"
] | From the [pytz documentation](http://pytz.sourceforge.net/):
>
> The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.
>
>
>
So ideally you should be using `utcnow` instead of `now`.
Assuming for some reason that your hands are tied and you need to work with local times, you can still run into a problem with trying to localize the current time if you're doing it during the daylight saving transition window. The same `datetime` might occur twice, once during daylight time and again during standard time, and the `localize` method doesn't know how to settle the conflict unless you tell it explicitly with the `is_dst` parameter.
So to get the current UTC time:
```
utc = pytz.timezone('UTC')
now = utc.localize(datetime.datetime.utcnow())
```
And to convert it to your local time (but only when you must):
```
la = pytz.timezone('America/Los_Angeles')
local_time = now.astimezone(la)
```
Edit: as pointed out in the comments by [@J.F. Sebastian](https://stackoverflow.com/users/4279/j-f-sebastian), your first example using `datetime.now(tz)` will work in all cases. Your second example fails during the fall transition as I outlined above. I still advocate using UTC instead of local time for everything except display. | The first solution is correct with regards to DST, and the second solution is bad.
I'll give an example. Here in Europe, when running this code:
```
from datetime import datetime
import pytz # $ pip install pytz
la = pytz.timezone("America/Los_Angeles")
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
now = datetime.now(la)
now2 = la.localize(datetime.now())
now3 = datetime.now()
print(now.strftime(fmt))
print(now2.strftime(fmt))
print(now3.strftime(fmt))
```
I get the following:
```
2012-08-30 12:34:06 PDT-0700
2012-08-30 21:34:06 PDT-0700
2012-08-30 21:34:06
```
`datetime.now(la)` creates a datetime with the current time in LA, plus the timezone information for LA.
`la.localize(datetime.now())` adds timezone information to the naive datetime, but does no timezone conversion; it just assumes the time was already in this timezone.
`datetime.now()` creates a naive datetime (without timezone information) with the local time.
As long as you are in LA, you will not see the difference, but if your code ever runs somewhere else, it will probably not do what you wanted.
Apart from that, if you ever need to deal seriously with timezones, it is better to have all your times in UTC, saving yourself a lot of trouble with DST. |
12,203,676 | I am writing a program which deals a lot with timezones and crossing them. The two things I deal with most are creating a datetime object from "now" and then localizing a naive datetime object.
To create a datetime object from now in the pacific timezone, I am currently doing this (python 2.7.2+)
```
from datetime import datetime
import pytz
la = pytz.timezone("America/Los_Angeles")
now = datetime.now(la)
```
Is this correct with regards to DST? If not, I suppose I should be doing:
```
now2 = la.localize(datetime.now())
```
My question is why? Can anyone show me a case where the first is wrong and the seconds is right?
As for my seconds question, suppose I had a naive date and time from some user input for 9/1/2012 at 8:00am in Los Angeles, CA. Is the right way to make the datetime like this:
```
la.localize(datetime(2012, 9, 1, 8, 0))
```
If not, how should I be building these datetimes? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12203676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1340015/"
] | The first solution is correct with regards to DST, and the second solution is bad.
I'll give an example. Here in Europe, when running this code:
```
from datetime import datetime
import pytz # $ pip install pytz
la = pytz.timezone("America/Los_Angeles")
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
now = datetime.now(la)
now2 = la.localize(datetime.now())
now3 = datetime.now()
print(now.strftime(fmt))
print(now2.strftime(fmt))
print(now3.strftime(fmt))
```
I get the following:
```
2012-08-30 12:34:06 PDT-0700
2012-08-30 21:34:06 PDT-0700
2012-08-30 21:34:06
```
`datetime.now(la)` creates a datetime with the current time in LA, plus the timezone information for LA.
`la.localize(datetime.now())` adds timezone information to the naive datetime, but does no timezone conversion; it just assumes the time was already in this timezone.
`datetime.now()` creates a naive datetime (without timezone information) with the local time.
As long as you are in LA, you will not see the difference, but if your code ever runs somewhere else, it will probably not do what you wanted.
Apart from that, if you ever need to deal seriously with timezones, it is better to have all your times in UTC, saving yourself a lot of trouble with DST. | **This works:**
```
# naive datetime
d = datetime.datetime(2016, 11, 5, 16, 43, 45)
utc = pytz.UTC # UTC timezone
pst = pytz.timezone('America/Los_Angeles') # LA timezone
# Convert to UTC timezone aware datetime
d = utc.localize(d)
>>> datetime.datetime(2016, 11, 5, 16, 43, 45, tzinfo=<UTC>)
# show as in LA time zone (not converting here)
d.astimezone(pst)
>>> datetime.datetime(2016, 11, 5, 9, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
# we get Pacific Daylight Time: PDT
# add 1 day to UTC date
d = d + datetime.timedelta(days=1)
>>> datetime.datetime(2016, 11, 6, 16, 43, 45, tzinfo=<UTC>)
d.astimezone(pst) # now cast to LA time zone
>>> datetime.datetime(2016, 11, 6, 8, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
# Daylight saving is applied -> we get Pacific Standard Time PST
```
**This DOES NOT work:**
```
# naive datetime
d = datetime.datetime(2016, 11, 5, 16, 43, 45)
utc = pytz.UTC # UTC timezone
pst = pytz.timezone('America/Los_Angeles') # LA timezone
# convert to UTC timezone aware datetime
d = utc.localize(d)
>>> datetime.datetime(2016, 11, 5, 16, 43, 45, tzinfo=<UTC>)
# convert to 'America/Los_Angeles' timezone: DON'T DO THIS
d = d.astimezone(pst)
>>> datetime.datetime(2016, 11, 5, 9, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
# we are in Pacific Daylight Time PDT
# add 1 day to LA local date: DON'T DO THAT
d = d + datetime.timedelta(days=1)
>>> datetime.datetime(2016, 11, 6, 9, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
# Daylight Saving is NOT respected, we are still in PDT time, not PST
```
**Conclusion:**
`datetime.timedelta()` **DOES NOT** account for daylight saving.
Do your time add/subtract in UTC timezone ALWAYS.
Cast to local time only for output / display. |
12,203,676 | I am writing a program which deals a lot with timezones and crossing them. The two things I deal with most are creating a datetime object from "now" and then localizing a naive datetime object.
To create a datetime object from now in the pacific timezone, I am currently doing this (python 2.7.2+)
```
from datetime import datetime
import pytz
la = pytz.timezone("America/Los_Angeles")
now = datetime.now(la)
```
Is this correct with regards to DST? If not, I suppose I should be doing:
```
now2 = la.localize(datetime.now())
```
My question is why? Can anyone show me a case where the first is wrong and the seconds is right?
As for my seconds question, suppose I had a naive date and time from some user input for 9/1/2012 at 8:00am in Los Angeles, CA. Is the right way to make the datetime like this:
```
la.localize(datetime(2012, 9, 1, 8, 0))
```
If not, how should I be building these datetimes? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12203676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1340015/"
] | From the [pytz documentation](http://pytz.sourceforge.net/):
>
> The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.
>
>
>
So ideally you should be using `utcnow` instead of `now`.
Assuming for some reason that your hands are tied and you need to work with local times, you can still run into a problem with trying to localize the current time if you're doing it during the daylight saving transition window. The same `datetime` might occur twice, once during daylight time and again during standard time, and the `localize` method doesn't know how to settle the conflict unless you tell it explicitly with the `is_dst` parameter.
So to get the current UTC time:
```
utc = pytz.timezone('UTC')
now = utc.localize(datetime.datetime.utcnow())
```
And to convert it to your local time (but only when you must):
```
la = pytz.timezone('America/Los_Angeles')
local_time = now.astimezone(la)
```
Edit: as pointed out in the comments by [@J.F. Sebastian](https://stackoverflow.com/users/4279/j-f-sebastian), your first example using `datetime.now(tz)` will work in all cases. Your second example fails during the fall transition as I outlined above. I still advocate using UTC instead of local time for everything except display. | **This works:**
```
# naive datetime
d = datetime.datetime(2016, 11, 5, 16, 43, 45)
utc = pytz.UTC # UTC timezone
pst = pytz.timezone('America/Los_Angeles') # LA timezone
# Convert to UTC timezone aware datetime
d = utc.localize(d)
>>> datetime.datetime(2016, 11, 5, 16, 43, 45, tzinfo=<UTC>)
# show as in LA time zone (not converting here)
d.astimezone(pst)
>>> datetime.datetime(2016, 11, 5, 9, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
# we get Pacific Daylight Time: PDT
# add 1 day to UTC date
d = d + datetime.timedelta(days=1)
>>> datetime.datetime(2016, 11, 6, 16, 43, 45, tzinfo=<UTC>)
d.astimezone(pst) # now cast to LA time zone
>>> datetime.datetime(2016, 11, 6, 8, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
# Daylight saving is applied -> we get Pacific Standard Time PST
```
**This DOES NOT work:**
```
# naive datetime
d = datetime.datetime(2016, 11, 5, 16, 43, 45)
utc = pytz.UTC # UTC timezone
pst = pytz.timezone('America/Los_Angeles') # LA timezone
# convert to UTC timezone aware datetime
d = utc.localize(d)
>>> datetime.datetime(2016, 11, 5, 16, 43, 45, tzinfo=<UTC>)
# convert to 'America/Los_Angeles' timezone: DON'T DO THIS
d = d.astimezone(pst)
>>> datetime.datetime(2016, 11, 5, 9, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
# we are in Pacific Daylight Time PDT
# add 1 day to LA local date: DON'T DO THAT
d = d + datetime.timedelta(days=1)
>>> datetime.datetime(2016, 11, 6, 9, 43, 45,
tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
# Daylight Saving is NOT respected, we are still in PDT time, not PST
```
**Conclusion:**
`datetime.timedelta()` **DOES NOT** account for daylight saving.
Do your time add/subtract in UTC timezone ALWAYS.
Cast to local time only for output / display. |
7,930,259 | I am using supervisor to run a python script:
```
[program:twitter_track]
autorestart = true
numprocs = 1
autostart = false
redirect_stderr = True
stopwaitsecs = 1
startsecs = 1
priority = 99
command = python /home/ubuntu/services/twitter.py track
startretries = 3
stdout_logfile = /home/ubuntu/logs/twitter_track.log
```
But the process fails to start. Here is what the error log says:
```
Traceback (most recent call last):
File "/home/ubuntu/services/twitter.py", line 6, in <module>
from mymodule.twitter.stream import TwitterStream
ImportError: No module named mymodule.twitter.stream
Traceback (most recent call last):
File "/home/ubuntu/services/twitter.py", line 6, in <module>
```
It seems that obtain mymodule, but if I run twitter.py on it's own, everything works fine, it only throws this error when I run it through supervisor.
I added mymodule to the PYTHONPATH in my ~/.profile file like so:
```
export PYTHONPATH=$PYTHONPATH:/home/ubuntu/lib
```
Is there any reason why the script would work when run through terminal but not when run through supervisor? Any help would be appreciated. | 2011/10/28 | [
"https://Stackoverflow.com/questions/7930259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170488/"
] | Add the `PYTHONPATH` definition to the `environment` directive in the supervisord configuration file. It should go under your `[program:twitter_track]` section, like so:
```
environment=PYTHONPATH=/home/ubuntu/lib/
```
This will ensure that that your python process sees the proper `PYTHONPATH` when supervisord starts it. | Add the PYTHONPATH definition to the environment:
```
[program:twitter_track]
command = python /home/ubuntu/services/twitter.py track
environment=PYTHONPATH=/home/ubuntu/lib
``` |
56,758,116 | I got some code from google for speech recognition when i try to run that code i'm getting "NotImplementedError" please see the below code and help me.I'm using Mac.
```
import speech_recognition as sr
r = sr.Recognizer()
with sr.Recognizer() as source:
print("Speak Anything")
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print("you said:{}".format(text))
except NotImplementedError:
print("Sorry could not recognise your voice")
```
Traceback (most recent call last):
File "", line 4, in
with sr.Recognizer() as source:
File "/Users/chiku/anaconda3/lib/python3.5/site-packages/speech\_recognition/**init**.py", line 51, in **enter**
raise NotImplementedError("this is an abstract class")
NotImplementedError: this is an abstract class
Traceback (most recent call last):
File "", line 4, in
with sr.Recognizer() as source:
File "/Users/chiku/anaconda3/lib/python3.5/site-packages/speech\_recognition/**init**.py", line 51, in **enter**
raise NotImplementedError("this is an abstract class")
NotImplementedError: this is an abstract class | 2019/06/25 | [
"https://Stackoverflow.com/questions/56758116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7614804/"
] | In the line above, you instantiate a `Recognizer` object, then you try to use the uninstatiated class in the problem line. Should that be
```
with r as source:
...
``` | I have the below code and it gives me same error i.e
Traceback (most recent call last):
File "/Users/../Listen.py", line 25, in
print(Listen())
^^^^^^^^
File "/Users/../Listen.py", line 8, in Listen
with sr.Recognizer() as source:
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/speech\_recognition/**init**.py", line 51, in **enter**
raise NotImplementedError("this is an abstract class")
NotImplementedError: this is an abstract class
```
import speech_recognition as sr
from googletrans import Translator
def Listen():
r = sr.Microphone()
with sr.Recognizer() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='hi')
except:
return ""
query = str(query).lower()
return query
Listen()
``` |
5,960,791 | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the `main( int argc, char* argv[])` function in the past.
Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.
Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.
Edit From Original Question:
Sorry I don't think I was clear with my question. I don't want to use the `main( int argc, char* argv[])` feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?
Thanks again mike | 2011/05/11 | [
"https://Stackoverflow.com/questions/5960791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644439/"
] | Use subprocess to execute your program from python.
```
import subprocess as sp
import shlex
def run(cmdline):
process = sp.Popen(shlex.split(cmdline), stdout=sp.PIPE, stderr=sp.PIPE)
output, err = process.communicate()
retcode = process.poll()
return retcode, output, err
run('./a.out '+arg1+' '+arg2+' '+...)
``` | With the [ctypes](http://docs.python.org/library/ctypes) module, you can call arbitrary C libraries. |
5,960,791 | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the `main( int argc, char* argv[])` function in the past.
Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.
Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.
Edit From Original Question:
Sorry I don't think I was clear with my question. I don't want to use the `main( int argc, char* argv[])` feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?
Thanks again mike | 2011/05/11 | [
"https://Stackoverflow.com/questions/5960791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644439/"
] | Use subprocess to execute your program from python.
```
import subprocess as sp
import shlex
def run(cmdline):
process = sp.Popen(shlex.split(cmdline), stdout=sp.PIPE, stderr=sp.PIPE)
output, err = process.communicate()
retcode = process.poll()
return retcode, output, err
run('./a.out '+arg1+' '+arg2+' '+...)
``` | There are several ways for interfacing C and C++ code with Python:
* [SWIG](http://www.swig.org/)
* [Boost.Python](http://boost.org/doc/libs/1_46_1/libs/python/doc/index.html)
* [Cython](http://cython.org/) |
5,960,791 | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the `main( int argc, char* argv[])` function in the past.
Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.
Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.
Edit From Original Question:
Sorry I don't think I was clear with my question. I don't want to use the `main( int argc, char* argv[])` feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?
Thanks again mike | 2011/05/11 | [
"https://Stackoverflow.com/questions/5960791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644439/"
] | Use subprocess to execute your program from python.
```
import subprocess as sp
import shlex
def run(cmdline):
process = sp.Popen(shlex.split(cmdline), stdout=sp.PIPE, stderr=sp.PIPE)
output, err = process.communicate()
retcode = process.poll()
return retcode, output, err
run('./a.out '+arg1+' '+arg2+' '+...)
``` | You can use subprocess module to launch an executable with defined command-line arguments:
```
import subprocess
option1 = True
option2 = Frue
# ...
optionN = True
lstopt = ['path_to_cpp_executable',
option1,
option2,
...
optionN
]
lstopt = [str(item) for item in lstopt] # because we need to pass strings
proc = subprocess.Popen(lstrun, close_fds = True)
stdoutdata, stderrdata = proc.communicate()
```
If you're using Python 2.7 or Python 3.2, then OrderedDict will make the code more readable:
```
from collections import OrderedDict
opts = OrderedDict([('option1', True),
('option2', False),
]
lstopt = (['path_to_cpp_executable'] +
list(str(item) for item in opts.values())
)
proc = subprocess.Popen(lstrun, close_fds = True)
stdoutdata, stderrdata = proc.communicate()
``` |
5,960,791 | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the `main( int argc, char* argv[])` function in the past.
Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.
Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.
Edit From Original Question:
Sorry I don't think I was clear with my question. I don't want to use the `main( int argc, char* argv[])` feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?
Thanks again mike | 2011/05/11 | [
"https://Stackoverflow.com/questions/5960791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644439/"
] | Interfacing between C/C++ and Python is heavily documented and there are several different approaches. However, if you're just setting values then it may be overkill to use Python, which is more geared toward customising large operations within your process by farming it off to the interpreter.
I would personally recommend researching an "ini" file method, either traditionally or by using XML, or even a lighter scripting language like Lua. | Use subprocess to execute your program from python.
```
import subprocess as sp
import shlex
def run(cmdline):
process = sp.Popen(shlex.split(cmdline), stdout=sp.PIPE, stderr=sp.PIPE)
output, err = process.communicate()
retcode = process.poll()
return retcode, output, err
run('./a.out '+arg1+' '+arg2+' '+...)
``` |
5,960,791 | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the `main( int argc, char* argv[])` function in the past.
Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.
Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.
Edit From Original Question:
Sorry I don't think I was clear with my question. I don't want to use the `main( int argc, char* argv[])` feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?
Thanks again mike | 2011/05/11 | [
"https://Stackoverflow.com/questions/5960791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644439/"
] | Use subprocess to execute your program from python.
```
import subprocess as sp
import shlex
def run(cmdline):
process = sp.Popen(shlex.split(cmdline), stdout=sp.PIPE, stderr=sp.PIPE)
output, err = process.communicate()
retcode = process.poll()
return retcode, output, err
run('./a.out '+arg1+' '+arg2+' '+...)
``` | I can only advise to have a look at [swig](http://www.swig.org/) : using director feature, it allows to fully integrate C++ and python, including cross derivation from onle language to the other |
5,960,791 | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the `main( int argc, char* argv[])` function in the past.
Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.
Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.
Edit From Original Question:
Sorry I don't think I was clear with my question. I don't want to use the `main( int argc, char* argv[])` feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?
Thanks again mike | 2011/05/11 | [
"https://Stackoverflow.com/questions/5960791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644439/"
] | Interfacing between C/C++ and Python is heavily documented and there are several different approaches. However, if you're just setting values then it may be overkill to use Python, which is more geared toward customising large operations within your process by farming it off to the interpreter.
I would personally recommend researching an "ini" file method, either traditionally or by using XML, or even a lighter scripting language like Lua. | With the [ctypes](http://docs.python.org/library/ctypes) module, you can call arbitrary C libraries. |
5,960,791 | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the `main( int argc, char* argv[])` function in the past.
Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.
Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.
Edit From Original Question:
Sorry I don't think I was clear with my question. I don't want to use the `main( int argc, char* argv[])` feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?
Thanks again mike | 2011/05/11 | [
"https://Stackoverflow.com/questions/5960791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644439/"
] | Interfacing between C/C++ and Python is heavily documented and there are several different approaches. However, if you're just setting values then it may be overkill to use Python, which is more geared toward customising large operations within your process by farming it off to the interpreter.
I would personally recommend researching an "ini" file method, either traditionally or by using XML, or even a lighter scripting language like Lua. | There are several ways for interfacing C and C++ code with Python:
* [SWIG](http://www.swig.org/)
* [Boost.Python](http://boost.org/doc/libs/1_46_1/libs/python/doc/index.html)
* [Cython](http://cython.org/) |
5,960,791 | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the `main( int argc, char* argv[])` function in the past.
Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.
Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.
Edit From Original Question:
Sorry I don't think I was clear with my question. I don't want to use the `main( int argc, char* argv[])` feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?
Thanks again mike | 2011/05/11 | [
"https://Stackoverflow.com/questions/5960791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644439/"
] | Interfacing between C/C++ and Python is heavily documented and there are several different approaches. However, if you're just setting values then it may be overkill to use Python, which is more geared toward customising large operations within your process by farming it off to the interpreter.
I would personally recommend researching an "ini" file method, either traditionally or by using XML, or even a lighter scripting language like Lua. | You can use subprocess module to launch an executable with defined command-line arguments:
```
import subprocess
option1 = True
option2 = Frue
# ...
optionN = True
lstopt = ['path_to_cpp_executable',
option1,
option2,
...
optionN
]
lstopt = [str(item) for item in lstopt] # because we need to pass strings
proc = subprocess.Popen(lstrun, close_fds = True)
stdoutdata, stderrdata = proc.communicate()
```
If you're using Python 2.7 or Python 3.2, then OrderedDict will make the code more readable:
```
from collections import OrderedDict
opts = OrderedDict([('option1', True),
('option2', False),
]
lstopt = (['path_to_cpp_executable'] +
list(str(item) for item in opts.values())
)
proc = subprocess.Popen(lstrun, close_fds = True)
stdoutdata, stderrdata = proc.communicate()
``` |
5,960,791 | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the `main( int argc, char* argv[])` function in the past.
Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.
Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.
Edit From Original Question:
Sorry I don't think I was clear with my question. I don't want to use the `main( int argc, char* argv[])` feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?
Thanks again mike | 2011/05/11 | [
"https://Stackoverflow.com/questions/5960791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644439/"
] | Interfacing between C/C++ and Python is heavily documented and there are several different approaches. However, if you're just setting values then it may be overkill to use Python, which is more geared toward customising large operations within your process by farming it off to the interpreter.
I would personally recommend researching an "ini" file method, either traditionally or by using XML, or even a lighter scripting language like Lua. | I can only advise to have a look at [swig](http://www.swig.org/) : using director feature, it allows to fully integrate C++ and python, including cross derivation from onle language to the other |
58,758,447 | I had Python versions of 2.7 and 3.5. I wanted the install a newer version of Python which is python 3.8. I am using Ubuntu 16.04 and I can not just uninstall Python 3.5 due to the dependencies. So in order to run my scripts, I use `python3.8 app.py`. No problem so far. But when I want to install new packages via pip:
```
python3.8 -m pip install pylint
```
It throws an error:
```
AttributeError: module 'platform' has no attribute 'linux_distribution'
```
So far, I tried:
```
sudo update-alternatives --config python3
```
and chose python3.8 and run command by starting with python3 but no luck.
Then:
```
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
```
I also tried running the command by starting with python3 but it did not work either.
How can I fix it so that I can install new packages to my new version of Python? | 2019/11/07 | [
"https://Stackoverflow.com/questions/58758447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325117/"
] | In my case, removing `python-pip-whl` package helped:
```
apt-get remove python-pip-whl
```
It removed also `pip` and `virtualenv`, so I had to install them again:
```
curl https://bootstrap.pypa.io/get-pip.py | python3
pip install virtualenv
``` | I recently had this error and it turns out that I had a package called `platform` at a folder on my path ahead of the standard library and so the interpreter imported that instead. Check your path to what it is that you're actually importing. |
58,758,447 | I had Python versions of 2.7 and 3.5. I wanted the install a newer version of Python which is python 3.8. I am using Ubuntu 16.04 and I can not just uninstall Python 3.5 due to the dependencies. So in order to run my scripts, I use `python3.8 app.py`. No problem so far. But when I want to install new packages via pip:
```
python3.8 -m pip install pylint
```
It throws an error:
```
AttributeError: module 'platform' has no attribute 'linux_distribution'
```
So far, I tried:
```
sudo update-alternatives --config python3
```
and chose python3.8 and run command by starting with python3 but no luck.
Then:
```
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
```
I also tried running the command by starting with python3 but it did not work either.
How can I fix it so that I can install new packages to my new version of Python? | 2019/11/07 | [
"https://Stackoverflow.com/questions/58758447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325117/"
] | Check if your wheels installation is old. I was getting this same error and fixed it with
`python3.8 -m pip install --upgrade pip setuptools wheel`
Pylint seems to work on python3.8 | I recently had this error and it turns out that I had a package called `platform` at a folder on my path ahead of the standard library and so the interpreter imported that instead. Check your path to what it is that you're actually importing. |
58,758,447 | I had Python versions of 2.7 and 3.5. I wanted the install a newer version of Python which is python 3.8. I am using Ubuntu 16.04 and I can not just uninstall Python 3.5 due to the dependencies. So in order to run my scripts, I use `python3.8 app.py`. No problem so far. But when I want to install new packages via pip:
```
python3.8 -m pip install pylint
```
It throws an error:
```
AttributeError: module 'platform' has no attribute 'linux_distribution'
```
So far, I tried:
```
sudo update-alternatives --config python3
```
and chose python3.8 and run command by starting with python3 but no luck.
Then:
```
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
```
I also tried running the command by starting with python3 but it did not work either.
How can I fix it so that I can install new packages to my new version of Python? | 2019/11/07 | [
"https://Stackoverflow.com/questions/58758447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325117/"
] | Python 3.8 removed some stuff. I solved my problems with `pip` (specifically `pip install`) by installing `pip` with `curl`.
What worked for me was downloading `get-pip.py` and run it with Python 3.8:
```
cd ~/Downloads
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3.8 get-pip.py
```
Source: <https://pip.pypa.io/en/stable/installing/> | I recently had this error and it turns out that I had a package called `platform` at a folder on my path ahead of the standard library and so the interpreter imported that instead. Check your path to what it is that you're actually importing. |
58,758,447 | I had Python versions of 2.7 and 3.5. I wanted the install a newer version of Python which is python 3.8. I am using Ubuntu 16.04 and I can not just uninstall Python 3.5 due to the dependencies. So in order to run my scripts, I use `python3.8 app.py`. No problem so far. But when I want to install new packages via pip:
```
python3.8 -m pip install pylint
```
It throws an error:
```
AttributeError: module 'platform' has no attribute 'linux_distribution'
```
So far, I tried:
```
sudo update-alternatives --config python3
```
and chose python3.8 and run command by starting with python3 but no luck.
Then:
```
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
```
I also tried running the command by starting with python3 but it did not work either.
How can I fix it so that I can install new packages to my new version of Python? | 2019/11/07 | [
"https://Stackoverflow.com/questions/58758447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325117/"
] | The problem is that package.linux\_distribution was deprecated starting with Python 3.5(?). and removed altogether for Python 3.8.
Use the distro package instead. This package only works on Linux however.
I ran into this problem after installing OpenCobolIDE on Linux Mint 20, having upgraded Python to the latest level. have submitted a code fix to the OpenCobolIDE author to review and test. I was able to get the IDE to start up and run with this fix.
Essentially the fix uses the distro package if available, otherwise it uses the old platform package. For example:
This code imports distro if available:
```
import platform
using_distro = False
try:
import distro
using_distro = True
except ImportError:
pass
```
Then you can test the value of *using\_distro* to determine whether to get the linux distro type from package or distro, for example:
```
if using_distro:
linux_distro = distro.like()
else:
linux_distro = platform.linux_distribution()[0]
``` | I recently had this error and it turns out that I had a package called `platform` at a folder on my path ahead of the standard library and so the interpreter imported that instead. Check your path to what it is that you're actually importing. |
58,758,447 | I had Python versions of 2.7 and 3.5. I wanted the install a newer version of Python which is python 3.8. I am using Ubuntu 16.04 and I can not just uninstall Python 3.5 due to the dependencies. So in order to run my scripts, I use `python3.8 app.py`. No problem so far. But when I want to install new packages via pip:
```
python3.8 -m pip install pylint
```
It throws an error:
```
AttributeError: module 'platform' has no attribute 'linux_distribution'
```
So far, I tried:
```
sudo update-alternatives --config python3
```
and chose python3.8 and run command by starting with python3 but no luck.
Then:
```
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
```
I also tried running the command by starting with python3 but it did not work either.
How can I fix it so that I can install new packages to my new version of Python? | 2019/11/07 | [
"https://Stackoverflow.com/questions/58758447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325117/"
] | The problem is that package.linux\_distribution was deprecated starting with Python 3.5(?). and removed altogether for Python 3.8.
Use the distro package instead. This package only works on Linux however.
I ran into this problem after installing OpenCobolIDE on Linux Mint 20, having upgraded Python to the latest level. have submitted a code fix to the OpenCobolIDE author to review and test. I was able to get the IDE to start up and run with this fix.
Essentially the fix uses the distro package if available, otherwise it uses the old platform package. For example:
This code imports distro if available:
```
import platform
using_distro = False
try:
import distro
using_distro = True
except ImportError:
pass
```
Then you can test the value of *using\_distro* to determine whether to get the linux distro type from package or distro, for example:
```
if using_distro:
linux_distro = distro.like()
else:
linux_distro = platform.linux_distribution()[0]
``` | In my case, removing `python-pip-whl` package helped:
```
apt-get remove python-pip-whl
```
It removed also `pip` and `virtualenv`, so I had to install them again:
```
curl https://bootstrap.pypa.io/get-pip.py | python3
pip install virtualenv
``` |
58,758,447 | I had Python versions of 2.7 and 3.5. I wanted the install a newer version of Python which is python 3.8. I am using Ubuntu 16.04 and I can not just uninstall Python 3.5 due to the dependencies. So in order to run my scripts, I use `python3.8 app.py`. No problem so far. But when I want to install new packages via pip:
```
python3.8 -m pip install pylint
```
It throws an error:
```
AttributeError: module 'platform' has no attribute 'linux_distribution'
```
So far, I tried:
```
sudo update-alternatives --config python3
```
and chose python3.8 and run command by starting with python3 but no luck.
Then:
```
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
```
I also tried running the command by starting with python3 but it did not work either.
How can I fix it so that I can install new packages to my new version of Python? | 2019/11/07 | [
"https://Stackoverflow.com/questions/58758447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325117/"
] | It looks like at least on my Ubuntu 16.04, pip is shared for all Python versions in `/usr/lib/python3/dist-packages/pip`.
This is what I did to get it working again:
* `sudo apt remove python3-pip`
* `sudo python3.8 -m easy_install pip`
You might want to install the python 3.5 version of pip again with `sudo python3.5 -m easy_install pip`. | Check if your wheels installation is old. I was getting this same error and fixed it with
`python3.8 -m pip install --upgrade pip setuptools wheel`
Pylint seems to work on python3.8 |
58,758,447 | I had Python versions of 2.7 and 3.5. I wanted the install a newer version of Python which is python 3.8. I am using Ubuntu 16.04 and I can not just uninstall Python 3.5 due to the dependencies. So in order to run my scripts, I use `python3.8 app.py`. No problem so far. But when I want to install new packages via pip:
```
python3.8 -m pip install pylint
```
It throws an error:
```
AttributeError: module 'platform' has no attribute 'linux_distribution'
```
So far, I tried:
```
sudo update-alternatives --config python3
```
and chose python3.8 and run command by starting with python3 but no luck.
Then:
```
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
```
I also tried running the command by starting with python3 but it did not work either.
How can I fix it so that I can install new packages to my new version of Python? | 2019/11/07 | [
"https://Stackoverflow.com/questions/58758447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325117/"
] | It looks like at least on my Ubuntu 16.04, pip is shared for all Python versions in `/usr/lib/python3/dist-packages/pip`.
This is what I did to get it working again:
* `sudo apt remove python3-pip`
* `sudo python3.8 -m easy_install pip`
You might want to install the python 3.5 version of pip again with `sudo python3.5 -m easy_install pip`. | The problem is that package.linux\_distribution was deprecated starting with Python 3.5(?). and removed altogether for Python 3.8.
Use the distro package instead. This package only works on Linux however.
I ran into this problem after installing OpenCobolIDE on Linux Mint 20, having upgraded Python to the latest level. have submitted a code fix to the OpenCobolIDE author to review and test. I was able to get the IDE to start up and run with this fix.
Essentially the fix uses the distro package if available, otherwise it uses the old platform package. For example:
This code imports distro if available:
```
import platform
using_distro = False
try:
import distro
using_distro = True
except ImportError:
pass
```
Then you can test the value of *using\_distro* to determine whether to get the linux distro type from package or distro, for example:
```
if using_distro:
linux_distro = distro.like()
else:
linux_distro = platform.linux_distribution()[0]
``` |
58,758,447 | I had Python versions of 2.7 and 3.5. I wanted the install a newer version of Python which is python 3.8. I am using Ubuntu 16.04 and I can not just uninstall Python 3.5 due to the dependencies. So in order to run my scripts, I use `python3.8 app.py`. No problem so far. But when I want to install new packages via pip:
```
python3.8 -m pip install pylint
```
It throws an error:
```
AttributeError: module 'platform' has no attribute 'linux_distribution'
```
So far, I tried:
```
sudo update-alternatives --config python3
```
and chose python3.8 and run command by starting with python3 but no luck.
Then:
```
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
```
I also tried running the command by starting with python3 but it did not work either.
How can I fix it so that I can install new packages to my new version of Python? | 2019/11/07 | [
"https://Stackoverflow.com/questions/58758447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325117/"
] | Python 3.8 removed some stuff. I solved my problems with `pip` (specifically `pip install`) by installing `pip` with `curl`.
What worked for me was downloading `get-pip.py` and run it with Python 3.8:
```
cd ~/Downloads
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3.8 get-pip.py
```
Source: <https://pip.pypa.io/en/stable/installing/> | In my case, removing `python-pip-whl` package helped:
```
apt-get remove python-pip-whl
```
It removed also `pip` and `virtualenv`, so I had to install them again:
```
curl https://bootstrap.pypa.io/get-pip.py | python3
pip install virtualenv
``` |
58,758,447 | I had Python versions of 2.7 and 3.5. I wanted the install a newer version of Python which is python 3.8. I am using Ubuntu 16.04 and I can not just uninstall Python 3.5 due to the dependencies. So in order to run my scripts, I use `python3.8 app.py`. No problem so far. But when I want to install new packages via pip:
```
python3.8 -m pip install pylint
```
It throws an error:
```
AttributeError: module 'platform' has no attribute 'linux_distribution'
```
So far, I tried:
```
sudo update-alternatives --config python3
```
and chose python3.8 and run command by starting with python3 but no luck.
Then:
```
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
```
I also tried running the command by starting with python3 but it did not work either.
How can I fix it so that I can install new packages to my new version of Python? | 2019/11/07 | [
"https://Stackoverflow.com/questions/58758447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325117/"
] | It looks like at least on my Ubuntu 16.04, pip is shared for all Python versions in `/usr/lib/python3/dist-packages/pip`.
This is what I did to get it working again:
* `sudo apt remove python3-pip`
* `sudo python3.8 -m easy_install pip`
You might want to install the python 3.5 version of pip again with `sudo python3.5 -m easy_install pip`. | In my case, removing `python-pip-whl` package helped:
```
apt-get remove python-pip-whl
```
It removed also `pip` and `virtualenv`, so I had to install them again:
```
curl https://bootstrap.pypa.io/get-pip.py | python3
pip install virtualenv
``` |
58,758,447 | I had Python versions of 2.7 and 3.5. I wanted the install a newer version of Python which is python 3.8. I am using Ubuntu 16.04 and I can not just uninstall Python 3.5 due to the dependencies. So in order to run my scripts, I use `python3.8 app.py`. No problem so far. But when I want to install new packages via pip:
```
python3.8 -m pip install pylint
```
It throws an error:
```
AttributeError: module 'platform' has no attribute 'linux_distribution'
```
So far, I tried:
```
sudo update-alternatives --config python3
```
and chose python3.8 and run command by starting with python3 but no luck.
Then:
```
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
```
I also tried running the command by starting with python3 but it did not work either.
How can I fix it so that I can install new packages to my new version of Python? | 2019/11/07 | [
"https://Stackoverflow.com/questions/58758447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325117/"
] | In my case, removing `python-pip-whl` package helped:
```
apt-get remove python-pip-whl
```
It removed also `pip` and `virtualenv`, so I had to install them again:
```
curl https://bootstrap.pypa.io/get-pip.py | python3
pip install virtualenv
``` | Check if your wheels installation is old. I was getting this same error and fixed it with
`python3.8 -m pip install --upgrade pip setuptools wheel`
Pylint seems to work on python3.8 |
70,881,335 | I follow all the instructions on the official AWS website, but I still get the same error. I have tried several projects, each on the local server works quite normally as soon as it starts on AWS I get the next error 502 Bad Gateway.
* this seams like main problem : `ModuleNotFoundError: No module named 'ebddjango/wsgi'`
wsg file:
```
import os from django.core.wsgi
import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ebddjango.settings') application = get_wsgi_application()
```
config:
```
option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: ebddjango/wsgi:application
```
Status:
```
Updated: 2022-01-27 14:19:09.259000+00:00
Status: Ready
Health: Red
```
Erorr log
```
Jan 27 14:49:19 ip-172-31-8-170 web: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
Jan 27 14:49:19 ip-172-31-8-170 web: File "<frozen importlib._bootstrap>", line 983, in _find_and_load
Jan 27 14:49:19 ip-172-31-8-170 web: File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
Jan 27 14:49:19 ip-172-31-8-170 web: ModuleNotFoundError: No module named 'ebddjango/wsgi'
Jan 27 14:49:19 ip-172-31-8-170 web: [2022-01-27 14:49:19 +0000] [4399] [INFO] Worker exiting (pid: 4399)
Jan 27 14:49:19 ip-172-31-8-170 web: [2022-01-27 14:49:19 +0000] [4392] [INFO] Shutting down: Master
Jan 27 14:49:19 ip-172-31-8-170 web: [2022-01-27 14:49:19 +0000] [4392] [INFO] Reason: Worker failed to boot.
Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Starting gunicorn 20.1.0
Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Listening at: http://127.0.0.1:8000 (4407)
Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Using worker: gthread
Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4414] [INFO] Booting worker with pid: 4414
Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4414] [ERROR] Exception in worker process
Jan 27 14:49:20 ip-172-31-8-170 web: Traceback (most recent call last):
Jan 27 14:49:20 ip-172-31-8-170 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
Jan 27 14:49:20 ip-172-31-8-170 web: worker.init_process()
Jan 27 14:49:20 ip-172-31-8-170 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 92, in init_process
Jan 27 14:49:20 ip-172-31-8-170 web: super().init_process()
Jan 27 14:49:20 ip-172-31-8-170 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/workers/base.py", line 134, in init_process
Jan 27 14:49:20 ip-172-31-8-170 web: self.load_wsgi()
Jan 27 14:49:20 ip-172-31-8-170 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
Jan 27 14:49:20 ip-172-31-8-170 web: self.wsgi = self.app.wsgi()
Jan 27 14:49:20 ip-172-31-8-170 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
Jan 27 14:49:20 ip-172-31-8-170 web: self.callable = self.load()
Jan 27 14:49:20 ip-172-31-8-170 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
Jan 27 14:49:20 ip-172-31-8-170 web: return self.load_wsgiapp()
Jan 27 14:49:20 ip-172-31-8-170 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
Jan 27 14:49:20 ip-172-31-8-170 web: return util.import_app(self.app_uri)
Jan 27 14:49:20 ip-172-31-8-170 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/util.py", line 359, in import_app
Jan 27 14:49:20 ip-172-31-8-170 web: mod = importlib.import_module(module)
Jan 27 14:49:20 ip-172-31-8-170 web: File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module
Jan 27 14:49:20 ip-172-31-8-170 web: return _bootstrap._gcd_import(name[level:], package, level)
Jan 27 14:49:20 ip-172-31-8-170 web: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
Jan 27 14:49:20 ip-172-31-8-170 web: File "<frozen importlib._bootstrap>", line 983, in _find_and_load
Jan 27 14:49:20 ip-172-31-8-170 web: File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
Jan 27 14:49:20 ip-172-31-8-170 web: ModuleNotFoundError: No module named 'ebddjango/wsgi'
Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4414] [INFO] Worker exiting (pid: 4414)
Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Shutting down: Master
Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Reason: Worker failed to boot.
Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4422] [INFO] Starting gunicorn 20.1.0
-- More --
``` | 2022/01/27 | [
"https://Stackoverflow.com/questions/70881335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15393374/"
] | Seems I had exactly the same problem: I was following the [official tutorial](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html) but it was ending up with a 502 error.
I found my solution on [here](https://stackoverflow.com/a/68233544/), where they said:
>
> It's true that Python 3.7+ on Amazon Linux 2 platform needs gunicorn.
>
>
>
So what I did was simply running the following command just after installing django (point 3 of the *[Set up a Python virtual environment and install Django](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-setup-venv)* section of the tutorial)
```
pip install gunicorn
``` | In your .config file try
```
option_settings:
aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: ebddjango.settings
aws:elasticbeanstalk:container:python:
WSGIPath: ebddjango.wsgi:application
aws:elasticbeanstalk:environment:proxy:staticfiles:
/static: static
``` |
70,694,605 | I am new in fastapi and please help me!
I got an validation error when I change the default API response comes when I use response\_model in fastAPI.
The default API response is simple json like object from response\_model.
user.py
```
from fastapi import FastAPI, Response, status, HTTPException, Depends
from sqlalchemy.orm.session import Session
import models
import schemas
from database import get_db
app = FastAPI()
@app.post('/', response_model=schemas.UserOut)
def UserCreate(users:schemas.UserBase, db:Session = Depends(get_db)):
# print(db.query(models.User).filter(models.User.username == users.username).first().username)
if db.query(models.User).filter(models.User.email == users.email).first() != None:
if users.email == db.query(models.User).filter(models.User.email == users.email).first().email:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="email already exist")
hashed_password = hash(users.password)
users.password =hashed_password
new_user = models.User(**users.dict())
db.add(new_user)
db.commit()
db.refresh(new_user)
# return new_user #if i uncomment this code then it will give default response which i don't want
return {"status":True,"data":new_user, "message":"User Created Successfully"}
```
schemas.py
```
from pydantic import BaseModel, validator, ValidationError
from datetime import datetime
from typing import Optional, Text
from pydantic.networks import EmailStr
from pydantic.types import constr, conint
class UserBase(BaseModel):
name : str
email : EmailStr
country: str
city: str
state : str
address: str
phone: constr(min_length=10, max_length=10)
password: str
class UserOut(BaseModel):
name : str
email : EmailStr
country: str
city: str
state : str
address: str
phone: str
class Config:
orm_mode = True
```
Now, when I run this code it gives me errors like below mentioned.
```
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/amit/.local/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/home/amit/.local/lib/python3.6/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc
File "/home/amit/.local/lib/python3.6/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc
File "/home/amit/.local/lib/python3.6/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 259, in handle
await self.app(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 61, in app
response = await func(request)
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/routing.py", line 243, in app
is_coroutine=is_coroutine,
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/routing.py", line 137, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 7 validation errors for UserOut
response -> name
field required (type=value_error.missing)
response -> email
field required (type=value_error.missing)
response -> country
field required (type=value_error.missing)
response -> city
field required (type=value_error.missing)
response -> state
field required (type=value_error.missing)
response -> address
field required (type=value_error.missing)
response -> phone
field required (type=value_error.missing)
```
Below is the output i want:-
```
{
"status": true,
"data": {
"name": "raj",
"email": "rajshah123@gmail.com",
"country": "India",
"city": "surat",
"state": "gujarat",
"address": "str5654",
"phone": "6666888899"
},
"message": "User Created Successfully"
}
```
Thank you so much. | 2022/01/13 | [
"https://Stackoverflow.com/questions/70694605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11545151/"
] | C++ uses 0-based indexing, ie valid indices of a `N` sized container are `0,1,2...N-1`. If you try to use an index out of bounds your code invokes undefined behavior.
Look at the output of this code:
```
#include <iostream>
#include <string>
void foo(const std::string& text){
for(int i=text.size();i>=-1;i--){
std::cout << i << "\n";
}
}
int main() {
foo("madam");
}
```
It is
```
5
4
3
2
1
0
-1
```
Both `-1` and `5` are not elements of the string, because it has only `5` characters. (For `5` I am allowing myself to simplify the matter a bit, because strings have some oddities for accessing the one past last character null terminator. As `-1` definitely is out of bounds and with `std::string` you usually need not deal with the null terminator explicitly, this is ok for this answer).
Now look at the output of this code:
```
#include <iostream>
#include <string>
void foo(const std::string& text){
for(int i=text.size()-1;i>=0;i--){
std::cout << i << "\n";
}
}
int main() {
foo("madam");
}
```
It is
```
4
3
2
1
0
```
It iterates all characters of the input string. Thats why this is correct and the other is wrong.
When your code has undefined behavior anything can happen. The results may appear to be correct or partially correct. Wrong code does not necessarily produce obviously wrong output.
Note that `for(int i=text.size()-1;i>=0;i--)` is a problem when the size of the string is `0`, because `size()` returns an unsigned which wraps around to result in a large positive number. You can avoid that by using iterators instead. There are reverse iterators that make a reverse loop look the same as a forward loop:
```
#include <iostream>
#include <string>
int main() {
std::string text("123");
for (auto i = text.rbegin(); i != text.rend(); ++i) std::cout << *i;
}
```
Output
```
321
``` | In addition to the answer by 463035818\_is\_not\_a\_number, you can also construct a string from another string using iterators:
```cpp
#include <iostream>
#include <string>
int main() {
std::string text("123");
std::string rev(crbegin(text), crend(text));
std::cout << rev << '\n';
}
```
And there's [std::reverse](https://en.cppreference.com/w/cpp/algorithm/reverse)
```cpp
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string text("123");
reverse(begin(text), end(text));
std::cout << text << '\n';
}
```
But for a palindrome, you don't have to compare two whole strings. You just need to see of the first half of the string is equal to the reverse of the last half of the string. |
57,096,886 | I am new to learning python, I know this kind questions asked before but i am not able to find any solutions for it. Please check my code and correct me about decorator's functionality, Thank you.
```
def uppercase(func_one):
func_one = func_one()
return func_one.upper()
def split(func_two):
func_two = func_two()
return func_two.split()
@split
@uppercase
def CallFunction():
return "my string was in lower case"
res = CallFunction()
print(res)
``` | 2019/07/18 | [
"https://Stackoverflow.com/questions/57096886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3611036/"
] | Decorators are confusing and probably should be avoided till you are super experienced with python. That being said, chaining decorators is even more tricky:
```
from functools import wraps
def split(fn): # fn is the passed in function
@wraps(fn) # This means we can grabs its args and kwargs
def wrapped(*args, **kwargs): # This is the new function declaration
return fn(*args, **kwargs).split()
return wrapped
def uppercase(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return fn(*args, **kwargs).upper()
return wrapped
# Order matters. You can't call .upper() on a list
@split
@uppercase
def CallFunction():
return "my string was in lower case"
res = CallFunction()
print(res)
```
Alternatively if you don't want the order of these two decorators to matter than you need to handle the `list` case:
```
def uppercase(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
result = fn(*args, **kwargs)
if isinstance(result, list):
return [x.upper() for x in result]
return result.upper()
return wrapped
```
Reference: [How to make a chain of function decorators?](https://stackoverflow.com/q/739654/8150685) | You don't even need `functools`, you just need to grab the args you are passing.
Here's what you are missing: Add the args being passed inside a wrapper and define that wrapper to accept the args passed. Happy coding!
```
def uppercase(func_one):
def wrapper(*args):
x = func_one()
return x.upper()
return wrapper
def split(func_two):
def wrapper(*args):
y = func_two()
return y.split()
return wrapper
@split
@uppercase
def CallFunction():
return "my string was in lower case"
res = CallFunction()
print(res)
``` |
65,480,873 | I should test login functionality for this Django project, but it seems it can't login properly.
This is the login method on views.py
```
def login_request(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
request.session['username'] = username # Session test
if user is not None:
login(request, user)
messages.info(request, "You are now logged in as {username}.")
# Redirect da login alla dashboard dell'utente
return redirect("dashboard")
else:
messages.error("Invalis User")
#return render(request=request, template_name="dashboard.html", context={})
else:
messages.error(request, "Invalid username or password.")
form = AuthenticationForm()
return render(request=request, template_name="login.html", context={"login_form": form})
```
After login, it redirects to the dashboard which shows boards linked to the user, with this code
```
def dashboard(request):
usern = request.session.get('username')
userlog = User.objects.get(username=usern)
boards = BoardMember.objects.all().filter(user=userlog)
return render(request, "dashboard.html", {'board': boards,
'user': userlog})
```
Everything works fine, but when I test it in TestCase the error is "User matching query does not exist", test code is:
```
class ViewsTestCase(TestCase):
def setUp(self):
User.objects.create(username="Paolo", password="Paolo")
self.client = Client()
def test_getLogin(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
def test_login(self):
username = "Paolo"
password = "Paolo"
response = self.client.post("/dashboard/",
{
'username': username,
'password': password
})
self.assertEqual(response.status_code, 200)
user = User.objects.get(username="Paolo")
session = self.client.session
"""self.assertEqual(session['username'], username)
self.assertEqual(session['user_id'], user.id)
self.assertEqual(session['logged'], True)"""
```
Complete traceback:
```
Traceback (most recent call last):
File "/tests.py", line 52, in test_login
response = self.client.post("/dashboard/",
File "venv/lib/python3.8/site- packages/django/test/client.py", line 543, in post
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 356, in post
return self.generic('POST', path, post_data, content_type,
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 503, in request
raise exc_value
File “/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File “/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/views.py", line 56, in dashboard
userlog = User.objects.get(username=usern)
File "/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File “/venv/lib/python3.8/site-packages/django/db/models/query.py", line 406, in get
raise self.model.DoesNotExist(
ISW_ScrumBoard.models.User.DoesNotExist: User matching query does not exist.
``` | 2020/12/28 | [
"https://Stackoverflow.com/questions/65480873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7541182/"
] | To handle errors, you should use a try-catch statement. It should look something like this:
```
for(int i = 1, i<26, i++){
try{
getURL();
}
catch (Exception e){
System.out.print(e);
}
}
```
This is a very basic example of what can be done. This will, however, only skip the failed attempts, print the error, and continue to the next iteration of the loop. | You could use a set and start randomizing numbers in the range of your batches, while doing this you will be tracking which batch you already passed by adding them to the set, something like this:
```
int numberOfBatches = 26;
Set<Integer> set = new HashSet<>();
List<Integer> failedBatches = new ArrayList<>();
Random random = new Random();
while(set.size() <= numberOfBatches)
{
int ran = random.nextInt(numberOfBatches) + 1;
if(set.contains(ran)) continue;
set.add(ran);
try
{
getURL ("http://batchjob/" + Integer.toString(ran));
} catch (Exception e)
{
failedBatches.add(ran);
}
}
```
As an extra, you can save which batches failed |
65,480,873 | I should test login functionality for this Django project, but it seems it can't login properly.
This is the login method on views.py
```
def login_request(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
request.session['username'] = username # Session test
if user is not None:
login(request, user)
messages.info(request, "You are now logged in as {username}.")
# Redirect da login alla dashboard dell'utente
return redirect("dashboard")
else:
messages.error("Invalis User")
#return render(request=request, template_name="dashboard.html", context={})
else:
messages.error(request, "Invalid username or password.")
form = AuthenticationForm()
return render(request=request, template_name="login.html", context={"login_form": form})
```
After login, it redirects to the dashboard which shows boards linked to the user, with this code
```
def dashboard(request):
usern = request.session.get('username')
userlog = User.objects.get(username=usern)
boards = BoardMember.objects.all().filter(user=userlog)
return render(request, "dashboard.html", {'board': boards,
'user': userlog})
```
Everything works fine, but when I test it in TestCase the error is "User matching query does not exist", test code is:
```
class ViewsTestCase(TestCase):
def setUp(self):
User.objects.create(username="Paolo", password="Paolo")
self.client = Client()
def test_getLogin(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
def test_login(self):
username = "Paolo"
password = "Paolo"
response = self.client.post("/dashboard/",
{
'username': username,
'password': password
})
self.assertEqual(response.status_code, 200)
user = User.objects.get(username="Paolo")
session = self.client.session
"""self.assertEqual(session['username'], username)
self.assertEqual(session['user_id'], user.id)
self.assertEqual(session['logged'], True)"""
```
Complete traceback:
```
Traceback (most recent call last):
File "/tests.py", line 52, in test_login
response = self.client.post("/dashboard/",
File "venv/lib/python3.8/site- packages/django/test/client.py", line 543, in post
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 356, in post
return self.generic('POST', path, post_data, content_type,
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 503, in request
raise exc_value
File “/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File “/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/views.py", line 56, in dashboard
userlog = User.objects.get(username=usern)
File "/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File “/venv/lib/python3.8/site-packages/django/db/models/query.py", line 406, in get
raise self.model.DoesNotExist(
ISW_ScrumBoard.models.User.DoesNotExist: User matching query does not exist.
``` | 2020/12/28 | [
"https://Stackoverflow.com/questions/65480873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7541182/"
] | To handle errors, you should use a try-catch statement. It should look something like this:
```
for(int i = 1, i<26, i++){
try{
getURL();
}
catch (Exception e){
System.out.print(e);
}
}
```
This is a very basic example of what can be done. This will, however, only skip the failed attempts, print the error, and continue to the next iteration of the loop. | The following is an example of a single-threaded, infinite looping (also colled [Round-robin](https://en.wikipedia.org/wiki/Round-robin_scheduling)) scheduler with simple retry capabilities. I called "scrape" the routine that calls your batch job (*scraping* means indexing a website contents):
```
public static void main(String... args) throws Exception {
Runnable[] jobs = new Runnable[]{
() -> scrape("https://www.stackoverfow.com"),
() -> scrape("https://www.github.com"),
() -> scrape("https://www.facebook.com"),
() -> scrape("https://www.twitter.com"),
() -> scrape("https://www.wikipedia.org"),
};
for (int i = 0; true; i++) {
int remainingAttempts = 3;
while (remainingAttempts > 0) {
try {
jobs[i % jobs.length].run();
break;
} catch (Throwable err) {
err.printStackTrace();
remainingAttempts--;
}
}
}
}
private static void scrape(String website) {
System.out.printf("Doing my job against %s%n", website);
try {
Thread.sleep(100); // Simulate network work
} catch (InterruptedException e) {
throw new RuntimeException("Requested interruption");
}
if (Math.random() > 0.5) { // Simulate network failure
throw new RuntimeException("Ooops! I'm a random error");
}
}
```
You may want to add multi-thread capabilities (that is achieved by simply adding an `ExecutorService` guarded by a `Semaphore`) and some retry logic (for example only for certain type of errors and with a exponential backoff). |
65,480,873 | I should test login functionality for this Django project, but it seems it can't login properly.
This is the login method on views.py
```
def login_request(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
request.session['username'] = username # Session test
if user is not None:
login(request, user)
messages.info(request, "You are now logged in as {username}.")
# Redirect da login alla dashboard dell'utente
return redirect("dashboard")
else:
messages.error("Invalis User")
#return render(request=request, template_name="dashboard.html", context={})
else:
messages.error(request, "Invalid username or password.")
form = AuthenticationForm()
return render(request=request, template_name="login.html", context={"login_form": form})
```
After login, it redirects to the dashboard which shows boards linked to the user, with this code
```
def dashboard(request):
usern = request.session.get('username')
userlog = User.objects.get(username=usern)
boards = BoardMember.objects.all().filter(user=userlog)
return render(request, "dashboard.html", {'board': boards,
'user': userlog})
```
Everything works fine, but when I test it in TestCase the error is "User matching query does not exist", test code is:
```
class ViewsTestCase(TestCase):
def setUp(self):
User.objects.create(username="Paolo", password="Paolo")
self.client = Client()
def test_getLogin(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
def test_login(self):
username = "Paolo"
password = "Paolo"
response = self.client.post("/dashboard/",
{
'username': username,
'password': password
})
self.assertEqual(response.status_code, 200)
user = User.objects.get(username="Paolo")
session = self.client.session
"""self.assertEqual(session['username'], username)
self.assertEqual(session['user_id'], user.id)
self.assertEqual(session['logged'], True)"""
```
Complete traceback:
```
Traceback (most recent call last):
File "/tests.py", line 52, in test_login
response = self.client.post("/dashboard/",
File "venv/lib/python3.8/site- packages/django/test/client.py", line 543, in post
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 356, in post
return self.generic('POST', path, post_data, content_type,
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 503, in request
raise exc_value
File “/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File “/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/views.py", line 56, in dashboard
userlog = User.objects.get(username=usern)
File "/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File “/venv/lib/python3.8/site-packages/django/db/models/query.py", line 406, in get
raise self.model.DoesNotExist(
ISW_ScrumBoard.models.User.DoesNotExist: User matching query does not exist.
``` | 2020/12/28 | [
"https://Stackoverflow.com/questions/65480873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7541182/"
] | There are two parts of your requirement:
1. **Randomness**: For this, you can use [`Random#nextInt`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-).
2. **Skip the problematic call and continue with the remaining ones**: For this, you can use a `try-catch` block.
**Code:**
```
Random random = new Random();
for (i = 1; i < 26; i++) {
try {
getURL ("http://batchjob/" + Integer.toString(random.nextInt(25) + 1));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
```
**Note:** `random.nextInt(25)` returns an `int` value from `0` to `24` and thus, when `1` is added to it, the range becomes `1` to `25`. | You could use a set and start randomizing numbers in the range of your batches, while doing this you will be tracking which batch you already passed by adding them to the set, something like this:
```
int numberOfBatches = 26;
Set<Integer> set = new HashSet<>();
List<Integer> failedBatches = new ArrayList<>();
Random random = new Random();
while(set.size() <= numberOfBatches)
{
int ran = random.nextInt(numberOfBatches) + 1;
if(set.contains(ran)) continue;
set.add(ran);
try
{
getURL ("http://batchjob/" + Integer.toString(ran));
} catch (Exception e)
{
failedBatches.add(ran);
}
}
```
As an extra, you can save which batches failed |
65,480,873 | I should test login functionality for this Django project, but it seems it can't login properly.
This is the login method on views.py
```
def login_request(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
request.session['username'] = username # Session test
if user is not None:
login(request, user)
messages.info(request, "You are now logged in as {username}.")
# Redirect da login alla dashboard dell'utente
return redirect("dashboard")
else:
messages.error("Invalis User")
#return render(request=request, template_name="dashboard.html", context={})
else:
messages.error(request, "Invalid username or password.")
form = AuthenticationForm()
return render(request=request, template_name="login.html", context={"login_form": form})
```
After login, it redirects to the dashboard which shows boards linked to the user, with this code
```
def dashboard(request):
usern = request.session.get('username')
userlog = User.objects.get(username=usern)
boards = BoardMember.objects.all().filter(user=userlog)
return render(request, "dashboard.html", {'board': boards,
'user': userlog})
```
Everything works fine, but when I test it in TestCase the error is "User matching query does not exist", test code is:
```
class ViewsTestCase(TestCase):
def setUp(self):
User.objects.create(username="Paolo", password="Paolo")
self.client = Client()
def test_getLogin(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
def test_login(self):
username = "Paolo"
password = "Paolo"
response = self.client.post("/dashboard/",
{
'username': username,
'password': password
})
self.assertEqual(response.status_code, 200)
user = User.objects.get(username="Paolo")
session = self.client.session
"""self.assertEqual(session['username'], username)
self.assertEqual(session['user_id'], user.id)
self.assertEqual(session['logged'], True)"""
```
Complete traceback:
```
Traceback (most recent call last):
File "/tests.py", line 52, in test_login
response = self.client.post("/dashboard/",
File "venv/lib/python3.8/site- packages/django/test/client.py", line 543, in post
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 356, in post
return self.generic('POST', path, post_data, content_type,
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/venv/lib/python3.8/site-packages/django/test/client.py", line 503, in request
raise exc_value
File “/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File “/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/views.py", line 56, in dashboard
userlog = User.objects.get(username=usern)
File "/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File “/venv/lib/python3.8/site-packages/django/db/models/query.py", line 406, in get
raise self.model.DoesNotExist(
ISW_ScrumBoard.models.User.DoesNotExist: User matching query does not exist.
``` | 2020/12/28 | [
"https://Stackoverflow.com/questions/65480873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7541182/"
] | There are two parts of your requirement:
1. **Randomness**: For this, you can use [`Random#nextInt`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-).
2. **Skip the problematic call and continue with the remaining ones**: For this, you can use a `try-catch` block.
**Code:**
```
Random random = new Random();
for (i = 1; i < 26; i++) {
try {
getURL ("http://batchjob/" + Integer.toString(random.nextInt(25) + 1));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
```
**Note:** `random.nextInt(25)` returns an `int` value from `0` to `24` and thus, when `1` is added to it, the range becomes `1` to `25`. | The following is an example of a single-threaded, infinite looping (also colled [Round-robin](https://en.wikipedia.org/wiki/Round-robin_scheduling)) scheduler with simple retry capabilities. I called "scrape" the routine that calls your batch job (*scraping* means indexing a website contents):
```
public static void main(String... args) throws Exception {
Runnable[] jobs = new Runnable[]{
() -> scrape("https://www.stackoverfow.com"),
() -> scrape("https://www.github.com"),
() -> scrape("https://www.facebook.com"),
() -> scrape("https://www.twitter.com"),
() -> scrape("https://www.wikipedia.org"),
};
for (int i = 0; true; i++) {
int remainingAttempts = 3;
while (remainingAttempts > 0) {
try {
jobs[i % jobs.length].run();
break;
} catch (Throwable err) {
err.printStackTrace();
remainingAttempts--;
}
}
}
}
private static void scrape(String website) {
System.out.printf("Doing my job against %s%n", website);
try {
Thread.sleep(100); // Simulate network work
} catch (InterruptedException e) {
throw new RuntimeException("Requested interruption");
}
if (Math.random() > 0.5) { // Simulate network failure
throw new RuntimeException("Ooops! I'm a random error");
}
}
```
You may want to add multi-thread capabilities (that is achieved by simply adding an `ExecutorService` guarded by a `Semaphore`) and some retry logic (for example only for certain type of errors and with a exponential backoff). |
33,309,121 | I am using docker-compose to deploy a multicontainer python Flask web application. I'm having difficulty understanding how to create tables in the postgresql database during the build so I don't have to add them manually with psql.
My docker-compose.yml file is:
```
web:
restart: always
build: ./web
expose:
- "8000"
links:
- postgres:postgres
volumes:
- /usr/src/flask-app/static
env_file: .env
command: /usr/local/bin/gunicorn -w 2 -b :8000 app:app
nginx:
restart: always
build: ./nginx/
ports:
- "80:80"
volumes:
- /www/static
volumes_from:
- web
links:
- web:web
data:
restart: always
image: postgres:latest
volumes:
- /var/lib/postgresql
command: "true"
postgres:
restart: always
image: postgres:latest
volumes_from:
- data
ports:
- "5432:5432"
```
I dont want to have to enter psql in order to type in:
```
CREATE DATABASE my_database;
CREATE USER this_user WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE "my_database" to this_user;
\i create_tables.sql
```
I would appreciate guidance on how to create the tables. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33309121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2569531/"
] | >
> I dont want to have to enter psql in order to type in
>
>
>
You can simply use container's built-in init mechanism:
`COPY init.sql /docker-entrypoint-initdb.d/10-init.sql`
This makes sure that your sql is executed after DB server is properly booted up.
Take a look at their entrypoint [script](https://github.com/docker-library/postgres/blob/master/docker-entrypoint.sh). It does some preparations to start psql correctly and looks into `/docker-entrypoint-initdb.d/` directory for files ending in `.sh`, `.sql` and `.sql.gz`.
`10-` in filename is because files are processed in ASCII order. You can name your other init files like `20-create-tables.sql` and `30-seed-tables.sql.gz` for example and be sure that they are processed in order you need.
Also note that invoking command [does not](https://github.com/docker-library/postgres/blob/master/docker-entrypoint.sh#L116) specify the database. Keep that in mind if you are, say, migrating to docker-compose and your existing `.sql` files don't specify DB either.
Your files will be processed at container's first start instead of `build` stage though. Since Docker Compose stops images and then resumes them, there's almost no difference, but if it's crucial for you to init the DB at `build` stage I suggest still using built-in init method by calling `/docker-entrypoint.sh` from your dockerfile and then cleaning up at `/docker-entrypoint-initdb.d/` directory. | I would create the tables as part of the build process. Create a new `Dockerfile` in a new directory `./database/`
```
FROM postgres:latest
COPY . /fixtures
WORKDIR /fixtures
RUN /fixtures/setup.sh
```
`./database/setup.sh` would look something like this:
```
#!/bin/bash
set -e
/etc/init.d/postgresql start
psql -f create_fixtures.sql
/etc/init.d/postgresql stop
```
Put your create user, create database, create table sql (and any other fixture data) into a `create_fixtures.sql` file in the `./database/` directory.
and finally your `postgres` service will change to use `build`:
```
postgres:
build: ./database/
...
```
Note: Sometimes you'll need a `sleep 5` (or even better a script to poll and wait for postgresql to start) after the `/etc/init.d/postgresql start` line. In my experience either the init script or the psql client handles this for you, but I know that's not the case with mysql, so I thought I'd call it out. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.