content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Locust is gave me error when trying to running on my machine mac m1
I have error when trying to run locust load test on my machine mac m1 it gaves me
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/geventhttpclient/_parser.cpython-310-darwin.so, 0x0002):
tried: '... | Locust is gave me error when trying to running on my machine mac m1 | I have error when trying to run locust load test on my machine mac m1 it gaves me
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/geventhttpclient/_parser.cpython-310-darwin.so, 0x0002):
tried: '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-pa... | [] | [] | [
"run VS code without checked Open using Rosetta helps me.\n"
] | [
-1
] | [
"load_testing",
"locust",
"performance_testing",
"python"
] | stackoverflow_0073065330_load_testing_locust_performance_testing_python.txt |
Q:
composition over inheritance, even is it a Is-a relationship
I try to use composition even the relationship is: is-a.
So I have a Animal class and I have a Zebra class:
class Name:
pass
class Age:
pass
class Zebra():
pass
class Animal:
def __init__(self, name_animal, age_animal) -> None:
... | composition over inheritance, even is it a Is-a relationship | I try to use composition even the relationship is: is-a.
So I have a Animal class and I have a Zebra class:
class Name:
pass
class Age:
pass
class Zebra():
pass
class Animal:
def __init__(self, name_animal, age_animal) -> None:
self.name_animal = name_animal
self.age_animal = age_... | [
"I don't recommend to use composition in this case. This is a use-case for inheritance. But academic questions also deserve an answer.\nAdd a constructor to Zebra that initializes and stores an Animal instance and delegate __repr__:\nclass Animal:\n def __init__(self, name_animal, age_animal) -> None:\n s... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074154656_python.txt |
Q:
Python: how to type hint a dataclass?
The code below works, but I'm getting the following warning by PyCharm:
Cannot find reference __annotations__ in '(...) -> Any'.
I guess it's because I'm using Callable. I didn't find something like Dataclass. Which type should I use instead?
from __future__ import annotatio... | Python: how to type hint a dataclass? | The code below works, but I'm getting the following warning by PyCharm:
Cannot find reference __annotations__ in '(...) -> Any'.
I guess it's because I'm using Callable. I didn't find something like Dataclass. Which type should I use instead?
from __future__ import annotations
from dataclasses import dataclass
from t... | [
"In this particular example you can just hint it directly:\nfrom dataclasses import dataclass\n\n@dataclass\nclass Fruit:\n x: str\n\ndef get_cls() -> type[Fruit]:\n return Fruit\n\nattrs = get_cls().__annotations__\nprint(attrs)\n\n$ python d.py\n{'x': <class 'str'>}\n$ mypy d.py\nSuccess: no issues found in... | [
3,
2,
2
] | [] | [] | [
"python",
"python_dataclasses",
"python_typing"
] | stackoverflow_0074153330_python_python_dataclasses_python_typing.txt |
Q:
How do I use line_profiler on a wrapped function?
I've been trying to use line_profiler on a wrapped function. However, the wrapper function gets profiled instead of the wrapped function. The executable snippet below shows that I can see that my @decorate wrapper function gets profiled instead of my d() function.
... | How do I use line_profiler on a wrapped function? | I've been trying to use line_profiler on a wrapped function. However, the wrapper function gets profiled instead of the wrapped function. The executable snippet below shows that I can see that my @decorate wrapper function gets profiled instead of my d() function.
Snippet: testy_profiler.py
from line_profiler import Li... | [
"According to this issue, line profiler will not profile code inside a decorated function, and will instead profile the decorator. (This issue is a month old at time of writing, and may have changed by the time you read this answer.)\nThere is a workaround, however.\nIf you want to profile the function which the de... | [
1,
0
] | [] | [] | [
"line_profiler",
"python",
"wrapper"
] | stackoverflow_0074155217_line_profiler_python_wrapper.txt |
Q:
SQL database with a column being a list or a set
With a SQL database (in my case Sqlite, using Python), what is a standard way to have a column which is a set of elements?
id name items_set
1 Foo apples,oranges,tomatoes,ananas
2 Bar tomatoes,bananas
...
A simple implementation is using
CR... | SQL database with a column being a list or a set | With a SQL database (in my case Sqlite, using Python), what is a standard way to have a column which is a set of elements?
id name items_set
1 Foo apples,oranges,tomatoes,ananas
2 Bar tomatoes,bananas
...
A simple implementation is using
CREATE TABLE data(id int, name text, items_set text);
b... | [
"To have a well structured SQL database, you should extract the items to their own table and use a join table between the main table and the items table\nI'm not familiar with the Sqlite syntax but you should be able to create the tables with\nCREATE TABLE entities(id int, name text); \nCREATE TABLE entity_items(e... | [
1,
1,
1,
0
] | [] | [] | [
"performance",
"python",
"set",
"sql",
"sqlite"
] | stackoverflow_0074156002_performance_python_set_sql_sqlite.txt |
Q:
"getaddrinfo failed", what does that mean?
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args) gaierror: [Errno 11004]
getaddrinfo failed
Getting this error when launching the hello world sample from here:
http://bottlepy.org/docs/dev/
A:
It most likely means the h... | "getaddrinfo failed", what does that mean? | File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args) gaierror: [Errno 11004]
getaddrinfo failed
Getting this error when launching the hello world sample from here:
http://bottlepy.org/docs/dev/
| [
"It most likely means the hostname can't be resolved.\nimport socket\nsocket.getaddrinfo('localhost', 8080)\n\nIf it doesn't work there, it's not going to work in the Bottle example. You can try '127.0.0.1' instead of 'localhost' in case that's the problem.\n",
"The problem, in my case, was that some install at ... | [
84,
15,
6,
5,
3,
1
] | [] | [] | [
"bottle",
"python"
] | stackoverflow_0007334199_bottle_python.txt |
Q:
How to cross-compile a single python library for ARM
I'm trying to install this spidev library on a machine with an arm processor. It is already running python 3.5, but it does not have any build tools, and therefore can't install the package directly. I've found a lot of tutorials outlining how to build python fo... | How to cross-compile a single python library for ARM | I'm trying to install this spidev library on a machine with an arm processor. It is already running python 3.5, but it does not have any build tools, and therefore can't install the package directly. I've found a lot of tutorials outlining how to build python for a specific architecture, but I just want to build a libr... | [
"I was able to install spidev on ARM architecture by building a wheel on x86.\nOn x86_84/AMD64 machine.\n$ git clone https://github.com/doceme/py-spidev\n$ cd py-spidev\n$ python3 setup.py bdist_wheel --plat-name=linux-aarch64\n\nCopy the aarch64 wheel to arm machine.\nOn arm64 machine\n$ python3 -m pip install spi... | [
0
] | [] | [] | [
"python",
"python_packaging"
] | stackoverflow_0058346120_python_python_packaging.txt |
Q:
Convert nested dict to dataframe
I want to convert a nested dict to dataframe
{
'2022-09-08T15:00:00Z': {
'INMET_BRASILIA_A001_M':
{
"DVENTO": [
{'value' : '95.0', 'quality': 'qf-GOOD', 'quality_flag': 'GOOD','structure' : 'INMET_BRASILIA_A001_M', 'element' : 'DVEN... | Convert nested dict to dataframe | I want to convert a nested dict to dataframe
{
'2022-09-08T15:00:00Z': {
'INMET_BRASILIA_A001_M':
{
"DVENTO": [
{'value' : '95.0', 'quality': 'qf-GOOD', 'quality_flag': 'GOOD','structure' : 'INMET_BRASILIA_A001_M', 'element' : 'DVENTO'}],
"TD_MN_C":[
... | [
"There are various ways to achieve the desired output.\nAssuming that the dictionary is stored in the variable dictionary, one can start by doing the following\ndf = pd.DataFrame.from_dict(dictionary, orient='index').stack().apply(pd.Series).reset_index(level=1, drop=True)\n\n[Out]:\n\n ... | [
5,
3,
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074155508_dataframe_pandas_python.txt |
Q:
Multiple Nested if Python
user_input_1 = string(input(“Y/N”))
user_input_2 = string(input(“Y/N”)
...
user_input_10 = string(input(“Y/N”))
Assuming that for each combination of inputs the code has to do another calculation, how do you avoid multiple if-elif-else?
For example:
if user_input_1 == “Y”:
if user_in... | Multiple Nested if Python | user_input_1 = string(input(“Y/N”))
user_input_2 = string(input(“Y/N”)
...
user_input_10 = string(input(“Y/N”))
Assuming that for each combination of inputs the code has to do another calculation, how do you avoid multiple if-elif-else?
For example:
if user_input_1 == “Y”:
if user_input_2 == “Y”:
if user_i... | [
"I think a better way of representing such logical structure would be nested-dictionary. It can be written as:\ndef perform_action_on_user_input(ui1, ui2, ui3)\n decision_tree = {\n \"Y\": {\n \"Y\": {\n \"Y\": {do_yyy},\n \"N\": {do_yyn}\n },\n ... | [
2
] | [] | [] | [
"conditional_statements",
"if_statement",
"python",
"python_3.x"
] | stackoverflow_0074156245_conditional_statements_if_statement_python_python_3.x.txt |
Q:
How can I reuse and SQLAlchemy filter?
I have a class which interacts with the SQLAlchemy objects through various methods and it issues queries for various tasks. Some of these queries use the same filter for example:
def get_all_expired(self,my_model):
q = session.query(my_model).filter(
my_model.sta... | How can I reuse and SQLAlchemy filter? | I have a class which interacts with the SQLAlchemy objects through various methods and it issues queries for various tasks. Some of these queries use the same filter for example:
def get_all_expired(self,my_model):
q = session.query(my_model).filter(
my_model.status == 'OK',
my_model.is_validated =... | [
"Ok so this is not very well documented, in the official documentation I did not find any examples, or even a mention of the fact that you can unpack multiple filters from a list (maybe they assume it is obvious, who knows).\nBut the following can be done. Make and unpack a list with the filters, for example:\ndef ... | [
0
] | [
"How aboot this?\nexpired_filter = session.query(MyModel).filter(\n MyModel.status == 'OK',\n MyModel.is_validated == True,\n MyModel.expires_at <= plum_dt.now()\n )\n \n def get_all_expired(self):\n return expired_filter.all()\n \n def update_all_expired(self):\n e... | [
-1
] | [
"flask_sqlalchemy",
"python",
"sqlalchemy"
] | stackoverflow_0074053511_flask_sqlalchemy_python_sqlalchemy.txt |
Q:
Flask csv problem converting string to float
I'm creating an application in Flask and first I need to load a csv base (just numbers) from string to float.
This is a sample of my database:
This is my code:
from flask import Flask, jsonify, render_template, request
import csv
import codecs
app = Flask(__name__)
@... | Flask csv problem converting string to float | I'm creating an application in Flask and first I need to load a csv base (just numbers) from string to float.
This is a sample of my database:
This is my code:
from flask import Flask, jsonify, render_template, request
import csv
import codecs
app = Flask(__name__)
@app.route("/submit", methods=["POST"])
def submit(... | [
"Solved, the delimiter has to be a semicolon instead of a comma.\nfor row in csv.reader(stream, delimiter =';', quoting=csv.QUOTE_NONNUMERIC, dialect=\"excel\"):\n\n"
] | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074152496_csv_python.txt |
Q:
how to make integer as Key and List as Value in Map in Python?
I have this input
arr = [1,2,1,3,4,2,4,2]
What I'm trying to achieve is make elements of the given list as keys of a map and its indices as values in the form of a list.
Like this :
mp = {1:[0,2],2:[1,5,7],3:[3],4:[4,6]}
And what will be the time-com... | how to make integer as Key and List as Value in Map in Python? | I have this input
arr = [1,2,1,3,4,2,4,2]
What I'm trying to achieve is make elements of the given list as keys of a map and its indices as values in the form of a list.
Like this :
mp = {1:[0,2],2:[1,5,7],3:[3],4:[4,6]}
And what will be the time-complexity for this?
| [
"from collections import defaultdict\n\nresult = defaultdict(list)\n\nfor pos, num in enumerate(array):\n result[num].append(pos)\n \n\nTime complexity is O(n), there is only one loop and all things in the loop (looking up thing in dictionary, appending an item) are constant wrt. the number of items.\n",
"arr... | [
2,
1,
0
] | [] | [] | [
"dictionary",
"hashmap",
"list",
"python",
"python_3.x"
] | stackoverflow_0074155924_dictionary_hashmap_list_python_python_3.x.txt |
Q:
How to count the number of rows after applying a condition another column, while grouping?
df1 = [[aa, '21/01/2022', ''], [aa, '22/01/2022', '22/01/2022'],
[aa, '22/01/2022', ''], [aa, '22/01/2022', ''],
[bb, '25/01/2022', '25/01/2022'],[bb, '26/01/2022', ''],
[bb, '26/01/2022', ''],[cc, '21/... | How to count the number of rows after applying a condition another column, while grouping? | df1 = [[aa, '21/01/2022', ''], [aa, '22/01/2022', '22/01/2022'],
[aa, '22/01/2022', ''], [aa, '22/01/2022', ''],
[bb, '25/01/2022', '25/01/2022'],[bb, '26/01/2022', ''],
[bb, '26/01/2022', ''],[cc, '21/01/2022', ''],
[cc, '21/01/2022', '22/01/2022'], [cc, '21/01/2022', '']]
df = pd.DataFr... | [
"Code:\nimport numpy as np\ndf = df.replace(r'', np.NaN)\ndf['CouNT'] = df.groupby(df.groupby(['userid'])['Signed_up'].ffill()+df['userid']).cumcount()\n\nUpdated code:\nHere, you can handle the group of NaN, by fill with unique value or index value, However I have fill with empty string and later concate with user... | [
0
] | [] | [] | [
"counting",
"cumsum",
"group_by",
"python"
] | stackoverflow_0074155553_counting_cumsum_group_by_python.txt |
Q:
Writing pandas/numpy statements in python functions
I am working on multiple data sets with similar data attributes (column names) in jupyter notebook. But it is really tiresome to run all the commands again and again with multiple data sets to achieve the same target. Can anyone let me know if I can automate the ... | Writing pandas/numpy statements in python functions | I am working on multiple data sets with similar data attributes (column names) in jupyter notebook. But it is really tiresome to run all the commands again and again with multiple data sets to achieve the same target. Can anyone let me know if I can automate the process and run this for various data sets. Let's say I'm... | [
"IIUC, your issue is that something like print(df) doesn't show as pretty as if you just have df as the last line in a Jupyter cell.\nYou can have the pretty output whenever you want (as long as your jupyter is updated) by using display!\nModifying your code:\ndef process_data(file):\n data = pd.read_csv(file, l... | [
1
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074156058_dataframe_numpy_pandas_python_python_3.x.txt |
Q:
Get the ID of inserted item if new, or the existing ID if it's not new
Since the column t is UNIQUE, foo won't be inserted twice:
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute("CREATE TABLE data(id INTEGER PRIMARY KEY AUTOINCREMENT, t TEXT UNIQUE);")
c = conn.cursor()
c.execute("INSERT OR IGNORE I... | Get the ID of inserted item if new, or the existing ID if it's not new | Since the column t is UNIQUE, foo won't be inserted twice:
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute("CREATE TABLE data(id INTEGER PRIMARY KEY AUTOINCREMENT, t TEXT UNIQUE);")
c = conn.cursor()
c.execute("INSERT OR IGNORE INTO data(t) VALUES (?)", ("foo", ))
print(c.lastrowid) # 1
c.execute("INSER... | [
"Yes, there is the RETURNING clause for the INSERT statement. Please see docs for details https://www.sqlite.org/lang_returning.html\nNote, if you use INSERT OR IGNORE, nothing happens when conflict occurs and nothing is returned. You need to use the UPSERT syntax, to force a dummy update in case of a conflict to m... | [
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0074156387_python_sqlite.txt |
Q:
pytest is not running any tests
My tests are in the following folder structure. Though I have also placed a sample test in the root, which doesn't work either. I get no tests ran in 6.08s
root/
test/
integrations/
test_sample.py
__init__.py
__init__.py
I hav... | pytest is not running any tests | My tests are in the following folder structure. Though I have also placed a sample test in the root, which doesn't work either. I get no tests ran in 6.08s
root/
test/
integrations/
test_sample.py
__init__.py
__init__.py
I have tried using the command pytest by ... | [
"You need to write a test as function with a name beginning with test. See pytest's docs: test-discovery.\nIn this test or function:\n\ninstantiate your class\nand run the class' method or function\n\nimport pytest\n\n# this class will be tested \nclass ClassUnderTest:\n def add(self):\n return \"it ran\"... | [
3,
0
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074156244_pytest_python.txt |
Q:
How to store datetime with millisecond precision in SQL database
With a float value representing date and time with millisecond precision:
import datetime
float_time = 1485538757.29289
print datetime.datetime.fromtimestamp(float_time)
prints:
2017-01-27 09:39:17.292890
To store it in db:
from sqlalchemy import ... | How to store datetime with millisecond precision in SQL database | With a float value representing date and time with millisecond precision:
import datetime
float_time = 1485538757.29289
print datetime.datetime.fromtimestamp(float_time)
prints:
2017-01-27 09:39:17.292890
To store it in db:
from sqlalchemy import Column, DateTime
from sqlalchemy.ext.declarative import declarative_ba... | [
"It depends on the SQL database you're using. They differ in precision:\nPostgreSQL: Default 1 microsecond. (See docs for far-future/past caveats.)\nMySQL: Default 1 second. Millisecond / microsecond precision optional after version 5.6.4.\nMariaDB: Default 1 second. Millisecond / microsecond precision optional sin... | [
6,
0,
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0041900415_python_sql_sqlalchemy.txt |
Q:
Return element from list matching first character pattern
I have the following list
students = ['44560 Susan Pierce 46', '49509 John Lee 74', '49510 Kim Note 76', '49519 Jennifer Six 50', '49556 Maria Cruz 67', '49586 Martin Lewis 79', '55900 Richard White 100']
I created this function which is supposed to return... | Return element from list matching first character pattern | I have the following list
students = ['44560 Susan Pierce 46', '49509 John Lee 74', '49510 Kim Note 76', '49519 Jennifer Six 50', '49556 Maria Cruz 67', '49586 Martin Lewis 79', '55900 Richard White 100']
I created this function which is supposed to return the entire element of the list if the inputted number matches ... | [
"This is because using return will immediately break the loop in the first iteration.\nYou need to temporarily save all the results and then return your results after the loop is finished.\nYou could do this as follows:\nstudents = ['44560 Susan Pierce 46', '49509 John Lee 74', '49510 Kim Note 76', '49519 Jennifer ... | [
1,
0
] | [] | [] | [
"for_loop",
"function",
"if_statement",
"python"
] | stackoverflow_0074156415_for_loop_function_if_statement_python.txt |
Q:
Select random dictionary
Let's say I have 2 dictionaries:
pal1 = {1:"bli", 2:"bla", 3:"blub"}
pal2 = {1:"blib", 2:"blab", 3:"bleb"}
Now I want to randomly select one of the two for further usage. My thought was creating another dictionary and assign a number to each dictionary name like so:
palettes = {1:"pal1", ... | Select random dictionary | Let's say I have 2 dictionaries:
pal1 = {1:"bli", 2:"bla", 3:"blub"}
pal2 = {1:"blib", 2:"blab", 3:"bleb"}
Now I want to randomly select one of the two for further usage. My thought was creating another dictionary and assign a number to each dictionary name like so:
palettes = {1:"pal1", 2:"pal2"}
now the random part... | [
"from random import choice\npal1 = {1:\"bli\", 2:\"bla\", 3:\"blub\"}\npal2 = {1:\"blib\", 2:\"blab\", 3:\"bleb\"}\nchoice([pal1, pal2])\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"python",
"random"
] | stackoverflow_0074122870_dictionary_python_random.txt |
Q:
how to call a method in another method in python
I have two methods method1 and method2. we can not call method2 alone and it should be in method1. how can i make sure method1 has return statement in this scenario.
def method1(list1, dict1):
for i in list1:
updated_list = i.replace(".",",") #some logic that wil... | how to call a method in another method in python | I have two methods method1 and method2. we can not call method2 alone and it should be in method1. how can i make sure method1 has return statement in this scenario.
def method1(list1, dict1):
for i in list1:
updated_list = i.replace(".",",") #some logic that will update the list not exactly this
method2(updated_l... | [
"Your inline comment is correct on line 4, you could just use return method2(updated_list, dict). On a side note, you'll want to rename your variables since list and dict are already reserved keywords in the Python standard library. method1 needs to have the loop indented, and the inline comment after that should b... | [
0,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074156487_function_python.txt |
Q:
date in pandas to csv in general format
Despite I had value to pandas data frame as string, it is being transformed to date format when I export data frame to CSV file.
I have tried various methods, but the outcome is the same.
Did anyone have a similar problem? If yes, how did you solve it?
A:
I think it has no... | date in pandas to csv in general format | Despite I had value to pandas data frame as string, it is being transformed to date format when I export data frame to CSV file.
I have tried various methods, but the outcome is the same.
Did anyone have a similar problem? If yes, how did you solve it?
| [
"I think it has nothing to do with pandas or python but with the excel or google docs or any other spreadsheet software you are using.\nIn the case of excel, you can use =TEXT(date, format) to convert the date into the text format.\nEDIT: \nYou can also specify the column as text instead of using formula.\n"
] | [
2
] | [] | [] | [
"csv",
"date",
"datetime",
"pandas",
"python"
] | stackoverflow_0074156595_csv_date_datetime_pandas_python.txt |
Q:
In Python 3.8+ is there a way to create a "named" type union?
I have a very long type union that I use in a number of places. I would like to name this union and use the name in place of the long list of types that make up the union.
In other words instead of writing this:
def foo(self) -> Union[Foo, Bar, Fizz, Bu... | In Python 3.8+ is there a way to create a "named" type union? | I have a very long type union that I use in a number of places. I would like to name this union and use the name in place of the long list of types that make up the union.
In other words instead of writing this:
def foo(self) -> Union[Foo, Bar, Fizz, Buzz, Splat, Bang, Woo, Wizz]:
...
I would like to write:
def fo... | [
"It looks like Python calls them \"Type Aliases\" and the docs can be found here: https://mypy.readthedocs.io/en/stable/kinds_of_types.html#type-aliases\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x",
"python_typing"
] | stackoverflow_0074156628_python_python_3.x_python_typing.txt |
Q:
CPython list.insert(index) real time complexity, when all inserts occur at same index?
My noob question is in the title
I have some code that iteratively builds a list. All inserts are always at the second-to-last position. Is list.insert(-1, value) truly an O(1) operation in the CPython implementation?
O(?) -> wh... | CPython list.insert(index) real time complexity, when all inserts occur at same index? | My noob question is in the title
I have some code that iteratively builds a list. All inserts are always at the second-to-last position. Is list.insert(-1, value) truly an O(1) operation in the CPython implementation?
O(?) -> what I want to do
some_list = ['always first', 'always last']
for i in range(10000):
some_... | [
"Why don't you just write:\nlast = some_list.pop()\nfor i in range(10000):\n some_list.append(value)\nsome_list.append(last)\n\nand you're guaranteed O(1) and more efficient code.\nBut I suspect your first example is also O(1) since only one element has to be moved every time. It just won't be as efficient as t... | [
1
] | [] | [] | [
"append",
"cpython",
"insert",
"python",
"time_complexity"
] | stackoverflow_0074156480_append_cpython_insert_python_time_complexity.txt |
Q:
Coverting one of the multi-index column labels to a column with row for each value of the column label
My df has multi-index column label like below (six columns):
Col lvl 1 01/02/89 31/12/97 15/07/65
Col lvl 2 ID1 ID2 ID1 ID2 ID1 ID2
Apple dec box coy sil mcd les
... | Coverting one of the multi-index column labels to a column with row for each value of the column label | My df has multi-index column label like below (six columns):
Col lvl 1 01/02/89 31/12/97 15/07/65
Col lvl 2 ID1 ID2 ID1 ID2 ID1 ID2
Apple dec box coy sil mcd les
Banana fox dog bil neo dol nit
Carrot kil not bis xev min les
And... | [
"It looks like you want to stack the 2nd level:\nout = df.stack(-2).reset_index()\nout.columns = ['Fruit', 'Date', 'ID1', 'ID2']\nout.columns.name = None\nprint(out)\n\nOutput:\n Fruit Date ID1 ID2\n0 Apple 01/02/89 dec box\n1 Apple 15/07/65 mcd les\n2 Apple 31/12/97 coy sil\n3 Banana 01/... | [
1
] | [] | [] | [
"dataframe",
"melt",
"multi_index",
"pandas",
"python"
] | stackoverflow_0074156460_dataframe_melt_multi_index_pandas_python.txt |
Q:
Python tkinter I can't control my btns using list, help me
I want to make btn using for loop
import tkinter as tk
root = tk.Tk()
win_width = 355
win_height = 312
root.geometry("{}x{}+{}+{}".format(win_width,win_height,
int(root.winfo_screenwidth()/2 - win_width/2),
... | Python tkinter I can't control my btns using list, help me | I want to make btn using for loop
import tkinter as tk
root = tk.Tk()
win_width = 355
win_height = 312
root.geometry("{}x{}+{}+{}".format(win_width,win_height,
int(root.winfo_screenwidth()/2 - win_width/2),
int(root.winfo_screenheight()/2 - win_... | [
"as @jasonharper 's link says this problem can be solve really easily\nin the for-loop you've to change this line\nbtn = tk.Button(root,text=' ',command=lambda: set_beat(btn_list[i],i))\n\nto this line:\nbtn = tk.Button(root,text=' ',command=lambda i=i :set_beat(btn_list[i],i))\n\nthe problem is that in thi... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074155962_python_tkinter.txt |
Q:
Python random.choice() fails to work in a function
I'm having trouble getting Pythons random.choice to work
Here's the working code:
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F... | Python random.choice() fails to work in a function | I'm having trouble getting Pythons random.choice to work
Here's the working code:
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q'... | [
"The parameters of the function letters, symbols, numbers are named like the arrays. So you are trying to make a random choice of a int. Pas by parameter the list of letters, symbols, numbers too.\n",
"The arguments of your method are named the same as your lists.\nJust change up the names of your lists like this... | [
1,
1,
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0074156647_python_random.txt |
Q:
ImportError: cannot import name 'app' from 'mypackage' (unknown location)
I know that there are a low of similar issues, but none helped me, so I am writing a new one. Here is my directory structure:
- mypackage
- __init__.py
- run.py
- requirements.txt
The run.py content:
from mypackage import app
app.run(h... | ImportError: cannot import name 'app' from 'mypackage' (unknown location) | I know that there are a low of similar issues, but none helped me, so I am writing a new one. Here is my directory structure:
- mypackage
- __init__.py
- run.py
- requirements.txt
The run.py content:
from mypackage import app
app.run(host='localhost', port=3648)
The mypackage/_init_.py content:
from flask import... | [
"tl;dr: rename your package\nWas your package really named mypackage? I guess not. :)\nI had had the same error. In my case, the name I chose for mypackage happened to be the name of an existing Python library I didn't know about. \nOnce I renamed my package, the error disappeared.\n",
"I guess when you are runni... | [
9,
3,
3,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0055657036_python.txt |
Q:
How to interactively change the animation arguments
I would like to interactively change a matplotlib.animation argument depending on the value provided by a GUI.
Example:
I prepared an example code which I show below, where I am trying to change the interval argument of animation based on a value provided by the... | How to interactively change the animation arguments | I would like to interactively change a matplotlib.animation argument depending on the value provided by a GUI.
Example:
I prepared an example code which I show below, where I am trying to change the interval argument of animation based on a value provided by the user through a spinBox created with tkinter.
Problem:
... | [
"We have to redraw the animation using fig.canvas.draw() when the animation is created inside the function button:\ndef button():\n global spinBoxValue, CumulativeX, CumulativeY, ani\n spinBoxValue = aSpinbox.get()\n CumulativeX, CumulativeY = [], [] # This is optional\n \n # To stop the background a... | [
2
] | [] | [] | [
"animation",
"callback",
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0074156144_animation_callback_matplotlib_python_tkinter.txt |
Q:
Make a one row dataframe from 1 list - Pyspark
I searched here but I didn't find anything that worked for me.
Basically, I have only 1 row list (with some columns) and I have to write them in a parquet table.
I need to "cast" that from list to DF, but for only 1 row, I have many problems!
from pyspark.sql import W... | Make a one row dataframe from 1 list - Pyspark | I searched here but I didn't find anything that worked for me.
Basically, I have only 1 row list (with some columns) and I have to write them in a parquet table.
I need to "cast" that from list to DF, but for only 1 row, I have many problems!
from pyspark.sql import Window,Row
from pyspark.sql import functions as F
fro... | [
"If you modify your dataset to remove spark F function & types, it works:\nfrom pyspark.sql import Window,Row\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.session import SparkSession\nfrom pyspark.sql.types import *\nimport datetime\n\ntablename='table'\nstart_time = datetime.datetime.now()\ncount_1 = ... | [
1
] | [] | [] | [
"dataframe",
"list",
"pyspark",
"python"
] | stackoverflow_0074155883_dataframe_list_pyspark_python.txt |
Q:
Pandas dataframe get expanding/rolling value counts
Is it possible to create value counts for a series in a cumulative/expanding fashion? E.g. for the following series
pd.Series(['a', 'a', 'b', 'c', 'c'])
I'd want
[ 'a', 'b', 'c'
1, 0, 0
2, 0, 0
2, 1, 0
2, 1, 1
2, 1, 2]
A:
Enco... | Pandas dataframe get expanding/rolling value counts | Is it possible to create value counts for a series in a cumulative/expanding fashion? E.g. for the following series
pd.Series(['a', 'a', 'b', 'c', 'c'])
I'd want
[ 'a', 'b', 'c'
1, 0, 0
2, 0, 0
2, 1, 0
2, 1, 1
2, 1, 2]
| [
"Encode the series into indicator variables and use cumsum\ns.str.get_dummies().cumsum()\n\n\n a b c\n0 1 0 0\n1 2 0 0\n2 2 1 0\n3 2 1 1\n4 2 1 2\n\n"
] | [
4
] | [] | [] | [
"pandas",
"python",
"rolling_computation",
"series"
] | stackoverflow_0074156723_pandas_python_rolling_computation_series.txt |
Q:
Updating labels with user input from MDTextField
I'm trying to print user input from MDTextField to a label, but I keep getting "AttributeError: 'super' object has no attribute 'getattr'".
Here's my python file:
'''
class TodoLayout(MDScreen, MDFloatLayout):
pass
class CatLayout(Screen):
pass
class Windo... | Updating labels with user input from MDTextField | I'm trying to print user input from MDTextField to a label, but I keep getting "AttributeError: 'super' object has no attribute 'getattr'".
Here's my python file:
'''
class TodoLayout(MDScreen, MDFloatLayout):
pass
class CatLayout(Screen):
pass
class WindowManager(ScreenManager):
pass
class BullyCat(M... | [
"Ids in your kv should not be enclosed in quotes. Just change:\nid: 'label_id'\n\nto:\nid: label_id\n\n"
] | [
0
] | [] | [] | [
"kivy",
"kivy_language",
"kivymd",
"python"
] | stackoverflow_0074154612_kivy_kivy_language_kivymd_python.txt |
Q:
How to add users with username using mozilla-django-oidc to auth_user table upon SSO login?
I'm using mozilla-django-oidc for SSO login with one of my django application. When each user logs in to the application using SSO, then the user is added to the auth_user table of postgres database(if the user is not alrea... | How to add users with username using mozilla-django-oidc to auth_user table upon SSO login? | I'm using mozilla-django-oidc for SSO login with one of my django application. When each user logs in to the application using SSO, then the user is added to the auth_user table of postgres database(if the user is not already saved).
The username column of the auth_user table is filled with the hash value of the email ... | [
"That's what I did for connecting to Azure AADB2C, guess it's similar for keycloak, or other oidc providers..\n1.\nMake sure your oidc provider supports user_info endpoint (which stored in OIDC_OP_USER_ENDPOINT settings value), otherwise the library fails to start (in case of azure aadb2c it means moving from user ... | [
0
] | [] | [] | [
"django",
"django_authentication",
"python"
] | stackoverflow_0070332904_django_django_authentication_python.txt |
Q:
AWS Config stuck at "Currently in progress" when deploying with AWS CDK
I want to use AWS CDK to deploy AWS Config. The deploy gets stuck at:
Currently in progress: AWSConfig, MyCfnConfigurationRecorder, MyCfnDeliveryChannel
from aws_cdk import (
Stack,
aws_config as config,
aws_iam as role,
aws_s... | AWS Config stuck at "Currently in progress" when deploying with AWS CDK | I want to use AWS CDK to deploy AWS Config. The deploy gets stuck at:
Currently in progress: AWSConfig, MyCfnConfigurationRecorder, MyCfnDeliveryChannel
from aws_cdk import (
Stack,
aws_config as config,
aws_iam as role,
aws_s3 as s3,
RemovalPolicy
)
from constructs import Construct
import os,sys,... | [
"The deploy is failing because your role is missing some required IAM permissions.\nHere are the IAM policies the Configuration Recorder requires. The S3 policies are required. The SNS and KMS policies are required only if you are using SNS as a delivery method or SSE-KMS to encrypt the bucket.\nAdd them to your ro... | [
0
] | [] | [] | [
"amazon_web_services",
"aws_cdk",
"aws_config",
"python"
] | stackoverflow_0073161604_amazon_web_services_aws_cdk_aws_config_python.txt |
Q:
from itertools import product: the result is not a list?
I am wondering why list(prod) is an empty list? But a print it out the print(type(list(prod))) is an list and print(list(prod)) did show a list with 64 tuples.
from itertools import product
a = [1, 2]
b = [3,4]
c = [5,6]
prod = product(a, b, c,repeat=2) #
p... | from itertools import product: the result is not a list? | I am wondering why list(prod) is an empty list? But a print it out the print(type(list(prod))) is an list and print(list(prod)) did show a list with 64 tuples.
from itertools import product
a = [1, 2]
b = [3,4]
c = [5,6]
prod = product(a, b, c,repeat=2) #
print(list(prod))
print(type(list(prod)))
mylist = list(prod)
... | [
"The return value of product is a generator, and it gets exhausted once its been iterated upon. The first time this generator is iterated when you are calling print(list(prod)) and then when you again try to call print(type(list(prod))) there is no entity left in the iterator. A better approach would be:\nfrom iter... | [
1
] | [] | [] | [
"list",
"product",
"python",
"python_itertools",
"tuples"
] | stackoverflow_0074156794_list_product_python_python_itertools_tuples.txt |
Q:
What is wrong with the "while" condition here?
What is wrong with the while condition here
while (a = input(">").lower()) != "quit":
if a == "start":
print("Car started...Ready to go")
elif a == "stop":
print("Car stopped")
A:
You cannot assign a value this way in python. If you are using... | What is wrong with the "while" condition here? | What is wrong with the while condition here
while (a = input(">").lower()) != "quit":
if a == "start":
print("Car started...Ready to go")
elif a == "stop":
print("Car stopped")
| [
"You cannot assign a value this way in python. If you are using python 3.8 or higher, you can use the so-called walrus operator like so:\nwhile (a := input(\">\").lower()) != \"quit\":\n if a == \"start\":\n print(\"Car started...Ready to go\")\n elif a == \"stop\":\n print(\"Car stopped\")\n\nO... | [
5
] | [] | [] | [
"python",
"while_loop"
] | stackoverflow_0074156809_python_while_loop.txt |
Q:
Mocking step_function with moto throwing a state machine error
I'm trying to run a unit test which mocks the AWS stepfunction client.
The initial function runs the following code:
client.start_execution(
stateMachineArn=config.step_function_arn,
input=json.dumps(
dict(
d... | Mocking step_function with moto throwing a state machine error | I'm trying to run a unit test which mocks the AWS stepfunction client.
The initial function runs the following code:
client.start_execution(
stateMachineArn=config.step_function_arn,
input=json.dumps(
dict(
date=date, file=file
)
)
)
And the test look... | [
"Moto is not a typical mock-library, in the sense that you cannot just provide any input.\nThe idea behind Moto is that it should act more like an offline version of AWS (within reason of course).\nBecause of this, you would have to create the state machine first, as Moto mimicks AWS' behaviour by throwing an excep... | [
2
] | [] | [] | [
"amazon_web_services",
"aws_step_functions",
"moto",
"python"
] | stackoverflow_0074156300_amazon_web_services_aws_step_functions_moto_python.txt |
Q:
How to sum up values from a Pandas dataframe column
I would like to have the column 'IMPACT' to have their values summed up and by adding a line on the bottom called 'Total' with the integers values summed,excluding the NA and N/A.
This is my code:
import pandas as pd
import openpyxl
import numpy as np
pd.set_opt... | How to sum up values from a Pandas dataframe column | I would like to have the column 'IMPACT' to have their values summed up and by adding a line on the bottom called 'Total' with the integers values summed,excluding the NA and N/A.
This is my code:
import pandas as pd
import openpyxl
import numpy as np
pd.set_option('display.max_colwidth', None)
file = 'sheet.xlsx'
pla... | [
"You should first edit your current function to get either the int you want or np.nan.\ndef my_function(text):\n key_string = 'IMPACT:'\n if '[' and ']' in text: \n my_slice = text[text.find(key_string)+len(key_string):text.find(']')]\n else:\n my_slice = text[text.find(key_string)+len(key_... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074156739_dataframe_pandas_python.txt |
Q:
How do I create a copy of a table using PYODBC?
I'm using 32-bit Python along with 32-bit Microsoft Access.
I connect to the database and create a cursor.
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=P:\path\database.accdb;')
c = conn.cursor()
I then read in a table for future use... | How do I create a copy of a table using PYODBC? | I'm using 32-bit Python along with 32-bit Microsoft Access.
I connect to the database and create a cursor.
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=P:\path\database.accdb;')
c = conn.cursor()
I then read in a table for future use:
c.execute('select * from tbl')
tbl = c.fetchall()
... | [
"Due to a lack of documentation, the best way I found to figure this out is to use Microsoft Access to create a template for the query...example below worked.\nquery = 'SELECT tbl.* INTO tbl2 FROM tbl'\nc.execute(query)\n\n"
] | [
0
] | [] | [] | [
"ms_access",
"pyodbc",
"python",
"sql"
] | stackoverflow_0074140947_ms_access_pyodbc_python_sql.txt |
Q:
Django : Downloading PDF object generated by the library FPDF
I have a view that contains a wizard form. When the form is submitted, a httpresponse is sent with a PDF file. I generate the PDF file with the FPDF2 Library from the data got in the form submitted by the user.
To be sure that the PDF class using this l... | Django : Downloading PDF object generated by the library FPDF | I have a view that contains a wizard form. When the form is submitted, a httpresponse is sent with a PDF file. I generate the PDF file with the FPDF2 Library from the data got in the form submitted by the user.
To be sure that the PDF class using this library works, I tested it in a simple python script.
EDITED
My prob... | [
"According to the documentation of the last version of pyFPDF2 (version 2.5.7) : https://pyfpdf.github.io/fpdf2/fpdf/fpdf.html#fpdf.fpdf.FPDF.output\nThe dest is DEPRECATED and \"By default the bytearray buffer is returned. If a name is given, the PDF is written to a new file.\"\nSo it just needs :\nresponse = Http... | [
1
] | [] | [] | [
"django",
"fpdf",
"httpresponse",
"pyfpdf",
"python"
] | stackoverflow_0074156059_django_fpdf_httpresponse_pyfpdf_python.txt |
Q:
Python MaxHeap Bubble_Down method
I am trying to write a bubble_down method for a MaxHeap class and am having trouble with, what looks like, indexing problems. I think what is mainly confusing me, is that it seems like the indexing in this problem is having to start at 1, which doesn't make sense on how that works... | Python MaxHeap Bubble_Down method | I am trying to write a bubble_down method for a MaxHeap class and am having trouble with, what looks like, indexing problems. I think what is mainly confusing me, is that it seems like the indexing in this problem is having to start at 1, which doesn't make sense on how that works if python indexing starts with 0. This... | [
"The cause of the problem is in these lines:\nlchild_value = self.H[lchild_index] if lchild_index < len(self.H) else float('inf')\nrchild_value = self.H[rchild_index] if rchild_index < len(self.H) else float('inf')\n\nIf a node does not have both children, then this code will use Infinity as default value, but then... | [
1
] | [] | [] | [
"heap",
"max_heap",
"python"
] | stackoverflow_0074156423_heap_max_heap_python.txt |
Q:
Error with the function bpy.ops.mesh.primitive_vert_add() in blender
I come across the function bpy.ops.mesh.primitive_vert_add() in some GitHub scripts but when I type in this function in the console, the following error pops up:
Traceback (most recent call last): File "<blender_console>", line 1,
in <module>... | Error with the function bpy.ops.mesh.primitive_vert_add() in blender | I come across the function bpy.ops.mesh.primitive_vert_add() in some GitHub scripts but when I type in this function in the console, the following error pops up:
Traceback (most recent call last): File "<blender_console>", line 1,
in <module> File "C:\Program Files\Blender Foundation\Blender
2.83\2.83\scripts\mo... | [
"Just now I installed some in-package add-ons and the option \"add single vertex\" appeared.\nRegards\n",
"To use that function, you need the \"Add Mesh: Extra Objects\" add-on to be enabled.\n"
] | [
0,
0
] | [] | [] | [
"blender",
"python"
] | stackoverflow_0062990451_blender_python.txt |
Q:
Tweepy Look up ID with username
I am trying to get a list of IDs from a list of usernames I have. Is there any method that tweepy provides that lets me do lookup user IDs using their username?
A:
Twitter API has the resource https://dev.twitter.com/rest/reference/get/users/lookup for such requirements. It can re... | Tweepy Look up ID with username | I am trying to get a list of IDs from a list of usernames I have. Is there any method that tweepy provides that lets me do lookup user IDs using their username?
| [
"Twitter API has the resource https://dev.twitter.com/rest/reference/get/users/lookup for such requirements. It can return user objects for at most 100 users at a time.\nYou can use this in Tweepy like:\nuser_objects = api.lookup_users(screen_names=list_of_at_most_100_screen_names)\nuser_ids = [user.id_str for user... | [
6,
1,
0
] | [] | [] | [
"python",
"tweepy",
"twitter"
] | stackoverflow_0042943934_python_tweepy_twitter.txt |
Q:
AWS instance/controller node randomly unable to find files on FSX that is there
This is a sporadic issue that I could not figure out a condition to replicate.
The gist of the issue is that instance/controller node will randomly fail to find files that are already created on Amazon FSx. A sample script can be as si... | AWS instance/controller node randomly unable to find files on FSX that is there | This is a sporadic issue that I could not figure out a condition to replicate.
The gist of the issue is that instance/controller node will randomly fail to find files that are already created on Amazon FSx. A sample script can be as simple as this:
import dask
fn = '/mnt/fsx/home/user/something.txt'
def run():
with... | [
"Unfortunately, the question was misdiagnosed as this was not an FSX issue.\nSomewhere in the paths there were symlinks which were based on a different shared drive. That was the shared drive that failed us. FSX was resilient throughout.\n"
] | [
0
] | [] | [] | [
"amazon_ec2",
"amazon_fsx",
"amazon_web_services",
"dask",
"python"
] | stackoverflow_0073070329_amazon_ec2_amazon_fsx_amazon_web_services_dask_python.txt |
Q:
Using Regex to NOT match a given pattern
I'm writing a script part of which is isolating part numbers from emails. I have this Regex which is helping isolate the part numbers:
\b(\S[A-Z0-9/-]{3,30})\b
It works perfectly, except it also gives back phone numbers. Many part numbers might look familiar to a phone num... | Using Regex to NOT match a given pattern | I'm writing a script part of which is isolating part numbers from emails. I have this Regex which is helping isolate the part numbers:
\b(\S[A-Z0-9/-]{3,30})\b
It works perfectly, except it also gives back phone numbers. Many part numbers might look familiar to a phone number, so changing that Regex is not likely. Wha... | [
"I think this will work but I haven't tested it thoroughly:\n(?<![\\w/-])(?!\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d(?![\\w/-]))(\\S[A-Z0-9/-]{3,30})(?![\\w/-])\n\nA lot of the noise in that regex is replacing \\b with the more precise (?![\\w/-]) (i.e., not followed by a word character, / or -), or the negative lookbehind... | [
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074156495_python_regex.txt |
Q:
Plot a 2D grid data from dict in python
I want to plot a 2D grid (24x4) where each grid coordinates have a value, the data is in a dict as such:
{map1_ID:[
['x_coor','y_coor','data_to plot'],
['x_coor','y_coor','data_to plot'],
...
],
map2_ID:[
['x_coo... | Plot a 2D grid data from dict in python | I want to plot a 2D grid (24x4) where each grid coordinates have a value, the data is in a dict as such:
{map1_ID:[
['x_coor','y_coor','data_to plot'],
['x_coor','y_coor','data_to plot'],
...
],
map2_ID:[
['x_coor','y_coor','data_to plot'],
['... | [
"Plotly is my go-to for any kind of figure. This is a rough version of what you're looking for.\nimport plotly.graph_objects as go\n\nmaps = {'map1_ID': [[0, 0, 1], [0, 1, 1], [0, 2, 10], [0, 3, 1], [1, 0, 1], [1, 1, 1], [1, 2, 14], [1, 3, 1], [2, 0, 1], [2, 1, 1], [2, 2, 10], [2, 3, 1], [3, 0, 1], [3, 1, 1], [3, 2... | [
0
] | [] | [] | [
"matplotlib",
"python",
"visualization"
] | stackoverflow_0074155894_matplotlib_python_visualization.txt |
Q:
Python : print 1-1000000 with recursion
This code results in RecursionError: maximum recursion depth exceeded while calling a Python object .
I know it is very easy to use loop but is there any way to implement it using recursion without increasing recursion limit?
Tail call optimization is one method? Are there a... | Python : print 1-1000000 with recursion | This code results in RecursionError: maximum recursion depth exceeded while calling a Python object .
I know it is very easy to use loop but is there any way to implement it using recursion without increasing recursion limit?
Tail call optimization is one method? Are there any other methods?
def print_recursion(m,n):
... | [
"You can use a divide and conquer strategy. Treat the problem like in-order traversal of a binary tree where conceptually each node contains a range. The root contains the full range, and each descendent node contains half the range of its parent. You print the current value when the lower_limit of the range equals... | [
1
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074141156_python_recursion.txt |
Q:
Flask: What is the use of __init__.py vs run.py? And are blueprints standard things to use in most Flask web applications?
I recently started getting into Flask web dev and I've probably gone through 5 different courses/tutorials now, and they all seem to have different ways/conventions of doing things. I was hopi... | Flask: What is the use of __init__.py vs run.py? And are blueprints standard things to use in most Flask web applications? | I recently started getting into Flask web dev and I've probably gone through 5 different courses/tutorials now, and they all seem to have different ways/conventions of doing things. I was hoping I could receive some clarity here!
Is __init__.py mandatory? I see some tutorials use them and some don't. From my understan... | [
"I can answer a few questions from your list that I understood.\nQuestion1\ninit.py is not a mandatory file. Files named __init__.py are used to mark directories on disk as Python package directories. So it really depends on your structure of projects. Ideally if you have a project with multiple folders, you might ... | [
8,
1,
1,
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0067528668_flask_python.txt |
Q:
ModuleNotFoundError: No module named 'requests' even though I have the module installed
Sorry for the badly worded title.
I installed the python module requests by using the command pip install requests now it worked but I opened vs code after a few days and got this error
ModuleNotFoundError: No module named 're... | ModuleNotFoundError: No module named 'requests' even though I have the module installed | Sorry for the badly worded title.
I installed the python module requests by using the command pip install requests now it worked but I opened vs code after a few days and got this error
ModuleNotFoundError: No module named 'requests'
so I used pip uninstall requests and then pip install requests it still gave me the ... | [
"you need to check the python interpreter used by vscode and ensure it's using the interpreter you installed and used by pip\nUsing the default interpreter from vscode, the request modules was flagged as not available and it will return an error\nenter image description here\nenter image description here\nLook that... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0072502493_python.txt |
Q:
Celery Beat: Synchronizing schedule is the last debug message I see
I am running superset and celery on AWS ECS. Celery worker, Celery beat and Superset are running in separate containers of the same task. I have turned on debug logs in celery so that I can see each step celery is taking. Celery is starting up and... | Celery Beat: Synchronizing schedule is the last debug message I see | I am running superset and celery on AWS ECS. Celery worker, Celery beat and Superset are running in separate containers of the same task. I have turned on debug logs in celery so that I can see each step celery is taking. Celery is starting up and running. Celery worker goes until the log message DEBUG/MainProcess] | C... | [
"So it turns out I was using MemoryDb instead of Elasticache, and the two things are not interchangeable.\n"
] | [
1
] | [] | [] | [
"apache_superset",
"celery",
"celerybeat",
"python"
] | stackoverflow_0074116701_apache_superset_celery_celerybeat_python.txt |
Q:
What does "exception raising placeholder" mean in the Descriptor HowTo Guide?
In the Python's Descriptor HowTo Guide there's this paragraph (bold added):
Descriptor HowTo Guide
Descriptor protocol
(...)
To make a read-only data descriptor, define both __get__() and __set__() with the __set__() raising an Attribut... | What does "exception raising placeholder" mean in the Descriptor HowTo Guide? | In the Python's Descriptor HowTo Guide there's this paragraph (bold added):
Descriptor HowTo Guide
Descriptor protocol
(...)
To make a read-only data descriptor, define both __get__() and __set__() with the __set__() raising an AttributeError when called. Defining the __set__() method with an exception raising placeho... | [
"It means that, if you want a data-descriptor, all you need is that it has a __set__ method - and even if that __set__ method will always raise an exception when called, it will still be a data-descriptor.\nThis \"method that always raise an exception\" is what is meant by \"exception raising placeholder\" in the d... | [
2
] | [] | [] | [
"exception",
"python",
"python_descriptors"
] | stackoverflow_0072814027_exception_python_python_descriptors.txt |
Q:
OpenCv error can't open camera through video capture
I was using my cam through opencv and suddenly after restarting I ran my code it shows below error:
[ WARN:0] global /io/opencv/modules/videoio/src/cap_v4l.cpp (802) open VIDEOIO ERROR: V4L: can't open camera by index 0
Traceback (most recent call last):
File ... | OpenCv error can't open camera through video capture | I was using my cam through opencv and suddenly after restarting I ran my code it shows below error:
[ WARN:0] global /io/opencv/modules/videoio/src/cap_v4l.cpp (802) open VIDEOIO ERROR: V4L: can't open camera by index 0
Traceback (most recent call last):
File "test.py", line 20, in <module>
retval, buffer_img = c... | [
"I got the same error. Try changing 0 to -1\ncap = cv2.VideoCapture(-1)\n\nThis solved the issue.\n",
"I got the same problem when I created more than one instance of the cv2.VideoCapture(0). So check if your code contains multiple initializations or sections which call cv2.VideoCapture(0) more than once. I was f... | [
20,
14,
9,
4,
3,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [
"This issue is due to the interruption. Try to end the execution with the key 'q' for example, don't close the window suddenly.\nI solved the same issue by opening terminal again and execute the same script again.\n"
] | [
-1
] | [
"opencv",
"python",
"python_3.x",
"ubuntu",
"video_capture"
] | stackoverflow_0059371075_opencv_python_python_3.x_ubuntu_video_capture.txt |
Q:
I was trying to understand the concept of generators in python I am trying to implement it in different ways but i am getting stuck at one point
For starters I wrote a code for generator to initially grasp the context
def cycleoflife():
# use yield to create a generator
for i in range(0, 1000):
yie... | I was trying to understand the concept of generators in python I am trying to implement it in different ways but i am getting stuck at one point | For starters I wrote a code for generator to initially grasp the context
def cycleoflife():
# use yield to create a generator
for i in range(0, 1000):
yield "eat"
yield "sleep"
yield "code"
which printed
eat
sleep
code
on every next call
But I want to try something different so wanted ... | [
"Here's how you could implement this, although this is not really a good use case for a generator. Note that itertools.cycle does exactly what your Mary function was doing.\nfrom itertools import cycle\ndef Mary():\n parts = [\"I love Mary\", \"Mary love that\", \"I love that\"]\n hold = []\n for n in cyc... | [
3
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0074156835_generator_python.txt |
Q:
how to set new value to one cell in df without error?
i want to change 10 to 5 in index 0 and column name 'x'.
my code is:
mydata = {'x' : [10, 50, 18, 32, 47, 20], 'y' : ['12', '11', 'N/A', '13', '15', 'N/A']}
df1 = pd.DataFrame(mydata)
df1['x'][df1['x'] == 10] = 5
and i got:
C:\Users\T\AppData\Local\Temp\ipyker... | how to set new value to one cell in df without error? | i want to change 10 to 5 in index 0 and column name 'x'.
my code is:
mydata = {'x' : [10, 50, 18, 32, 47, 20], 'y' : ['12', '11', 'N/A', '13', '15', 'N/A']}
df1 = pd.DataFrame(mydata)
df1['x'][df1['x'] == 10] = 5
and i got:
C:\Users\T\AppData\Local\Temp\ipykernel_2260\1154778325.py:1: SettingWithCopyWarning:
A value ... | [
"This is where you need to use the loc function:\ndf1.loc[df1['x'] == 10, 'x'] = 5\n\nHere's why this is an issue. Think about how Python implements your statement:\n(df1['x'])[df1['x'] == 10] = 5\n\nThat first expression extracts a column from your dataframe and returns it as a separate Series object, which is ca... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074157052_pandas_python.txt |
Q:
How can I normalize a nested JSON object from a pandas column and append to existing data frame or as its own data frame?
I have been struggling to sort some data I am getting from an API. I am still fairly new to python and attempting to do this in pandas.
(The data I am getting is from here: https://www.jao.eu/p... | How can I normalize a nested JSON object from a pandas column and append to existing data frame or as its own data frame? | I have been struggling to sort some data I am getting from an API. I am still fairly new to python and attempting to do this in pandas.
(The data I am getting is from here: https://www.jao.eu/page-api/market-data).
I have tried to normalize the data for the results column, which seems to be a nested dictionary and the ... | [
"use:\ndf=df.explode('results')\ndf=df.join(pd.json_normalize(df.pop('results')).add_suffix('_new'))\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"json",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074156974_dataframe_json_jupyter_notebook_pandas_python.txt |
Q:
How do I show the Prices on January 1 of 2017, 18, 19, 20, 21, and 22 in my dataframe? Python
I can't figure out how to get the first days of every year so that I can show the change.
A:
I suspect your column that holds the dates is unnamed.
That column is called index by default even though you don't see that. ... | How do I show the Prices on January 1 of 2017, 18, 19, 20, 21, and 22 in my dataframe? Python |
I can't figure out how to get the first days of every year so that I can show the change.
| [
"I suspect your column that holds the dates is unnamed.\nThat column is called index by default even though you don't see that. So in order to iterate that column you will have to do something like this:\ndate = data.index\n\nTo get first date of every year:\nfirst_dates = data.groupby(pd.DatetimeIndex(data.index).... | [
1,
0
] | [] | [] | [
"pandas",
"python",
"streamlit"
] | stackoverflow_0074154932_pandas_python_streamlit.txt |
Q:
How to move member to channel | discord.py
How to move member to a different channel without member: discord.Member, channel : discord.VoiceChannel arguments in a function if i have variables with channel id and member id in this function?
@commands.command()
async def msg(ctx):
member = 848494088563327006
... | How to move member to channel | discord.py | How to move member to a different channel without member: discord.Member, channel : discord.VoiceChannel arguments in a function if i have variables with channel id and member id in this function?
@commands.command()
async def msg(ctx):
member = 848494088563327006
channel = 430388650786947083
await member.m... | [
"I think you could use get_member, to get a member object by ID docs for get_member and get_channel to get the channel object by ID docs for get_channel. Then do the move_to command\nI am not an expert with this but this would be an idea.\n"
] | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074157022_discord.py_python.txt |
Q:
psycopg2: update multiple rows with one query
I tried to update multiple rows (approx. 350000) with a single query by implementing the following function:
def update_items(rows_to_update):
sql_query = """UPDATE contact as t SET
name = e.name
FROM (VALUES %s) AS e(id, nam... | psycopg2: update multiple rows with one query | I tried to update multiple rows (approx. 350000) with a single query by implementing the following function:
def update_items(rows_to_update):
sql_query = """UPDATE contact as t SET
name = e.name
FROM (VALUES %s) AS e(id, name)
WHERE e.id = t.id;"""
c... | [
"By splitting the list into chunks of size equal to page_size, it worked well:\ndef update_items(rows_to_update):\n sql_query = \"\"\"UPDATE contact as t SET\n name = data.name\n FROM (VALUES %s) AS data (id, name)\n WHERE t.id = data.id\"\"\"\n conn = ... | [
1,
0
] | [] | [] | [
"postgresql",
"psycopg2",
"python",
"sql_update"
] | stackoverflow_0067737098_postgresql_psycopg2_python_sql_update.txt |
Q:
Overlaping dates in pandas dataframe
ID START DATE END DATE
5194 2019-05-15 2019-05-31
5193 2017-02-08 2017-04-02
5193 2017-02-15 2017-04-10
5193 2021-04-01 2021-05-15
5191 2020-10-01 2020-11-20
5191 2019-02-28 2019-04-20
5188 2018-10-01 2018-11-30
i have a dataframe(this is just a p... | Overlaping dates in pandas dataframe | ID START DATE END DATE
5194 2019-05-15 2019-05-31
5193 2017-02-08 2017-04-02
5193 2017-02-15 2017-04-10
5193 2021-04-01 2021-05-15
5191 2020-10-01 2020-11-20
5191 2019-02-28 2019-04-20
5188 2018-10-01 2018-11-30
i have a dataframe(this is just a part of it) , When the id value of the prev... | [
"Try with groupby and agg\nimport pandas as pd\na = \"\"\"5194 2019-05-15 2019-05-31\n5193 2017-02-08 2017-04-02\n5193 2017-02-15 2017-04-10\n5193 2021-04-01 2021-05-15\n5191 2020-10-01 2020-11-20\n5191 2019-02-28 2019-04-20\n5188 2018-10-01 2018-11-30\n\"\"\"\ndf = pd.DataFrame([i.split... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"timestamp"
] | stackoverflow_0074157100_dataframe_pandas_python_timestamp.txt |
Q:
How do I add custom user model fields to the Wagtail user settings page?
I am building a wagtail site. I've followed the instructions found in the docs and my additional fields show up in the edit and create user forms, found at [site url]/admin/users/[user id]. However, I want them to also show up in the account ... | How do I add custom user model fields to the Wagtail user settings page? | I am building a wagtail site. I've followed the instructions found in the docs and my additional fields show up in the edit and create user forms, found at [site url]/admin/users/[user id]. However, I want them to also show up in the account settings page accessed from the bottom left. This page seems to describe what ... | [
"\"expected str instance, ellipsis found\" sounds like you literally have fields = [...] in your code. The example in the docs expects you to put actual field names in that list. So perhaps fields = ['bio', 'nickname']?\n",
"As noted by @cnk, the fields array should contain ['bio', 'nickname']. However, the main ... | [
0,
0
] | [] | [] | [
"django",
"python",
"wagtail"
] | stackoverflow_0074132248_django_python_wagtail.txt |
Q:
How to replace all "False" values in any columns by values from other columns with the same names if that values are not False
for example:
import pandas as pd
dc1 = {
'n':[1, 2, 3, 4],
'a':[0, 2, 0.0, 4],
'b':[0,'', False, 5],
}
dc2 = {
'n':[1, 2, 3, 4],
'a':[1, 0, 3, 0.0],
'b':[6, 5... | How to replace all "False" values in any columns by values from other columns with the same names if that values are not False | for example:
import pandas as pd
dc1 = {
'n':[1, 2, 3, 4],
'a':[0, 2, 0.0, 4],
'b':[0,'', False, 5],
}
dc2 = {
'n':[1, 2, 3, 4],
'a':[1, 0, 3, 0.0],
'b':[6, 5, 8, 9],
}
Merge on 'n' column. Is it possible values in 'a'(and 'b') column in df1 is replaced by values of 'a' (and 'b') col... | [
"You can use isin to get the indexes where a cell in a or b contains an element from a manual list: [False, 0, 0.0, 'Nan', None, '','Null'] and use np.where to replace those elements:\nreplace_list = [False, 0, 0.0, 'Nan', None, '','Null']\ndf1[['a', 'b']] = ( np.where(df1[['a', 'b']].isin(replace_list), df2[['a', ... | [
1
] | [] | [] | [
"dataframe",
"drop",
"merge",
"pandas",
"python"
] | stackoverflow_0074156843_dataframe_drop_merge_pandas_python.txt |
Q:
How to virtually click mouse with Python instead of actually moving mouse cursor
I tried many answers on stackoverflow and other websites but all of them actually move my mouse cursor.
I'm looking for a way to click in a position (x, y) without actually moving my mouse cursor.
Also I want to run it in a Windows RD... | How to virtually click mouse with Python instead of actually moving mouse cursor | I tried many answers on stackoverflow and other websites but all of them actually move my mouse cursor.
I'm looking for a way to click in a position (x, y) without actually moving my mouse cursor.
Also I want to run it in a Windows RDP, so that when I exit the RDP, it still runs and clicks on it.
I tried python modules... | [
"This doesn't virtually move cursor but logically move the cursor and click then again reset the cursor's position to its original position.\nimport pyautogui as ag\n\ndef clickAndResetCursor(x,y):\n i,j = ag.position()\n ag.moveTo(x,y)\n ag.click()\n ag.moveTo(i,j)\n\n",
"This is simple impossible, y... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074155676_python.txt |
Q:
ranking items in a list by user score
What is the Best Thing - Tom Scott
basically trying to imitate this code in python to make code that ranks items based on the users input.
output 2 items from a list, ask user for which is better, add +1 score to that item, add -1 score to the other item, move on to next compa... | ranking items in a list by user score | What is the Best Thing - Tom Scott
basically trying to imitate this code in python to make code that ranks items based on the users input.
output 2 items from a list, ask user for which is better, add +1 score to that item, add -1 score to the other item, move on to next comparison.
new to coding, so i can understand b... | [
"Given a file where each line in the file is some str item label like:\nPlate\nFork\nSpoon\n\nand you want to write a program that will read all of the items from the file and then continuously ask a user one or the other while keeping tally of those results in the form of a single score value per item which goes +... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074157166_python.txt |
Q:
Print datetime in ISO format without milliseconds
I'm trying to serialize datetime in an API, but I don't want milliseconds. What I want is here: https://en.wikipedia.org/wiki/ISO_8601 - "2015-09-14T17:51:31+00:00"
tz = pytz.timezone('Asia/Taipei')
dt = datetime.datetime.now()
loc_dt = tz.localize(dt)
Try A:
loc_... | Print datetime in ISO format without milliseconds | I'm trying to serialize datetime in an API, but I don't want milliseconds. What I want is here: https://en.wikipedia.org/wiki/ISO_8601 - "2015-09-14T17:51:31+00:00"
tz = pytz.timezone('Asia/Taipei')
dt = datetime.datetime.now()
loc_dt = tz.localize(dt)
Try A:
loc_dt.isoformat()
>> '2015-09-17T10:46:15.767000+08:00'
T... | [
"You can replace the microseconds with 0 and use isoformat:\nimport pytz\nfrom datetime import datetime\ntz = pytz.timezone('Asia/Taipei')\ndt = datetime.now()\nloc_dt = tz.localize(dt).replace(microsecond=0)\nprint loc_dt.isoformat()\n2015-09-17T19:12:33+08:00\n\nIf you want to keep loc_dt as is do the replacing w... | [
17,
1
] | [] | [] | [
"datetime",
"iso",
"python",
"timezone"
] | stackoverflow_0032637076_datetime_iso_python_timezone.txt |
Q:
Python Regex to extract meeting invite from Gmail Subject
I'm trying to extract the meeting date / time from meeting invites within Gmail's subject. Below is an example of a subject for a meeting invite:
Invitation: Bob / Carol Meeting @ Tue Oct 25, 2022 11:30am - 12pm (CST) (bob@example.org)
What I would like to... | Python Regex to extract meeting invite from Gmail Subject | I'm trying to extract the meeting date / time from meeting invites within Gmail's subject. Below is an example of a subject for a meeting invite:
Invitation: Bob / Carol Meeting @ Tue Oct 25, 2022 11:30am - 12pm (CST) (bob@example.org)
What I would like to extract:
Tue Oct 25, 2022 11:30am - 12pm (CST)
I think the pa... | [
"Try this - it should match everything after the \"@ \" and up to the end of the timezone \")\"\nimport re\n\nstring = (\n 'Invitation: Bob / Carol Meeting @ Tue Oct 25, 2022 11:30am - 12pm (CST) (bob@example.org)'\n)\npattern = re.compile(r'(?<=@ )[^)]+\\)')\nmatches = re.findall(pattern, string)\nprint(matches... | [
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074157121_python_regex.txt |
Q:
Why does my loop return a string if it is accepted in the "if" but returns a "None" once it passed through the "else"
Apologies for the vague title. I wasn't sure how to make it specific enough.
I have some code that asks for a word and then turns it into a list of characters. I wanted to pass it through a loop to... | Why does my loop return a string if it is accepted in the "if" but returns a "None" once it passed through the "else" | Apologies for the vague title. I wasn't sure how to make it specific enough.
I have some code that asks for a word and then turns it into a list of characters. I wanted to pass it through a loop to check in its isalpha().
When I run it. If my word is alpha it works fine. If my word has digits, it will restart the loop ... | [
"This is because an implicit return None is observed in cases where a function does not return a value.\nThe above code is the same as below:\ndef start():\n word = input(\"Enter word to turn into a list\")\n if word.isalpha():\n word = word.lower()\n return word\n # all paths above return a ... | [
0
] | [] | [] | [
"isalpha",
"list",
"loops",
"nonetype",
"python"
] | stackoverflow_0074157429_isalpha_list_loops_nonetype_python.txt |
Q:
Is it possible to create a sidebar that can be hidden in dash?
I want to add to my dashboard a sidebar that allows hiding pulsing a button, is that possible?
Thanks.
A:
Dash Bootstrap Components will give you this capability.
If you just want to add a side bar which is always visible, you can achieve this using ... | Is it possible to create a sidebar that can be hidden in dash? | I want to add to my dashboard a sidebar that allows hiding pulsing a button, is that possible?
Thanks.
| [
"Dash Bootstrap Components will give you this capability.\nIf you just want to add a side bar which is always visible, you can achieve this using Bootstrap layout components.\nHowever, it sounds like you want to be able to hide the sidebar, in which case you should investigate the Offcanvas component\n"
] | [
1
] | [] | [] | [
"data_science",
"plotly_dash",
"python"
] | stackoverflow_0074150666_data_science_plotly_dash_python.txt |
Q:
Returning key-value pairs in a list of dictionaries
I am currently working with a list of dictionaries that is stored in rest_list variable after calling the get_rest(rest) function. I would like to return a list of dictionaries where availability == available (all of them in this case). This is the list of dictio... | Returning key-value pairs in a list of dictionaries | I am currently working with a list of dictionaries that is stored in rest_list variable after calling the get_rest(rest) function. I would like to return a list of dictionaries where availability == available (all of them in this case). This is the list of dictionaries in the rest_list variable.
[{'close_time': '5:00 p... | [
"l = [{'close_time': '5:00 pm',\n 'open_time': '8:00 am',\n 'name': 'Pizza DeVille',\n 'city': 'Las Vegas',\n 'availability': 'available'},\n {'close_time': '10:00 pm',\n 'open_time': '9:00 am',\n 'name': 'Cecil’s',\n 'city': 'Philadelphia',\n 'availability': 'available'}... | [
2,
2
] | [] | [] | [
"dictionary",
"if_statement",
"list",
"python"
] | stackoverflow_0074157216_dictionary_if_statement_list_python.txt |
Q:
Filter pandas dataframe by list
I have a dataframe that has a row called "Hybridization REF". I would like to filter so that I only get the data for the items that have the same label as one of the items in my list.
Basically, I'd like to do the following:
dataframe[dataframe["Hybridization REF"].apply(lambda: x i... | Filter pandas dataframe by list | I have a dataframe that has a row called "Hybridization REF". I would like to filter so that I only get the data for the items that have the same label as one of the items in my list.
Basically, I'd like to do the following:
dataframe[dataframe["Hybridization REF"].apply(lambda: x in list)]
but that syntax is not cor... | [
"Suppose \ndf is your dataframe,\nlst is our list of labels.\ndf.loc[ df.index.isin(lst), : ]\n\nWill display all rows whose index matches any value of the list item. I hope this helps solve your query.\n",
"Is there a numpy dataframe? I am guessing it is pandas dataframe, if so here is the solution.\ndf[df['Hybr... | [
18,
10,
4,
0,
0,
0,
0
] | [] | [] | [
"data_science",
"numpy",
"pandas",
"python"
] | stackoverflow_0045040312_data_science_numpy_pandas_python.txt |
Q:
Specifying the display of a django DateField from the model, and not form/input/settings?
I have a Django model with a DateField, like so:
production_date = models.DateField(null=True, blank=True)
I am trying to have that field display as the default Python date format in templates, which looks like "2000-01-01".... | Specifying the display of a django DateField from the model, and not form/input/settings? | I have a Django model with a DateField, like so:
production_date = models.DateField(null=True, blank=True)
I am trying to have that field display as the default Python date format in templates, which looks like "2000-01-01". But in a Django template it displays as "Jan. 1, 2000."
In a Python shell, the date displays ... | [
"I'd make a model method get_production_date.. So I'm not doing a crap ton of template tags, not a fan of them.. and then CTRL+Shift+F (only HTML files) find production_date and change them to get_production_date\nmodels.py\nclass MyModel(models.Model):\n production_date = models.DateField('Creation Time')\n ... | [
2
] | [
"You can apply date filter in template\nExample:\n{{ birthday|date:\"m, d, Y\" }}\n\nDjango date format reference\n"
] | [
-1
] | [
"datefield",
"django",
"model",
"python",
"templates"
] | stackoverflow_0074157344_datefield_django_model_python_templates.txt |
Q:
Django select_for_update cannot be used outside of a transaction
I was using Django 1.5.1 and upgraded to Django 1.6.6.
In Django 1.5.1, I was using select for update to guarantee atomic execution.
# "views.py"
from django.db import transaction
def some_method():
job_qs = Job.objects.select_for_update().... | Django select_for_update cannot be used outside of a transaction | I was using Django 1.5.1 and upgraded to Django 1.6.6.
In Django 1.5.1, I was using select for update to guarantee atomic execution.
# "views.py"
from django.db import transaction
def some_method():
job_qs = Job.objects.select_for_update().filter(pk=job.id)
for job in job_qs:
Unfortunately this now throw... | [
"The answer is in the error, wrap the query in a transaction\nDjango's documentation is located here: https://docs.djangoproject.com/en/dev/topics/db/transactions/#django.db.transaction.atomic\nOne approach is:\n# \"views.py\"\n\nfrom django.db import transaction\n\ndef some_method(): \n with transaction.atom... | [
32,
11,
0
] | [
"For me it happened even when using with transaction.atomic():. The problem was that we didn't set 'ATOMIC_REQUESTS': True in the settings.py file. Now this solved the problem.\nAs documented here: https://docs.djangoproject.com/en/3.1/topics/db/transactions/\n\"Set ATOMIC_REQUESTS to True in the configuration of e... | [
-1
] | [
"django",
"python",
"python_3.x",
"select_for_update",
"transactions"
] | stackoverflow_0025451087_django_python_python_3.x_select_for_update_transactions.txt |
Q:
Python bit for bitcoin transactions send() method doesn't work
I am trying to create and broadcast a transaction with help of bit library in python, here is the code -
from bit import PrivateKeyTestnet
main_key = PrivateKeyTestnet('MyWalletWIF')
tx_hash = main_key.send([("RecievingAddress", 67000, 'satoshi')], fe... | Python bit for bitcoin transactions send() method doesn't work | I am trying to create and broadcast a transaction with help of bit library in python, here is the code -
from bit import PrivateKeyTestnet
main_key = PrivateKeyTestnet('MyWalletWIF')
tx_hash = main_key.send([("RecievingAddress", 67000, 'satoshi')], fee=200, absolute_fee=True, leftover="MyWalletAddress")
My wallet has... | [
"Still don't understand what was the issue but I solved it by removing fee related part of the code, and it worked\ntx_hash = main_key.send([(\"RecievingAddress\", 67000, 'satoshi')], leftover=\"MyWalletAddress\")\n\n"
] | [
0
] | [] | [] | [
"bitcoin_testnet",
"python"
] | stackoverflow_0074153386_bitcoin_testnet_python.txt |
Q:
(-215:Assertion failed) total >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::convexHull'
co_ords = np.column_stack(np.where(img > 0))
angle = cv2.minAreaRect(co_ords)[-1]
if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
co_ords = np.column_stack(np.where(img > ... | (-215:Assertion failed) total >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::convexHull' | co_ords = np.column_stack(np.where(img > 0))
angle = cv2.minAreaRect(co_ords)[-1]
if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
co_ords = np.column_stack(np.where(img > 0))
returns
[[ 0 0 0]
[ 0 0 1]
[ 0 0 2]
...
[7014 4960 0]
[7014 4960 1]
... | [
"minAreaRect needs 2D coordinates, that is array of [x,y] coordinates in the form array([[x,y], [x,y], [x,y]...])\nYou fed it with an array 3D coordinates, namely of y, x and component (0 for blue, 1 for green, 2 for red) coordinates.\nimg is a BGR image. So a 3D array, each img[y,x,c] being a 0..255 int.\nSo img[1... | [
1
] | [] | [] | [
"numpy",
"opencv",
"python"
] | stackoverflow_0074157201_numpy_opencv_python.txt |
Q:
Minimum amount for action='append'?
I have an argparse argument that appends, and I want it to be called at least twice. (args.option would contain at least two lists) I know that one way would be to check it myself, but I would prefer a way to make argparse do it.
import argparse
parser = argparse.ArgumentParser... | Minimum amount for action='append'? | I have an argparse argument that appends, and I want it to be called at least twice. (args.option would contain at least two lists) I know that one way would be to check it myself, but I would prefer a way to make argparse do it.
import argparse
parser = argparse.ArgumentParser(description='Do the thing')
parser.add_a... | [
"With that argument, each time you use a '-o' flag, it looks for 3 strings, and it puts them in a list in the output:\nIn [127]: import argparse\n ...: \n ...: parser = argparse.ArgumentParser(description='Do the thing')\n ...: parser.add_argument('-o', '--option', nargs=3, action='append', metavar=('A'... | [
1
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0074157488_argparse_python.txt |
Q:
Python PULP optimization - Limiting total number of one variable chosen
This is a follow-up to this question: Python PULP optimization - LpVariable across THREE factors?
I've altered the code setup (for clarity) as follows. The goal is to maximize the number of points scored across 3 games. Each of the listed play... | Python PULP optimization - Limiting total number of one variable chosen | This is a follow-up to this question: Python PULP optimization - LpVariable across THREE factors?
I've altered the code setup (for clarity) as follows. The goal is to maximize the number of points scored across 3 games. Each of the listed players has a different points projection for each of the 3 games, at each of 3 d... | [
"You'll need another variable to enforce the consistency across the games. As is now, if you sum up across the positions or teams or both, you could get differing players.\nAnyhow, you can introduce another variable that just captures the players selected on the team and link that to the other...\nThe \"effectiven... | [
1
] | [] | [] | [
"optimization",
"pulp",
"python"
] | stackoverflow_0074156804_optimization_pulp_python.txt |
Q:
Api request to the BitBucket is failing
I wanted to get a list of repositories in a workspace of BitBucket and found out such a command.
curl --request GET --url 'https://api.bitbucket.org/2.0/repositories/{workspace}' --header 'Authorization: Bearer {token}' --header 'Accept: application/json'
I use a fre... | Api request to the BitBucket is failing | I wanted to get a list of repositories in a workspace of BitBucket and found out such a command.
curl --request GET --url 'https://api.bitbucket.org/2.0/repositories/{workspace}' --header 'Authorization: Bearer {token}' --header 'Accept: application/json'
I use a free plan of BitBucket and use for "Authorizatio... | [
"Make sure your auth header is properly constructed. From bitbucket docs:\n\nSupplying Basic Auth headers\n\nBuild a string of the form username:password BASE64 encode the string\nSupply an \"Authorization\" header with content \"Basic \" followed by the\nencoded string, e.g. Basic YWRtaW46YWRtaW4=\n\n\ncurl also c... | [
0
] | [] | [] | [
"api",
"bitbucket",
"python"
] | stackoverflow_0074157523_api_bitbucket_python.txt |
Q:
using pyinstaller keep the fonts on all systems
I made a GUI using tkinter.
I created onefile exe with pyinstaller, but seted font (font = freesans.ttf) is not applied to other computers.
I think I need to adddata a font, but I don't understand the answers of pygame or pyqt in cases similar to mine.
A:
Here's a... | using pyinstaller keep the fonts on all systems | I made a GUI using tkinter.
I created onefile exe with pyinstaller, but seted font (font = freesans.ttf) is not applied to other computers.
I think I need to adddata a font, but I don't understand the answers of pygame or pyqt in cases similar to mine.
| [
"Here's a solution for adding custom fonts to pyinstaller executables on Windows. You'll need to add your font path to the pyinstaller build with --add-data so it can be picked up in the MEI folder used by the executable.\nimport ctypes\nimport sys\nfrom pathlib import Path\n\n\ndef fetch_resource(rsrc_path):\n ... | [
1
] | [] | [] | [
"pyinstaller",
"python",
"tkinter"
] | stackoverflow_0074157535_pyinstaller_python_tkinter.txt |
Q:
Pandas table to Pyarrow conversion not working for string to int
I have a xlsx file with 15000 records. I'm trying to serialize the data for a API services. Read the file and send it in HTTP response.
Input data look as below
account_name | dr_code | cr_code |amount | rate | category
A | 12582 | 1258... | Pandas table to Pyarrow conversion not working for string to int | I have a xlsx file with 15000 records. I'm trying to serialize the data for a API services. Read the file and send it in HTTP response.
Input data look as below
account_name | dr_code | cr_code |amount | rate | category
A | 12582 | 12582 |5000 |30 | POP
B | 55AG98 | 55AG98 |2000 |40 ... | [
"If you don't want pyarrow to guess what types the result should have, you need to pass a schema when doing this conversion.\nE.g.\nimport pandas\nimport pyarrow\ndf = pandas.read_excel(file.xlsx, {usecols: [0, 1,4,6,7, 8]})\nschema = pyarrow.schema([\n ('account_name', pa.string()),\n ('dr_code', pa.string()... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"pyarrow",
"python",
"serialization"
] | stackoverflow_0074157587_dataframe_pandas_pyarrow_python_serialization.txt |
Q:
Dataframe : using all the values of an other column for a regression and then storing the result at the same index as the corresponding value
I have a database in the following form :
Date
temp
result
t1
obs1
r1,1
t1
obs2
r1,2
t1
obs3
r1,3
t2
obs1
r2,1
t2
obs2
r2,2
t2
obs3
r2,3
t3
obs1
r3,1
t3
obs2
r3,2
... | Dataframe : using all the values of an other column for a regression and then storing the result at the same index as the corresponding value | I have a database in the following form :
Date
temp
result
t1
obs1
r1,1
t1
obs2
r1,2
t1
obs3
r1,3
t2
obs1
r2,1
t2
obs2
r2,2
t2
obs3
r2,3
t3
obs1
r3,1
t3
obs2
r3,2
database
....
I want to do a regression linear w.r.t the date on the values "result" for each observation, for example :
For obs1, ... | [
"First, turn columns 'Date' and 'temp' into your data as MultiIndex.\nIterate through the desired indexes to process each subdataframe.\nThen, use 'df.loc[ row_indexer, col_indexer ]' to select and asign values.\nimport pandas as pd\ndf = pd.read_csv('database.csv')\n\n\ndf.set_index(['temp', 'Date'], inplace=True)... | [
0
] | [] | [] | [
"dataframe",
"python",
"regression"
] | stackoverflow_0074155796_dataframe_python_regression.txt |
Q:
Difference between MultiOutputRegressor(RandomForestRegressor()) versus RandomForestRegressor() when predicting multiple outputs?
It's not clear to me why some resources online demonstrate a multi-target Random Forest regression as being instantiated as either
model = MultiOutputRegressor(RandomForestRegressor())
... | Difference between MultiOutputRegressor(RandomForestRegressor()) versus RandomForestRegressor() when predicting multiple outputs? | It's not clear to me why some resources online demonstrate a multi-target Random Forest regression as being instantiated as either
model = MultiOutputRegressor(RandomForestRegressor())
versus:
model = RandomForestRegressor()
when both seemingly generate multiple regressed outputs. Can anyone clarify?
| [
"The internal models are different, but they are both multioutput regressors.\nMultiOutputRegressor fits one random forest for each target. Each tree inside then is predicting one of your outputs.\nWithout the wrapper, RandomForestRegressor fits trees targeting all the outputs at once. The split criteria are base... | [
0
] | [] | [] | [
"python",
"random_forest",
"regression",
"scikit_learn"
] | stackoverflow_0074155460_python_random_forest_regression_scikit_learn.txt |
Q:
Pyinstaller fails to import module __PyInstaller_hooks_0_IPython
I am building a project just for fun and I want to turn it into an exe but it gives me the error
PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_IPython required by hook for module c:\users\waddy\appda... | Pyinstaller fails to import module __PyInstaller_hooks_0_IPython | I am building a project just for fun and I want to turn it into an exe but it gives me the error
PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_IPython required by hook for module c:\users\waddy\appdata\local\programs\python\python39\lib\site-packages\_pyinstaller_hooks... | [
"In my case this exception was caused by missing text-unidecode package.\nIt was resolved by\npip install text-unidecode\n\nLook complete traceback of exception and see if there is any other package missing in your case.\n",
"Try to uninstall pyinstaller and re-install it using pip\nAnd if it doesn't work for you... | [
1,
0,
0
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0068788047_pyinstaller_python.txt |
Q:
java.lang.IllegalStateException: Error occurred when wrapping object
Here is my problem to solve using optapy.
@problem_fact
class Room:
id: int
name: str
def __init__(self, id, name):
self.id = id
self.name = name
@planning_id
def get_id(self):
return self.id
def... | java.lang.IllegalStateException: Error occurred when wrapping object | Here is my problem to solve using optapy.
@problem_fact
class Room:
id: int
name: str
def __init__(self, id, name):
self.id = id
self.name = name
@planning_id
def get_id(self):
return self.id
def __str__(self):
return f"Room(id={self.id}, name={self.name})"
@... | [
"Your model is incorrect: you have a chained @planning_variable in Slot without an anchor value range ('timeslotRangeLSEntity' and 'timeslotRangeLBEntity' correspond to Lesson and Lab respectively, which are both planning entities that extend Slot, which cannot be used as an anchor). I am guessing you want TimeSlot... | [
1,
0
] | [] | [] | [
"optapy",
"python"
] | stackoverflow_0074095348_optapy_python.txt |
Q:
Retrieve class schedule changes from website using python and selenium No Such Element error, ID, XPATH, and more
My school has a system that tells us if our schedule has any changes.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait,... | Retrieve class schedule changes from website using python and selenium No Such Element error, ID, XPATH, and more | My school has a system that tells us if our schedule has any changes.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import Timeout... | [
"You can not seek the element because it is layed inside the iframe. So, you have to:\n\nfind iframe\nswitch to it\nfind your element\nclick on it\n\nframe = driver.find_element(By.XPATH, value=\"//iframe[@title='Embedded Content']\")\ndriver.switch_to.frame(frame)\nelem = driver.find_element(By.XPATH, value=\"//a[... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074157239_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
After save dataframe to excel I can't open the excel file
I created dataframe, and use df.to_excel('test.xlsx', index=False). I can see my python code generated excel file in a local directory, but problem is I can't open it with excel.
I also added more parameter engine='xlsxwriter' in df.to_excel('test.xlsx', i... | After save dataframe to excel I can't open the excel file | I created dataframe, and use df.to_excel('test.xlsx', index=False). I can see my python code generated excel file in a local directory, but problem is I can't open it with excel.
I also added more parameter engine='xlsxwriter' in df.to_excel('test.xlsx', index=False). Thus I tried
df.to_excel('test.xlsx', index=False,... | [
"I'm responding some time later, but it may be helpful to someone\nYou may try by using an ExcelWriter, paying attention to include the .close(), which actually saves the file. In fact, as documentation reports \"The writer should be used as a context manager. Otherwise, call close() to save and close any opened fi... | [
0,
0
] | [
"It should work as expected. I tried your program with the following sample input (tab separated):\nM L\nfoo 123\nbar 456\nbaz 789\n\nAnd was able to open the output 123.xlsx file:\n\nCan you try this simple input and see if it works.\n",
"It is excel issue after I updated it. Please close this issue stackoverf... | [
-1,
-1
] | [
"dataframe",
"excel",
"pandas",
"python"
] | stackoverflow_0057186307_dataframe_excel_pandas_python.txt |
Q:
ARIMA seasonal prediction with Python: x12a and x13as not found on path
I am using Statsmodels to implement seasonal ARIMA prediction for time series. Here is my code :
import statsmodels.api as sm
from statsmodels.tsa.x13 import x13_arima_select_order, _find_x12
import pandas
import scipy
import numpy
import imp... | ARIMA seasonal prediction with Python: x12a and x13as not found on path | I am using Statsmodels to implement seasonal ARIMA prediction for time series. Here is my code :
import statsmodels.api as sm
from statsmodels.tsa.x13 import x13_arima_select_order, _find_x12
import pandas
import scipy
import numpy
import imp
data_source = imp.load_source('data_source', '/mypath/')
def main():
dat... | [
"From looking at the source code for statsmodels.tsa.x13 you need to have either the x12a or x13as binary applications installed on your system.\nIn addition to that, the path to the folders where those binaries are located must be set in your user's PATH environment variable.\nYou don't mention what operating syst... | [
7,
0
] | [] | [] | [
"python",
"statsmodels"
] | stackoverflow_0032053770_python_statsmodels.txt |
Q:
jinja2.exceptions.TemplateNotFound error when making a python virtual environment
so I have made a website using Flask which was working perfectly fine until today when I tried to create a python virtual environment. Does anyone know what could have happened? This is the code for my python file.
from flask import ... | jinja2.exceptions.TemplateNotFound error when making a python virtual environment | so I have made a website using Flask which was working perfectly fine until today when I tried to create a python virtual environment. Does anyone know what could have happened? This is the code for my python file.
from flask import Flask, render_template
app = Flask(__name__, template_folder='html_scripts')
@app.rou... | [
"In render_template, try using the actual html files. The code below fixes your problem\nfrom flask import Flask, render_template\n\napp = Flask(__name__, template_folder='html_scripts')\n\n@app.route('/home/')\ndef home():\n return render_template('/home_page.html')\n\n@app.route('/about/')\ndef about():\n r... | [
2,
0
] | [] | [] | [
"flask",
"python",
"virtual_environment"
] | stackoverflow_0069801449_flask_python_virtual_environment.txt |
Q:
Python anywhere don't see file
all. Today i wanted upload my small-forum on pythonanywhere. I debug some there mistakes, for example absence folder 'static' :). But now i cant delete one mistake.
for my forum i use a small database by file database.json but pythonanywhere doesn't see my file.
i uploaded my file
... | Python anywhere don't see file | all. Today i wanted upload my small-forum on pythonanywhere. I debug some there mistakes, for example absence folder 'static' :). But now i cant delete one mistake.
for my forum i use a small database by file database.json but pythonanywhere doesn't see my file.
i uploaded my file
but i have bug.
`FileNotFoundError: ... | [
"Try putting the full path, in your case I think that would be\nopen(\"/home/Gsites2023/mysite/database.json\", \"r\")\n\nthat is if the database is in the same directory as the main flask app script.\n",
"For me this answer solved it.\nEssentially, you need to append the root from pythonanywhere to your file pat... | [
3,
0
] | [] | [] | [
"flask",
"python",
"pythonanywhere"
] | stackoverflow_0073435698_flask_python_pythonanywhere.txt |
Q:
Can't return class instance parameters after getting class instance
I'm having trouble calling back a class' self.name.
I'm a bit lost because i pulled this from another file i'm working on where calling "classinstance[0].parameter" works but it won't here.
Basically i can get the class instance from BidRequest.fi... | Can't return class instance parameters after getting class instance | I'm having trouble calling back a class' self.name.
I'm a bit lost because i pulled this from another file i'm working on where calling "classinstance[0].parameter" works but it won't here.
Basically i can get the class instance from BidRequest.find_bid_request(), but i can't return any of the parameters of the BidRequ... | [
"the error was found. The dataframe was a csv file that needed to be reformated because it had two hidden rows of data that couldn't be read by the layman and needed to be fixed.\nTLDR: Dataframe error\n"
] | [
0
] | [] | [] | [
"class",
"instance",
"python"
] | stackoverflow_0074143394_class_instance_python.txt |
Q:
Concatenate the result of multiple functions
I have this code that contains multiple function. The output is fine except that the result of each function appears on a different line. I actually want the output concatenated as one item. I used +, %, f', almost everything I see on the net. Please help. The code is b... | Concatenate the result of multiple functions | I have this code that contains multiple function. The output is fine except that the result of each function appears on a different line. I actually want the output concatenated as one item. I used +, %, f', almost everything I see on the net. Please help. The code is below.
import string
import asyncio
async def get_... | [
"This is because print by default ends with a newline (\\n) character.\nYou can override this:\ndef print_many_lines():\n print(\"line 1\")\n print(\"line 2\")\n print(\"line 3\")\n\ndef print_one_line():\n print(\"line 1\", end=\" \")\n print(\"line 2\", end=\" \")\n print(\"line 3\")\n\nYou coul... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074157794_python.txt |
Q:
Delete last line from multiple docx files in python
I want to delete text of multiple docx file using python language.
Let's say the contents of a file are:
This is line 1
This is line 2
This is line 3
This is line 4
I want to delete the very last line only i.e. This is line 4.
I've tried many code but getting er... | Delete last line from multiple docx files in python | I want to delete text of multiple docx file using python language.
Let's say the contents of a file are:
This is line 1
This is line 2
This is line 3
This is line 4
I want to delete the very last line only i.e. This is line 4.
I've tried many code but getting errors.
Try 1:
with open(r"FILE_PATH.docx", 'r+', errors='i... | [
"You will not get the correct lines from a docx using that method, a docx is not the like a text file. (If you use your current method on a txt file it will work).\nDo this and you can see what you are removing:\nwith open(r\"FILE_PATH.docx\", 'r+', errors='ignore') as fp:\n # read an store all lines into list\n... | [
1
] | [] | [] | [
"file_handling",
"python",
"python_3.x",
"python_docx"
] | stackoverflow_0074157418_file_handling_python_python_3.x_python_docx.txt |
Q:
Hi, i am trying to do an app that counts your clicks using python, tkinter. The problem is that the buttons won't work. Can someone help me?
import tkinter as tk
counter = 0
def counter_label (label):
counter = 0
def count():
global counter
counter+=1
label.config(text = str(counter... | Hi, i am trying to do an app that counts your clicks using python, tkinter. The problem is that the buttons won't work. Can someone help me? | import tkinter as tk
counter = 0
def counter_label (label):
counter = 0
def count():
global counter
counter+=1
label.config(text = str(counter))
label.after(1000, count)
count()
root = tk.Tk()
root.geometry("250x200")
root.title("Vladuzz208 SRL")
label = tk.Label(root, tex... | [
"Like @acw1668 mentioned you should move the counter inside ambda() however, it could also be simplified quite a bit and if you want your label to update correctly you should move that also. Maybe this will help.\nimport tkinter as tk\n\ncounter = 0\n\nroot = tk.Tk()\n\nroot.geometry(\"250x200\")\nroot.title(\"Vla... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074157684_python_tkinter.txt |
Q:
2Darray column slicing using 2 square brackets
Defining a 2D array:
array_2D = np.array([[20,30,40,50,60], [43,54,65,76,87], [11,22,33,44,55]])
array_2D
Output:
array([[20, 30, 40, 50, 60],
[43, 54, 65, 76, 87],
[11, 22, 33, 44, 55]])
Need to change the values of the last column
But I cannot do it ... | 2Darray column slicing using 2 square brackets | Defining a 2D array:
array_2D = np.array([[20,30,40,50,60], [43,54,65,76,87], [11,22,33,44,55]])
array_2D
Output:
array([[20, 30, 40, 50, 60],
[43, 54, 65, 76, 87],
[11, 22, 33, 44, 55]])
Need to change the values of the last column
But I cannot do it using the code below
array_2D[:][-1] = 10
array_2D
... | [
"I have hard time understanding what is you question.\nBut I take that you already know how to do this.\n# Change values of the last column\narray_2D[:,-1]=10\n# Change values of the last line\narray_2D[-1,:]=10\n\nSo, if I understand correctly, your question is why you can't do that with\narray_2D[:][-1]=10\n# and... | [
0
] | [] | [] | [
"arrays",
"matrix",
"numpy_slicing",
"python",
"slice"
] | stackoverflow_0074157695_arrays_matrix_numpy_slicing_python_slice.txt |
Q:
Transform XML file to CSV with Python
I need to convert my xml file to csv file using Python. The xml is hadly nested and I use the next code:
#head = ['order-date', 'original-order-no', 'customer-email', 'quantity']
head = ['order_no', 'order_date', 'name', 'email', 'product_id', 'product_name', 'quantity']
body... | Transform XML file to CSV with Python | I need to convert my xml file to csv file using Python. The xml is hadly nested and I use the next code:
#head = ['order-date', 'original-order-no', 'customer-email', 'quantity']
head = ['order_no', 'order_date', 'name', 'email', 'product_id', 'product_name', 'quantity']
body = []
for i in root.findall('.//customer/cu... | [
"Consider XSLT, special-purpose language to transform XML files such as flattening nested documents for easier migration to a two-dimensional data frame. The recently added IO tool, pandas.read_xml, using the third-party lxml parser supports XSLT 1.0 scripts.\nSpecifically, below XSLT will parse down to lowest gran... | [
0
] | [] | [] | [
"csv",
"python",
"transformation",
"xml",
"xml_parsing"
] | stackoverflow_0074145880_csv_python_transformation_xml_xml_parsing.txt |
Q:
turning lists into dictionary for frequencies (Python)
I have been given two lists (wofo and role). One is just words, and the other one tells you if the word has been used as a metaphor in a text or not.
The first few entries look like this, if you print them:
wofo:
Lichtfiguren
nachhängt
diese
Sterne
fallen
role... | turning lists into dictionary for frequencies (Python) | I have been given two lists (wofo and role). One is just words, and the other one tells you if the word has been used as a metaphor in a text or not.
The first few entries look like this, if you print them:
wofo:
Lichtfiguren
nachhängt
diese
Sterne
fallen
role:
Metapher
Anker
Anker
Metapher
Metapher
(so the words don't... | [
"This might likely work better for you:\nlemma_met = {}\nlemma_ank = {}\n\nwofo2 = wofo.split(\"\\n\") # these may not be separating your strings into list\nrole2 = role.split(\"\\n\")\n#wofo2 = wofo.split(\" \") # these might likely be splitting your string into a list form which will work with your output.\n#wofo... | [
1,
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074157582_dictionary_list_python.txt |
Q:
why is math.sin() not working, or converting to degrees
I have a simple problem. I am trying to use sin() and I am getting answers different
from my calculator
Here is the code:
r = math.sin(45)
q = math.degrees(r)
print(r)
print(q)
I am obviously getting the numbers of r = 0.8509035245341184 &
q = 48.75318072861... | why is math.sin() not working, or converting to degrees | I have a simple problem. I am trying to use sin() and I am getting answers different
from my calculator
Here is the code:
r = math.sin(45)
q = math.degrees(r)
print(r)
print(q)
I am obviously getting the numbers of r = 0.8509035245341184 &
q = 48.75318072861148 which is not the same result as my calculator.
| [
"As it was noted here, math.sin accepts radians input.\nMore to it, to reverse from sine value to degrees, you would need to obtain inverse sine, which is arcsin and is in radians in math, and then obtain degrees from that.\nr = math.sin(math.radians(45))\nq = math.degrees(math.asin(r))\nprint(r)\nprint(q)\n\nOutpu... | [
4
] | [] | [] | [
"math",
"python",
"trigonometry"
] | stackoverflow_0074157793_math_python_trigonometry.txt |
Q:
Learning Better Way of Doing It (Django Models)
I am doing Django and I have 4 models. District, Province, Schools and User. The District belongs to a Province, in the School model/table there are the foreign keys to which the school belong. In the User table, I have district, province and school foreign keys. the... | Learning Better Way of Doing It (Django Models) | I am doing Django and I have 4 models. District, Province, Schools and User. The District belongs to a Province, in the School model/table there are the foreign keys to which the school belong. In the User table, I have district, province and school foreign keys. these tuples were named province or district in the tabl... | [
"related_name is used for reverse relations..\nan Example of one: from a District Object, I want to get all of the students in the distinct\ndistrictObj.student_set.all()\n# > Returns a list of Students\n\n# format: {model}_set\n\nNow you've got a conflict because student_set (the default) is taken, I'm not 100% wh... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074157771_django_python.txt |
Q:
PyQt5 doesn't launch QProcess in a window-chain
I have a program that requires several scripts to work together.
I managed to recreate the situation with a simplified example.
I have a main window (here called the StartTestUIv01) that is launched from another script (here called LaunchTestv01) so that variables an... | PyQt5 doesn't launch QProcess in a window-chain | I have a program that requires several scripts to work together.
I managed to recreate the situation with a simplified example.
I have a main window (here called the StartTestUIv01) that is launched from another script (here called LaunchTestv01) so that variables and options can be added in my actual script. This main... | [
"Solved it!\nThanks to @musicamante for the clues.\nI only had to change the two launching scripts as so:\nLaunchTestv01\n## This will launch StartTestUIv01 with the button\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtCore import QProcess\nfrom StartTestUIv01 import Ui_MainWindow\n\nclass Window(QtWidgets.QMainWindow... | [
0
] | [] | [] | [
"pyqt5",
"python",
"qprocess",
"qt_designer",
"subprocess"
] | stackoverflow_0074147842_pyqt5_python_qprocess_qt_designer_subprocess.txt |
Q:
Query regarding Pytorch LSTM code snippet
In the Stack Overflow thread How can i add a Bi-LSTM layer on top of bert model?, there is a line of code:
hidden = torch.cat((lstm_output[:,-1, :256],lstm_output[:,0, 256:]),dim=-1)
Can someone explain why the concatenation of last and first tokens and not any other? Wha... | Query regarding Pytorch LSTM code snippet | In the Stack Overflow thread How can i add a Bi-LSTM layer on top of bert model?, there is a line of code:
hidden = torch.cat((lstm_output[:,-1, :256],lstm_output[:,0, 256:]),dim=-1)
Can someone explain why the concatenation of last and first tokens and not any other? What would these two tokens contain that they were... | [
"In bidirectional models, hidden states gets concatenated at each step; so, the line basically concatenates the first :256 units of the last hidden state in the positive direction (-1) to the last 256: units of the last hidden state in the negative direction (0). Such locations contain the most \"interesting\" summ... | [
0
] | [] | [] | [
"deep_learning",
"lstm",
"python",
"pytorch"
] | stackoverflow_0074153439_deep_learning_lstm_python_pytorch.txt |
Q:
python - Letter Count Dict
Write a Python function called LetterCount() which takes a string as an argument and returns a dictionary of letter counts.
The line:
print LetterCount("Abracadabra, Monsignor")
Should produce the output:
{'a': 5, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'i': 1, 'm': 1, 'o': 2, 'n': 2, 's': 1, ... | python - Letter Count Dict | Write a Python function called LetterCount() which takes a string as an argument and returns a dictionary of letter counts.
The line:
print LetterCount("Abracadabra, Monsignor")
Should produce the output:
{'a': 5, 'c': 1, 'b': 2, 'd': 1, 'g': 1, 'i': 1, 'm': 1, 'o': 2, 'n': 2, 's': 1, 'r': 3}
I tried:
import collect... | [
"You are close. Note that in the task description, the case of the letters is not taken into account. They want {'a': 5}, where you have {'a': 4, 'A': 1}.\nSo you have to convert the string to lower case first (I'm sure you will find out how).\n",
"Use dictionary for the letter count:\ns = \"string is an immutabl... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005606421_python.txt |
Q:
ImportError: DLL load failed while importing _gdal: The specified module could not be found
I have a python script that previously worked but that now throws the error:ImportError: DLL load failed while importing _gdal: The specified module could not be found. I am trying to upload a shapefile using fiona and orig... | ImportError: DLL load failed while importing _gdal: The specified module could not be found | I have a python script that previously worked but that now throws the error:ImportError: DLL load failed while importing _gdal: The specified module could not be found. I am trying to upload a shapefile using fiona and originally the message read: ImportError: DLL load failed while importing _fiona: The specified modul... | [
"I was struggling badly with the same problem for the last couple of days. Using conda, I've tried everything I found on the internet such as:\nconda update gdal\nconda update -n base -c defaults conda \nCreating new environments (over and over again).\nDespite it's not recommended I even tried it with pip in... | [
1,
1
] | [] | [] | [
"conda",
"dll",
"dllimport",
"package",
"python"
] | stackoverflow_0071344780_conda_dll_dllimport_package_python.txt |
Q:
ValueError: could not convert string to float: 'male'
I'm running the following python script:
%%time
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
print(cross_val_scores['DecisionTreeClassifier']['best_params'])
decision_tree = DecisionTreeClassifier(
random_... | ValueError: could not convert string to float: 'male' | I'm running the following python script:
%%time
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
print(cross_val_scores['DecisionTreeClassifier']['best_params'])
decision_tree = DecisionTreeClassifier(
random_state=RAND_STATE,
class_weight='balanced',
max_depth=3
... | [
"You probably jump the section \"Handle Categorical Data\". You have to make a dummy of categorical features (like \"sex\"), because DecisionTreeClassifier works with numerical types only.\n# handle categorical data\ncat_cols = X.select_dtypes(include=['object','category']).columns\ndummies = pd.get_dummies(X[cat_c... | [
0
] | [] | [] | [
"machine_learning",
"python"
] | stackoverflow_0074156877_machine_learning_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.