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:
"Timed out waiting for debuggee to spawn" error for certain conda envs on vs code?
Update:
I just discovered that with a python 3.7 environment created with Anaconda (version number 4.11.0, which creates a python 3.7.11), this problem happens while python 3.8(.12) created by conda doesn't have this kind of problem... | "Timed out waiting for debuggee to spawn" error for certain conda envs on vs code? | Update:
I just discovered that with a python 3.7 environment created with Anaconda (version number 4.11.0, which creates a python 3.7.11), this problem happens while python 3.8(.12) created by conda doesn't have this kind of problem.
And I found a solution: I use integratedTerminal in the launch.json, and without speci... | [
"Upon reading this post I tried changing my conda env. I might have changed it a few times and tried to debug. Eventually 1 just worked. I thought maybe it was a python version, so I switched to a conda env which just a few seconds earlier hadn't worked with debugging. But this time it just worked.\nI don't hav... | [
0
] | [] | [] | [
"python",
"visual_studio_code",
"vscode_debugger"
] | stackoverflow_0071015203_python_visual_studio_code_vscode_debugger.txt |
Q:
How to integrate RabbitMQ RPC into FastApi properly
I am improving my FastAPI project. One of the methods needs to run a heavy computational task on another machine. Due to the high load this should be done in a queue way. I am following RabbitMQ RPC guide to perform remote procedure call via message queue.
This g... | How to integrate RabbitMQ RPC into FastApi properly | I am improving my FastAPI project. One of the methods needs to run a heavy computational task on another machine. Due to the high load this should be done in a queue way. I am following RabbitMQ RPC guide to perform remote procedure call via message queue.
This guide suggests to create exclusive queue for each client-s... | [
"I've managed to solve all those problems by simply using Celery with RabbitMQ as backend\n"
] | [
0
] | [] | [] | [
"fastapi",
"python",
"rabbitmq",
"rpc"
] | stackoverflow_0074415094_fastapi_python_rabbitmq_rpc.txt |
Q:
Upload image on Facebook Marketplace with selenium (python)
I am trying to automatize the creation of ads on facebook marketplace.
I success in log in and go on the correct page.
But I don't how to upload an image with selenium.
Indeed, the element which handle the uploading of image is not an input type=file but ... | Upload image on Facebook Marketplace with selenium (python) | I am trying to automatize the creation of ads on facebook marketplace.
I success in log in and go on the correct page.
But I don't how to upload an image with selenium.
Indeed, the element which handle the uploading of image is not an input type=file but a div which has a role of a button which open the windows file wi... | [
"Uploading file with Selenium is done by sending the uploaded file to a special element. This is not an element you are clicking as a user via GUI to upload elements. The element actually receiving uploaded files normally matching this XPath:\n//input[@type='file']\nThis is the fully working code - I tried this on ... | [
0
] | [] | [] | [
"automation",
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074479046_automation_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
Python 1 printing an input letter-by-letter with sys
I am testing the sys module's ability to print a string letter-by-letter on the same line. When I try to print an input this way, it works until it prints "none". I don't yet know enough about sys to find and correct the problem. I tried finding a similar questi... | Python 1 printing an input letter-by-letter with sys | I am testing the sys module's ability to print a string letter-by-letter on the same line. When I try to print an input this way, it works until it prints "none". I don't yet know enough about sys to find and correct the problem. I tried finding a similar question on this site, but only found answers for coding languag... | [
"I have found one way that works. After liner(prompt) is run, it stays on the same line unless \\n is used:\n liner(\"Enter the input here.\")\n x=input()\n\nHowever, I was still wondering if there is a one-line solution so I don't need to enter multiple lines of code every time I print a string.\n"
] | [
0
] | [] | [] | [
"input",
"python",
"sys"
] | stackoverflow_0074479126_input_python_sys.txt |
Q:
Python Concatenate strings stored in one variable into a single list
so i have this variable which has stored multiple strings:
123
456
789
876
543
each string inside the variable is also classified as a string:
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
however when i try to get them ... | Python Concatenate strings stored in one variable into a single list | so i have this variable which has stored multiple strings:
123
456
789
876
543
each string inside the variable is also classified as a string:
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
however when i try to get them all into a single list with attemps like:
for x in varwithstr:
full_ls... | [
"The lines are separated by '\\n' (newline) and not ' ' (space). So maybe this can work.\nl = x.split(\"\\n\")\n\n"
] | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074479095_list_python.txt |
Q:
A more pythonic way for string placeholders?
Is there a more pythonic way to do the following? F-strings seem to require a defined variable (no empty expressions) but if I want to define @names and @locations later on, what is the best way to go about it?
funct_a = call_function()
str_a = f"a very long string of ... | A more pythonic way for string placeholders? | Is there a more pythonic way to do the following? F-strings seem to require a defined variable (no empty expressions) but if I want to define @names and @locations later on, what is the best way to go about it?
funct_a = call_function()
str_a = f"a very long string of text that contains {funct_a} and also @names or @l... | [
"Escape {}'s from the f-string and use them later on in format:\nnow = 'hey'\n\ns = f'{now}, then {{names}} or {{locations}}'\n\n# later on\n\nprint(s.format(names='foo', locations='bar'))\n\nNB: requires some care if the immediate expansion also contains {}.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0074479092_python.txt |
Q:
what could be the cause of this error in python vs code?
enter code here
i = 0
sums = []
while i <= 1000:
if i%3==0 or i%5==0:
sums.append(i)
i=i+1
for i in sums:
total = sums[i] + sums[i+1]
print(total)
The problem was:
If we list all the natural numbers below 10 that are multiples of 3 or 5,... | what could be the cause of this error in python vs code? | enter code here
i = 0
sums = []
while i <= 1000:
if i%3==0 or i%5==0:
sums.append(i)
i=i+1
for i in sums:
total = sums[i] + sums[i+1]
print(total)
The problem was:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find ... | [
"for i in sums:\n total = sums[i] + sums[i+1]\n\nimagine that sums array have 5 elements.\nand values like [3,5,7,10,15]\nand when you looped like above, it assigns values in order 3,5,7,10,15.\nSo as we do not have seventh elementh in the list it gives up an error.\nHowever there is a easier way to do this\npri... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074479183_python.txt |
Q:
Amazon website shows "Deliver to Country". How can I change it programmatically in Python Selenium to take screenshots
The problem:
I want to search keywords on Amazon and take screenshots. I am using selenium package. However, when I search on amazon.co.uk, it shows delivery address as Unites States. How can I ch... | Amazon website shows "Deliver to Country". How can I change it programmatically in Python Selenium to take screenshots | The problem:
I want to search keywords on Amazon and take screenshots. I am using selenium package. However, when I search on amazon.co.uk, it shows delivery address as Unites States. How can I change the "Deliver to Country"?
Below are sample Python code and a sample screenshot.
import time as t
from datetime import d... | [
"In order to set UK delivery address on UK Amazon when your IP address is out from the UK you can do the following steps:\n\nOpen the \"Delivery to\" dialog\nInsert some valid UK postal code and click submit button\nApprove this on the appeared after that pop-up.\nAs you asked, I also added the code to close cookie... | [
1,
1
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074478453_css_selectors_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
matplotlib has no attribute 'pyplot'
I can import matplotlib but when I try to run the following:
matplotlib.pyplot(x)
I get:
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
matplotlib.pyplot(x)
AttributeError: 'module' object has no attribute 'pyplot'
A:
pyplot is a sub-mo... | matplotlib has no attribute 'pyplot' | I can import matplotlib but when I try to run the following:
matplotlib.pyplot(x)
I get:
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
matplotlib.pyplot(x)
AttributeError: 'module' object has no attribute 'pyplot'
| [
"pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.\n>>> import matplotlib\n>>> print matplotlib.pyplot\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'module' object has no attribute 'pyplot'\n>>> import matplotlib.pyplot\... | [
59,
42
] | [
"You have to import matplotlib.pyplot\nimport matplotlib.pyplot as plt\n"
] | [
-1
] | [
"matplotlib",
"python"
] | stackoverflow_0014812342_matplotlib_python.txt |
Q:
Extract date from string in a pandas dataframe column
I am trying to extract date from a DF column containing strings and store in another column.
from dateutil.parser import parse
extract = parse("January 24, 1976", fuzzy_with_tokens=True)
print(str(extract[0]))
The above code extracts: 1976-01-24 00:00:00
I w... | Extract date from string in a pandas dataframe column | I am trying to extract date from a DF column containing strings and store in another column.
from dateutil.parser import parse
extract = parse("January 24, 1976", fuzzy_with_tokens=True)
print(str(extract[0]))
The above code extracts: 1976-01-24 00:00:00
I would like this to be done to all strings in a column in a D... | [
"See pd.to_datetime\nIt operates in a vectorized manner so can convert all dates quickly.\ndf[\"Dates\"] = pd.to_datetime(df[\"Dates\"])\n\nIf there are strings that won't convert to a datetime and you want them nullified, you can use errors=\"coerce\"\ndf[\"Dates\"] = pd.to_datetime(df[\"Dates\"], errors=\"coerce\... | [
1,
0
] | [] | [] | [
"extract",
"pandas",
"python",
"python_dateutil"
] | stackoverflow_0074479115_extract_pandas_python_python_dateutil.txt |
Q:
Large dataset and finding permutations matching various criteria
I have a list of football players with length 15000 which consists of dicts (same size all). An element in the list looks like this:
{
'id': '123456',
'name': 'Foo Bar',
'position': 'GK',
'club': 'Python FC',
'league': 'Champions... | Large dataset and finding permutations matching various criteria | I have a list of football players with length 15000 which consists of dicts (same size all). An element in the list looks like this:
{
'id': '123456',
'name': 'Foo Bar',
'position': 'GK',
'club': 'Python FC',
'league': 'Champions League',
'country': 'Neverland'
}
Given a team which consists of... | [
"Here's a couple of things which will help, but they won't reduce this to a tractable problem (see below).\nFirst,\nsquads = product(list_goalkeepers, list_strikers, list_strikers, .....)\n\nis not actually correct. product([striker1, striker2], [striker1, striker2]) (to just look a small bit of that product) gener... | [
0
] | [] | [] | [
"generator",
"list",
"permutation",
"python"
] | stackoverflow_0074476651_generator_list_permutation_python.txt |
Q:
TypeError: unsupported operand type(s) for +: 'DatetimeArray' and 'relativedelta'
I am trying to convert a column called Month_Next from a dataframe called df_actual from the last day of one month to the first day of the next. The column looks like this:
And I'm using
df_actual.Month_Next = pd.to_datetime(df_actu... | TypeError: unsupported operand type(s) for +: 'DatetimeArray' and 'relativedelta' | I am trying to convert a column called Month_Next from a dataframe called df_actual from the last day of one month to the first day of the next. The column looks like this:
And I'm using
df_actual.Month_Next = pd.to_datetime(df_actual.Month_Next) + relativedelta(months=1, day=1)
and getting this error.
TypeError: uns... | [
"You are trying to add date types from different packages - one from pandas and the other dateutil. Try converting them to pandas types (use pandas.Timedelta).\nExample:\nimport pandas as pd\n\ndatetime_arr = pd.arrays.DatetimeArray(pd.Series([0, 1, 2, 3, 4]))\n\nprint(datetime_arr)\nprint(datetime_arr + pd.Timedel... | [
1,
1
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python",
"relativedelta"
] | stackoverflow_0074467623_dataframe_datetime_pandas_python_relativedelta.txt |
Q:
How to convert Python dictionary to Scala equivalent (Map?)?
I have a large (~700K) Python dictionary that has many sub-dictionaries, that I need to convert to whatever the appropriate equivalent is in Scala (Map?). It can be immutable. What's the easiest/quickest way to do this?
The dictionary is a hardcoded stat... | How to convert Python dictionary to Scala equivalent (Map?)? | I have a large (~700K) Python dictionary that has many sub-dictionaries, that I need to convert to whatever the appropriate equivalent is in Scala (Map?). It can be immutable. What's the easiest/quickest way to do this?
The dictionary is a hardcoded static dictionary in the source code of a larger Python script, which ... | [] | [] | [
"When you say you \"have it in python\", where is it coming from? Is python code generating it, or reading it from a file, or...?\nI ask because my first move would be to try to just re-implement whatever is loading/generating it into the python runtime in scala instead. Otherwise you're adding unnecessary performa... | [
-1
] | [
"python",
"scala"
] | stackoverflow_0074479328_python_scala.txt |
Q:
I get an error while installing python-docx how can i solve this?
C:\Users\Mateo>pip install python-docx
Collecting python-docx
Using cached python_docx-0.8.11-py3-none-any.whl
Collecting lxml>=2.3.2
Using cached lxml-4.9.1.tar.gz (3.4 MB)
Preparing metadata (setup.py) ... done
Building wheels for collected ... | I get an error while installing python-docx how can i solve this? | C:\Users\Mateo>pip install python-docx
Collecting python-docx
Using cached python_docx-0.8.11-py3-none-any.whl
Collecting lxml>=2.3.2
Using cached lxml-4.9.1.tar.gz (3.4 MB)
Preparing metadata (setup.py) ... done
Building wheels for collected packages: lxml
Building wheel for lxml (setup.py) ... error
error: ... | [
"Okay after an hour of searching :) I found something that works. So for the beginners like me I'll explain it very simple.\n\nFirst download the right lxml file here:\nhttp://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml\nThen type this in cmd:\npip install C:\\path\\to\\downloaded\\file\\lxml‑4.5.2‑cp39‑cp39‑win32.whl... | [
1
] | [] | [] | [
"libxml2",
"pip",
"python",
"python_docx",
"xml"
] | stackoverflow_0074479256_libxml2_pip_python_python_docx_xml.txt |
Q:
High accuracy during training and validation, low accuracy during prediction with the same dataset
So I'm trying to train Keras model. There is high accuracy (I'm using f1score, but accuracy is also high) while training and validating. But when I'm trying to predict some dataset I'm getting lower accuracy. Even if... | High accuracy during training and validation, low accuracy during prediction with the same dataset | So I'm trying to train Keras model. There is high accuracy (I'm using f1score, but accuracy is also high) while training and validating. But when I'm trying to predict some dataset I'm getting lower accuracy. Even if I predict training set. So I guess it's not about overfitting problem. What then is the problem?
import... | [
"Since you use a last layer of\nmodel.add(Dense(2, activation='softmax')\n\nyou should not use loss='binary_crossentropy' in model.compile(), but loss='categorical_crossentropy' instead.\nDue to this mistake, the results shown during model fitting are probably wrong - the results returned by sklearn's f1_score are ... | [
1,
0,
0
] | [] | [] | [
"deep_learning",
"keras",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0066452884_deep_learning_keras_machine_learning_python_tensorflow.txt |
Q:
how to use pandas groupby to aggregate data across multiple columns
I have a pandas dataframe:
Reference
timestamp
sub_reference
datatype_indicator
figure
REF1
2022-09-01
10
A
23.6
REF1
2022-09-01
48
B
25.8
REF1
2022-09-02
10
A
17.4
REF1
2022-10-01
10
A
23.6
REF1
2022-10-01
48
B
25.8
REF1
2022-10-02
10
A
17... | how to use pandas groupby to aggregate data across multiple columns | I have a pandas dataframe:
Reference
timestamp
sub_reference
datatype_indicator
figure
REF1
2022-09-01
10
A
23.6
REF1
2022-09-01
48
B
25.8
REF1
2022-09-02
10
A
17.4
REF1
2022-10-01
10
A
23.6
REF1
2022-10-01
48
B
25.8
REF1
2022-10-02
10
A
17.4
REF2
2022-09-01
10
A
23.6
REF2
2022-09-01
48
B
25.8
R... | [
"I've never used the pd.Grouper before, but I think your issue is with how it is treating the extraction of the month.\nI tried it like this:\n>>> # add a new column for month\n>>> df1[\"month\"] = df1[\"timestamp\"].dt.month\n\n>>> dg = df1.groupby(by=[\"Reference\", \"month\"], as_index=False).agg({\"figure\":sum... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python",
"sum"
] | stackoverflow_0074479192_dataframe_group_by_pandas_python_sum.txt |
Q:
Pandas ValueError when creating series indexes from a list of pd.Index objects
When trying to create a pandas Series in the following way, I am receiving a ValueError:
indexes = [pd.Index([1]), pd.Index([2])]
pd.Series(
["a", "b"],
index=indexes
)
ValueError: Length of values (2) does not match length of... | Pandas ValueError when creating series indexes from a list of pd.Index objects | When trying to create a pandas Series in the following way, I am receiving a ValueError:
indexes = [pd.Index([1]), pd.Index([2])]
pd.Series(
["a", "b"],
index=indexes
)
ValueError: Length of values (2) does not match length of index (1)
Is this expected/documented behaviour?
Tested on:
python3.11/pandas1.5.1... | [
"Why are you not using ?\nindexes = [1,2]\npd.Series(\n [\"a\", \"b\"], \n index=indexes\n)\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074479349_pandas_python.txt |
Q:
Is there a faster way to create a df from a txt file?
I have a .txt file with lines such as "G1 X174.774 Y46.362 E1.48236", "M73 Q1 S245", all with one letter then a number and then a space. I'm trying to create a dataframe such that each row is a line from my file and each column is a letter. If my file were just... | Is there a faster way to create a df from a txt file? | I have a .txt file with lines such as "G1 X174.774 Y46.362 E1.48236", "M73 Q1 S245", all with one letter then a number and then a space. I'm trying to create a dataframe such that each row is a line from my file and each column is a letter. If my file were just the two lines above, my resulting dataframe would be
G X ... | [
"Yes, I suspect there is. Do not incrementally increase the number of rows in a dataframe in a loop:\ndf.loc[j] = pd.Series(line_dict)\n\nThis will result in quadratic time complexity.\nInstead, accumulate those dicts into a list, then create a pandas dataframe from that list at the very end. So:\ndata = []\nfor li... | [
1,
0
] | [] | [] | [
"dictionary",
"loops",
"optimization",
"pandas",
"python"
] | stackoverflow_0074479254_dictionary_loops_optimization_pandas_python.txt |
Q:
parsing telegram MessageMediaPoll and print it as readable text
Good day every one,
I'm trying to parse telegram poll data, I have the following:
{'_': 'MessageMediaPoll', 'poll': {'_': 'Poll', 'id': 578954245254551900254, 'question': 'Have you seen it ?! ', 'answers': [{'_': 'PollAnswer', 'text': 'Lost', 'option'... | parsing telegram MessageMediaPoll and print it as readable text | Good day every one,
I'm trying to parse telegram poll data, I have the following:
{'_': 'MessageMediaPoll', 'poll': {'_': 'Poll', 'id': 578954245254551900254, 'question': 'Have you seen it ?! ', 'answers': [{'_': 'PollAnswer', 'text': 'Lost', 'option': [48]}, {'_': 'PollAnswer', 'text': 'Am lose', 'option': [49]}, {'_'... | [
"data = {'_': 'MessageMediaPoll', 'poll': {'_': 'Poll', 'id': 57894245245450254, 'question': 'Have you seen it ?! ', 'answers': [{'_': 'PollAnswer', 'text': 'Lost', 'option': [48]}, {'_': 'PollAnswer', 'text': 'Am lose', 'option': [49]}, {'_': 'PollAnswer', 'text': 'Have lost', 'option': [50]}, {'_': 'PollAnswer', ... | [
0
] | [] | [] | [
"python",
"telegram"
] | stackoverflow_0074433968_python_telegram.txt |
Q:
Minecraft Clone Bug - Ursina Engine
I don't know why my minecraft clone destroys blocks of the ground, where I don't want. Here's my code:
from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
from random import *
from perlin_noise import *
app = Ursina()
player = FirstPers... | Minecraft Clone Bug - Ursina Engine | I don't know why my minecraft clone destroys blocks of the ground, where I don't want. Here's my code:
from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
from random import *
from perlin_noise import *
app = Ursina()
player = FirstPersonController()
Sky(color=color.azure,text... | [
"I have to do this, but the hole isn't still displayed yet.\nfrom ursina import *\nfrom ursina.prefabs.first_person_controller import FirstPersonController\nfrom random import *\nfrom perlin_noise import *\n#import pyautogui\napp = Ursina()\nplayer = FirstPersonController()\nSky(color=color.azure,texture=None)\namp... | [
0,
0,
0
] | [] | [] | [
"python",
"ursina"
] | stackoverflow_0074307820_python_ursina.txt |
Q:
How to manipulate a python list based on the following restrictions?
import numpy as np
m1 = np.arange(1,10).reshape(3,3)
diagonal = np.diag(m1)
antdiagonal =[]
for j in range(0,3):
x = m1[j][3-1-j]
antdiagonal.append(x)
def common_data(list1, list2):
result = Fa... | How to manipulate a python list based on the following restrictions? | import numpy as np
m1 = np.arange(1,10).reshape(3,3)
diagonal = np.diag(m1)
antdiagonal =[]
for j in range(0,3):
x = m1[j][3-1-j]
antdiagonal.append(x)
def common_data(list1, list2):
result = False
for x in list1:
for y in list2:
if x... | [
"pdiagonal = []\npantidiagonal = []\n\n# for Principal Diagonal\ndef getPrincipalDiagonal(mat, n):\n for i in range(n):\n for j in range(n):\n if (i == j):\n pdiagonal.append(mat[i][j])\n\n# for Anti-Diagonal\ndef getSecondaryDiagonal(mat, n):\n for i in range(n):\n for... | [
0
] | [] | [] | [
"data_science",
"python"
] | stackoverflow_0074464301_data_science_python.txt |
Q:
Python: get value from dictionary when key is a list
I have a dictionary where the key is a list
cfn = {('A', 'B'): 1, ('A','C'): 2 , ('A', 'D'): 3}
genes = ['A', 'C', 'D', 'E']
I am trying to get a value from the dictionary if the gene pairs in the key exist in a list together. My attempt is as follows, however ... | Python: get value from dictionary when key is a list | I have a dictionary where the key is a list
cfn = {('A', 'B'): 1, ('A','C'): 2 , ('A', 'D'): 3}
genes = ['A', 'C', 'D', 'E']
I am trying to get a value from the dictionary if the gene pairs in the key exist in a list together. My attempt is as follows, however I get TypeError: unhashable type: 'list'
def create_netwo... | [
"Your keys in cfn are of type tuple as a key needs to be a hashable type.\nHashable types are immutable data types such as:\n\nint\nstring\ntuple\nfrozenset\n\nas they can't be changed or mutated. Otherwise you can't access the value stored at that key.\nSo in your case you just need to change these [] into this ()... | [
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074479316_dictionary_list_python.txt |
Q:
Error in simple Caesar Cypher program - Python v3
In the below code, an unexpected output is produced. The desired result is as follows:
Enter a plaintext message and then the rotation key. The plaintext is then converted to cypher text and saved to a file. For example, a user enters 'Hello!' and a key of 13. The ... | Error in simple Caesar Cypher program - Python v3 | In the below code, an unexpected output is produced. The desired result is as follows:
Enter a plaintext message and then the rotation key. The plaintext is then converted to cypher text and saved to a file. For example, a user enters 'Hello!' and a key of 13. The output should give 'Uryyb!' and write it to a file.
Som... | [
"You are overwriting cypher_text in each iteration of the loop.\n# Set cypher_text to an empty string to add to later\ncypher_text = ''\n\nYou should move this line before the loop.\n# Set cypher_text to an empty string to add to later\ncypher_text = ''\n# Iterate through each character in the message.\nfor char in... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074477270_python.txt |
Q:
Django - Python: 'int' object has no attribute 'get'
I am setting up a Django project to allow tickets to be sold for various theatre dates with a price for adults and a price for children. I have created a models.py and ticket_details.html.
I am unfortunately receiving the following error: 'int' object has no att... | Django - Python: 'int' object has no attribute 'get' | I am setting up a Django project to allow tickets to be sold for various theatre dates with a price for adults and a price for children. I have created a models.py and ticket_details.html.
I am unfortunately receiving the following error: 'int' object has no attribute 'get' and I am at a loss to how I am to get the adu... | [
"The issue is how you are iterating in for item_id, adult_quantity in bag.items():. I see that bag is a dictionary, and I think that it's a dictionary like:\n{\n 'item_id': 1,\n 'quantity': 10,\n 'ticket': ticket,\n 'adult_ticket': True,\n}\n\nIf this is correct, then why do you need to iterate through... | [
0
] | [] | [] | [
"django",
"e_commerce",
"model",
"price",
"python"
] | stackoverflow_0074477773_django_e_commerce_model_price_python.txt |
Q:
Draw text around image in semicircular path in Python
I need to write/draw some text of the objects in an image around semicircular path, I have used ImageMagic/Wand using the image.distort method but it works for longer text, if the text is small it looks bad. Is there a way in PIL or ImageMagic/Wand to achieve t... | Draw text around image in semicircular path in Python | I need to write/draw some text of the objects in an image around semicircular path, I have used ImageMagic/Wand using the image.distort method but it works for longer text, if the text is small it looks bad. Is there a way in PIL or ImageMagic/Wand to achieve that.
I am looking for something like this image.
I have al... | [
"You can pad the text with spaces in Imagemagick.\nconvert -font Arial -pointsize 20 label:' Your Curved Text Your Curved Text ' -virtual-pixel Background -background white -distort Arc 360 -rotate -90 arc_circle_text.jpg\n\n\nconvert -font Arial -pointsize 20 label:' Text ' -virtu... | [
1
] | [] | [] | [
"image_processing",
"imagemagick",
"python",
"python_imaging_library",
"wand"
] | stackoverflow_0074468853_image_processing_imagemagick_python_python_imaging_library_wand.txt |
Q:
ASGI_APPLICATION not working with Django Channels
I followed the tutorial in the channels documentation but when I start the server python3 manage.py runserver it gives me this :
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
October 17, 202... | ASGI_APPLICATION not working with Django Channels | I followed the tutorial in the channels documentation but when I start the server python3 manage.py runserver it gives me this :
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
October 17, 2022 - 00:13:21
Django version 4.1.2, using settings 'conf... | [
"This could be due to the fact that the Django and channels versions you have used are not compatible\nTry : channels==3.0.4 and django==4.0.0\n",
"Use version of python that support by channels, you will found it at pypi channels page\n",
"I had the same problem, and found that there was a new release of Chann... | [
4,
0,
0
] | [] | [] | [
"django",
"django_channels",
"python"
] | stackoverflow_0074091600_django_django_channels_python.txt |
Q:
Django list_display does not work at reverse model
Django list_display does not work at reverse model, i want to list_display the title and the production company of two seperated but related tables.
here ist my model.py
class ProjectBaseModel(models.Model):
title = models.CharField("Titel", max_length=100, blank=... | Django list_display does not work at reverse model | Django list_display does not work at reverse model, i want to list_display the title and the production company of two seperated but related tables.
here ist my model.py
class ProjectBaseModel(models.Model):
title = models.CharField("Titel", max_length=100, blank=False, unique=True)
former_title = models.CharField("ehe... | [
"My question was not precise enough. Yes, the FeatureFilm table points with a Foreignkey to a ProjectCompanySet table. and this has a field: production_company. what I actually want is that the first ProjectCompanySet entry and from it the first company is shown to me. What I have managed in the meantime is that th... | [
0
] | [] | [] | [
"django",
"django_admin",
"foreign_keys",
"orm",
"python"
] | stackoverflow_0074453280_django_django_admin_foreign_keys_orm_python.txt |
Q:
Iterate over all the sub-groups of a list
Let's say I have a list [1,2,3,4,5,6], and I want to iterate over all the subgroups of len 2 [1,2] [3,4] [5,6].
The naive way of doing it
L = [1,2,3,4,5,6]
N = len(L)//2
for k in range(N):
slice = L[k*2:(k+1)*2]
for val in slice:
#Do... | Iterate over all the sub-groups of a list | Let's say I have a list [1,2,3,4,5,6], and I want to iterate over all the subgroups of len 2 [1,2] [3,4] [5,6].
The naive way of doing it
L = [1,2,3,4,5,6]
N = len(L)//2
for k in range(N):
slice = L[k*2:(k+1)*2]
for val in slice:
#Do things with the slice
However I was wondering... | [
"Use the grouper recipe from the itertools library:\nimport itertools\n\ndef grouper(iterable, n, fillvalue=None):\n \"Collect data into fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return itertools.zip_longest(*args, fillvalue=fillvalu... | [
2,
1
] | [] | [] | [
"list",
"numpy",
"python"
] | stackoverflow_0074479111_list_numpy_python.txt |
Q:
Remove element in list with bool flag with List Comprehension
Wondering if there would be a neat way to use List Comprehension to accomplish removing an element from a list based on a bool.
example
test_list = [
"apple",
"orange",
"grape",
"lemon"
]
apple = True
if apple:
test_list.... | Remove element in list with bool flag with List Comprehension | Wondering if there would be a neat way to use List Comprehension to accomplish removing an element from a list based on a bool.
example
test_list = [
"apple",
"orange",
"grape",
"lemon"
]
apple = True
if apple:
test_list.remove("apple")
print(test_list)
expected output
['orange', 'grap... | [
"test_list = [x for x in test_list if not (apple and x == \"apple\")]\n\nResults:\n>>> apple = True\n>>> [x for x in test_list if not (apple and x == \"apple\")]\n['orange', 'grape', 'lemon']\n\n>>> apple = False\n>>> [x for x in test_list if not (apple and x == \"apple\")]\n['apple', 'orange', 'grape', 'lemon']\n\... | [
1,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0074479220_list_comprehension_python.txt |
Q:
Why does ZoneInfo("UTC") do different time conversions from timezone.utc?
I was trying to convert a datetime from one timezone to another. I'm in the process of updating our Python codebase to stop relying on utilities we don't need anymore. In particular, I'm deprecating our use of arrow and pytz. In doing so, I ... | Why does ZoneInfo("UTC") do different time conversions from timezone.utc? | I was trying to convert a datetime from one timezone to another. I'm in the process of updating our Python codebase to stop relying on utilities we don't need anymore. In particular, I'm deprecating our use of arrow and pytz. In doing so, I noticed some strange behavior from ZoneInfo("UTC").
from datetime import dateti... | [
"Cannot reproduce. Did you make sure tzdata is installed and up-to-date?\nOn\nPython 3.9.15 (main, Oct 30 2022, 10:17:28) \n[GCC 11.3.0] on linux\n\nI get Toronto time at UTC-5 as expected for both options:\nfrom datetime import datetime, timezone\nfrom zoneinfo import ZoneInfo\n\njan1_in_utc = datetime.fromisoform... | [
0,
0
] | [] | [] | [
"datetime",
"python",
"zoneinfo"
] | stackoverflow_0074467999_datetime_python_zoneinfo.txt |
Q:
PySpark - Collect vs CrossJoin, which to choose to create a max column?
Spark Masters!
Does anyone has some tips on which is better or faster on pyspark to create a column with the max number of another column.
Option A:
max_num = df.agg({"number": "max"}).collect()[0][0]
df = df.withColumn("max", f.lit(max_num))
... | PySpark - Collect vs CrossJoin, which to choose to create a max column? | Spark Masters!
Does anyone has some tips on which is better or faster on pyspark to create a column with the max number of another column.
Option A:
max_num = df.agg({"number": "max"}).collect()[0][0]
df = df.withColumn("max", f.lit(max_num))
Option B:
max_num = df2.select(f.max(f.col("number")).alias("max"))
df2 = df... | [
"I added another method similar to your B method, which consists in creating a Window over all dataframe and then taking the maximum value on it:\ndf3.withColumn(\"max\", F.max(\"number\").over(Window.partitionBy()))\n\n\nHere is how the three methods performed over a dataframe of 100 million rows (I couldn't fit m... | [
1,
0
] | [] | [] | [
"apache_spark",
"collect",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074469309_apache_spark_collect_dataframe_pyspark_python.txt |
Q:
Solve almostIncreasingSequence (Codefights)
Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
Example
For sequence [1, 3, 2, 1], the output should be:
almostIncreasingSequence(sequence) = false;
... | Solve almostIncreasingSequence (Codefights) | Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
Example
For sequence [1, 3, 2, 1], the output should be:
almostIncreasingSequence(sequence) = false;
There is no one element in this array that can be... | [
"Your algorithm is much too simplistic. You have a right idea, checking consecutive pairs of elements that the earlier element is less than the later element, but more is required.\nMake a routine first_bad_pair(sequence) that checks the list that all pairs of elements are in order. If so, return the value -1. Othe... | [
53,
16,
6,
5,
5,
3,
2,
2,
2,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"Swift\n//Brute Force\n//Running Time: O(n * n)\nfunc isIncreasing(sequence: [Int]) -> Bool {\n if sequence.count == 1 { return true }\n \n var isStrictlyIncreasing = false\n \nfor (indexOfPotentialNumberToRemove) in 0...sequence.count - 1 {\n \n print(\"indexOfPotentialNumberToRemove: \\(indexOfPotenti... | [
-1
] | [
"arrays",
"python"
] | stackoverflow_0043017251_arrays_python.txt |
Q:
SublimeText3: How to set spaces to 4 on .py file only?
I am using SublimeText3 and writing HTML/CSS so I set spaces to 2 on editing HTML/CSS files but I want to use 4 spaces auto on editing .py files.
How to do it?
A:
While you have any particular file open, choosing Preferences > Settings - Syntax Specific will... | SublimeText3: How to set spaces to 4 on .py file only? | I am using SublimeText3 and writing HTML/CSS so I set spaces to 2 on editing HTML/CSS files but I want to use 4 spaces auto on editing .py files.
How to do it?
| [
"While you have any particular file open, choosing Preferences > Settings - Syntax Specific will open/create a set of preferences that apply only to files of that particular type.\nSettings in a syntax specific preferences file are applied on top of the global default preferences, allowing you to specify for partic... | [
1
] | [] | [] | [
"python",
"sublimetext3"
] | stackoverflow_0074469375_python_sublimetext3.txt |
Q:
I am creating a face recognition system using Python and OpenCV on these versions
AttributeError: module 'cv2' has no attribute 'face'
face_recognizer = cv2.face.createLBPHFaceRecognizer()
A:
As stated in this answer, you have to install opencv-contrib-python
pip install opencv-contrib-python
| I am creating a face recognition system using Python and OpenCV on these versions | AttributeError: module 'cv2' has no attribute 'face'
face_recognizer = cv2.face.createLBPHFaceRecognizer()
| [
"As stated in this answer, you have to install opencv-contrib-python\npip install opencv-contrib-python\n\n"
] | [
1
] | [] | [] | [
"face_recognition",
"opencv",
"python"
] | stackoverflow_0074479428_face_recognition_opencv_python.txt |
Q:
Numpy doesn't respond accurate in m1 macbook
I have macbook pro m1 pro and I have tested some simple numpy commands on it and it doesn't respond correctly but if I check the same command in an online compiler it respond ok.
Can you help me please?
import numpy as np
y=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(np.l... | Numpy doesn't respond accurate in m1 macbook | I have macbook pro m1 pro and I have tested some simple numpy commands on it and it doesn't respond correctly but if I check the same command in an online compiler it respond ok.
Can you help me please?
import numpy as np
y=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(np.linalg.det(y))
the result in my Macbook is : -9.51... | [
"Comparing two floats (or doubles etc) can be problematic. Generally, instead of comparing for exact equality they should be checked against an error bound. If they are within the error bound, they are considered equal.\nJust round the results and you will always get 0. it is nothing to do with mac. it could be two... | [
0
] | [] | [] | [
"apple_m1",
"numpy",
"python"
] | stackoverflow_0074479446_apple_m1_numpy_python.txt |
Q:
How do I switch to a Python log formatter I have defined in my logging.ini file?
This is my logging.ini file:
[loggers]
keys=root
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter,json
[logger_root]
level=INFO
handlers=consoleHandler
[handler_consoleHandler]
class=StreamHandler
formatter=json
ar... | How do I switch to a Python log formatter I have defined in my logging.ini file? | This is my logging.ini file:
[loggers]
keys=root
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter,json
[logger_root]
level=INFO
handlers=consoleHandler
[handler_consoleHandler]
class=StreamHandler
formatter=json
args=(sys.stdout,)
[formatter_json]
class=pythonjsonlogger.jsonlogger.JsonFormatter
for... | [
"Adding this an answer, but it's not a very good one.\nI wound up just creating a separate log config file and switching like this:\nLOG_CONFIG_PROFILE = os.environ.get(\"LOG_CONFIG_PROFILE\", \"logging_conf_local\")\nlogging_config_file_path = path.join(\n path.dirname(path.abspath(__file__)), f\"{LOG_CONFIG_PR... | [
0
] | [] | [] | [
"python",
"python_logging"
] | stackoverflow_0074478345_python_python_logging.txt |
Q:
My python list doesn't understand letters :(
my Code doesent understand letters in the list i would like somone to help me fix this
usernames = (BTP, btp, Btp, BTp)
def username(usernames2):
if usernames == input('whats your username? : ')
Its a simple username system, i plan to use for a interface im making.... | My python list doesn't understand letters :( | my Code doesent understand letters in the list i would like somone to help me fix this
usernames = (BTP, btp, Btp, BTp)
def username(usernames2):
if usernames == input('whats your username? : ')
Its a simple username system, i plan to use for a interface im making.
| [
"usernames is defined as a tuple of 4 items, with the names BTP, btp, Btp, and BTp. You said \"list\" in your title but your code has no actual lists. Lists use brackets, tuples use parentheses.\nAnyway, I'm assuming you actually want to check if the user's input actually was equal to the letters \"btp\" and you wa... | [
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074479654_python_python_3.x.txt |
Q:
pd.read_excel throws PermissionError if file is open in Excel
Whenever I have the file open in Excel and run the code, I get the following error which is surprising because I thought read_excel should be a read only operation and would not require the file to be unlocked?
Traceback (most recent call last):
F... | pd.read_excel throws PermissionError if file is open in Excel | Whenever I have the file open in Excel and run the code, I get the following error which is surprising because I thought read_excel should be a read only operation and would not require the file to be unlocked?
Traceback (most recent call last):
File "C:\Users\Public\a.py", line 53, in <module>
main()
File ... | [
"Generally Excel have a lot of restrictions when opening files (can't open the same file twice, can't open 2 different files with the same name ..etc).\nI don't have excel on machine to test, but checking the docs for read_excel I've noticed that it allows you to set the engine.\nfrom the stack trace you posted it ... | [
3,
2,
2,
0,
0
] | [
"I fix this error simply closing the .xlsx file that was open.\n",
"You can set engine = 'xlrd', then you can run the code while Excel has the file open.\ndf = pd.read_excel(filename, sheetname, engine = 'xlrd')\n\nYou may need to pip install xlrd if you don't have it\n",
"You may also want to check if the file... | [
-1,
-2,
-2,
-3
] | [
"excel",
"pandas",
"python"
] | stackoverflow_0035743905_excel_pandas_python.txt |
Q:
I have a variable value in lower case and the same value is in one of the dictionary keys how do I fulfill the condition
i have document_title variable value with lowercase letters and same value is in the dic keys with upercase letter
TITLE_MAP = {
'AUS Marketing Consent': "DOCUMENT_TYPE_MARKETING_CONSENT",
... | I have a variable value in lower case and the same value is in one of the dictionary keys how do I fulfill the condition | i have document_title variable value with lowercase letters and same value is in the dic keys with upercase letter
TITLE_MAP = {
'AUS Marketing Consent': "DOCUMENT_TYPE_MARKETING_CONSENT",
'Consent & History': "DOCUMENT_TYPE_CONSENT",
}
document_title = 'aus marketing consent'
if i do this won't work with... | [
"You can use the casefold method to do string comparison. Since you want to apply it to all the keys, you can use a list comprehension.\nif document_title.casefold() in [x.casefold() for x in TITLE_MAP.keys()]:\n print(True)\n\nHope this helps.\n",
"if document_title.upper() in TITLE_MAP.key():\n return True... | [
1,
0,
0,
0
] | [] | [] | [
"character",
"dictionary",
"python",
"string"
] | stackoverflow_0074479418_character_dictionary_python_string.txt |
Q:
Counting each day in a dataframe
Say I have a dataframe 'df':
I would like to add an additional column named 'Day No' which adds a count to each day. Desired output below:
This wont reset at the end of each month, the count will just continue. For example at the end of the year it will read 365 for all the 1 hou... | Counting each day in a dataframe | Say I have a dataframe 'df':
I would like to add an additional column named 'Day No' which adds a count to each day. Desired output below:
This wont reset at the end of each month, the count will just continue. For example at the end of the year it will read 365 for all the 1 hour entries in the last day of the year.... | [
"here is one way to do it\n# convert to datetime and extract dayofyear\n\ndf['Day No']= pd.to_datetime(df['DateTime'], dayfirst=True).dt.dayofyear\n\nPS: if you had shared df constructor or as text, i would have been able to share the result\n",
"You can map the result of enumerated unique values:\nreversed_dict ... | [
2,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074479445_dataframe_pandas_python.txt |
Q:
Compare and count the sparse arrays in a list in python
Holla!
I have a list of 60 large-size 2d arrays (30000,30000).
The goal is to compare each array with every other array and count the total number of exactly the same arrays in the entire list.
I am working on this logic, however, it is counting the number of... | Compare and count the sparse arrays in a list in python | Holla!
I have a list of 60 large-size 2d arrays (30000,30000).
The goal is to compare each array with every other array and count the total number of exactly the same arrays in the entire list.
I am working on this logic, however, it is counting the number of same arrays individually and not what I want:
import numpy a... | [
"EDIT#3:\nBased on your comments, I think this is what you are trying to do.\nimport numpy as np\nfrom copy import deepcopy\n\ndef convert_to_tuple(mat):\n x = tuple(np.flatnonzero(mat)) + mat.shape\n return (x)\n\ndef get_replicates(id, mat, mat_list):\n replicates = 0\n \n #Remove the relevant matr... | [
1,
1
] | [] | [] | [
"arrays",
"list",
"numpy",
"python",
"sparse_matrix"
] | stackoverflow_0074397307_arrays_list_numpy_python_sparse_matrix.txt |
Q:
lxml find all elements between two tags
extracted a word document and search in this all bookmarks. But the bookmark tag have no end tag, so lxml find only the bookmarkStart but not the elements between bookmarkStart and bookmarkEnd. How can i get all Elements within bookmarkStart and bookmarkEnd? Thanks!
<?xml ve... | lxml find all elements between two tags | extracted a word document and search in this all bookmarks. But the bookmark tag have no end tag, so lxml find only the bookmarkStart but not the elements between bookmarkStart and bookmarkEnd. How can i get all Elements within bookmarkStart and bookmarkEnd? Thanks!
<?xml version="1.0" encoding="UTF-8" standalone="yes"... | [
"If I understand you correctly, and based on the sample xml in the question, the following should get you at least close to what you are trying to do:\nword = \"\"\"[your sample xml]\"\"\"\ndoc = etree.XML(word.encode())\nns = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}\nstart_param = 'w:b... | [
0
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0074474718_lxml_python.txt |
Q:
How to install a win32 version of python using win64 anaconda
I am trying to set up the covarep software on my win64 machine for a project and need to install 'a Windows 32-bit version of Python 2.7, 3.3, and/or 3.4'.
I used conda (platform win-64) to run conda create -n "covarep-env" python=3.4.0 -c free
This cre... | How to install a win32 version of python using win64 anaconda | I am trying to set up the covarep software on my win64 machine for a project and need to install 'a Windows 32-bit version of Python 2.7, 3.3, and/or 3.4'.
I used conda (platform win-64) to run conda create -n "covarep-env" python=3.4.0 -c free
This created an environment that has python version 3.4.0, but this obvious... | [
"You must set the CONDA_FORCE_32BIT environment variable (got it from [YouTube]: DotPi - Create 32-bit Python Environments from a 64-bit Conda Installation) before creating the environment (not related to (previous) \"environment variable\").\nUnfortunately the only official reference I could find is [Anaconda.Docs... | [
1
] | [] | [] | [
"anaconda",
"anaconda3",
"python",
"windows"
] | stackoverflow_0074479238_anaconda_anaconda3_python_windows.txt |
Q:
Problem with parent-child class and turtle, kernel says it is an error in the turtle bib
Below is the code I have and the error which is displayed is: turtle.Vec2D() argument after * must be an iterable, not int.
The task is to create a square, triangle, polygon and rectangle. The properties should be put togethe... | Problem with parent-child class and turtle, kernel says it is an error in the turtle bib | Below is the code I have and the error which is displayed is: turtle.Vec2D() argument after * must be an iterable, not int.
The task is to create a square, triangle, polygon and rectangle. The properties should be put together in a parent class. Each other class should be the child class from the class GeometricObject... | [
"The problem appears to be that you're playing fast and loose with argument order:\nclass GeometricObject: \n def __init__(self, starting_angle = 45, side_length = 100, position = (0,0)): \n \nclass Square(GeometricObject):\n def __init__(self, side_length, position, starting_angle, turn = 90):\n su... | [
0
] | [] | [] | [
"parent_child",
"python",
"turtle_graphics"
] | stackoverflow_0074477328_parent_child_python_turtle_graphics.txt |
Q:
Cannot pickle Tensorflow object in Python - TypeError: can't pickle _thread._local objects
I want to pickle the history object after running a keras fit on tensorflow. But I am getting an error.
import gzip
import numpy as np
import os
import pickle
import tensorflow as tf
from tensorflow import keras
with gzip.o... | Cannot pickle Tensorflow object in Python - TypeError: can't pickle _thread._local objects | I want to pickle the history object after running a keras fit on tensorflow. But I am getting an error.
import gzip
import numpy as np
import os
import pickle
import tensorflow as tf
from tensorflow import keras
with gzip.open('mnist.pkl.gz', 'rb') as f:
train_set, test_set = pickle.load(f, encoding='latin1')
X_... | [
"As Karl suggested, the history object cannot be pickled. But it's dictionary can:\nwith open('models/basic_history.pickle', 'wb') as f:\n pickle.dump(history.history, f)\n\n",
"joblib also worked for me:\nimport joblib\nmodel_filename = \"lstm.pkl\"\njoblib.dump(history.history, model_filename)\n\n"
] | [
8,
1
] | [] | [] | [
"pickle",
"python",
"tensorflow"
] | stackoverflow_0059326551_pickle_python_tensorflow.txt |
Q:
Identify uploaded file type from buffer
I'm using django to accept files from the user (mostly csv, text and excel).
I need to detect the file type for further processing
Using python-magic I'm getting different results for reading a file and a buffer
import magic
magic.from_file('/testfiles/xls.xls',mime=True... | Identify uploaded file type from buffer | I'm using django to accept files from the user (mostly csv, text and excel).
I need to detect the file type for further processing
Using python-magic I'm getting different results for reading a file and a buffer
import magic
magic.from_file('/testfiles/xls.xls',mime=True)
'application/vnd.ms-excel'
f = open('/test... | [
"You can use filetype Python Package(pip install filetype). The below code worked for me :\nimport filetype\n\nfileinfo = filetype.guess(mock.jpg) #the argument can be buffer or file\ndetectedExt = fileinfo.extension\ndetectedmime = fileinfo.mime\n\nfiletype package documentation\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0020160548_django_python.txt |
Q:
set x axis as column names on barplot
I have a dataframe such as this:
data = {'name': ['Bob', 'Chuck', 'Daren', 'Elisa'],
'100m': [19, 14, 12, 11],
'200m': [36, 25, 24, 24],
'400m': [67, 64, 58, 57],
'800m': [117, 120, 123, 121]}
df = pd.DataFrame(data)
name 100m 200m ... | set x axis as column names on barplot | I have a dataframe such as this:
data = {'name': ['Bob', 'Chuck', 'Daren', 'Elisa'],
'100m': [19, 14, 12, 11],
'200m': [36, 25, 24, 24],
'400m': [67, 64, 58, 57],
'800m': [117, 120, 123, 121]}
df = pd.DataFrame(data)
name 100m 200m 400m 800m
1 Bob 19 36 6... | [
"Instead of using seaborn, which is an API for matplotlib, plot df directly with pandas.DataFrame.plot. matplotlib is the default plotting backend for pandas.\nTested in python 3.11, pandas 1.5.1, matplotlib 3.6.2, seaborn 0.12.1\nax = df.set_index('name').T.plot.bar(alpha=.7, rot=0, stacked=True)\n\n\nseaborn.barp... | [
2
] | [] | [] | [
"matplotlib",
"pandas",
"python",
"seaborn",
"stacked_bar_chart"
] | stackoverflow_0074479784_matplotlib_pandas_python_seaborn_stacked_bar_chart.txt |
Q:
How to give image as an user input in api request using flask in python
I am creating an API where I want to give image as an user input.
I know request.args.get take user input in dictionary format. I want to know if in any way user can give image as input to api in below api script.
My image path is E:\env\abc.p... | How to give image as an user input in api request using flask in python | I am creating an API where I want to give image as an user input.
I know request.args.get take user input in dictionary format. I want to know if in any way user can give image as input to api in below api script.
My image path is E:\env\abc.png
a.py
import pandas as pd
from datetime import datetime
from pandas import ... | [
"First, this method should be a POST and not a GET. You are putting information on the server. Second, you want to read the file from the files parameter and not one of the query parameters.\n@app.route(\"/api_endpoint\", methods=[\"POST\"])\ndef function_for_api():\n img = request.files['file']\n print(img... | [
1
] | [] | [] | [
"api",
"flask",
"python",
"rest"
] | stackoverflow_0074479707_api_flask_python_rest.txt |
Q:
In dataframe, how to speed up recognizing rows that have more than 5 consecutive previous values with same sign?
I have a dataframe like this.
val consecutive
0 0.0001 0.0
1 0.0008 0.0
2 -0.0001 0.0
3 0.0005 0.0
4 0.0008 0.0
5 0.0002 0.0
6 ... | In dataframe, how to speed up recognizing rows that have more than 5 consecutive previous values with same sign? | I have a dataframe like this.
val consecutive
0 0.0001 0.0
1 0.0008 0.0
2 -0.0001 0.0
3 0.0005 0.0
4 0.0008 0.0
5 0.0002 0.0
6 0.0012 0.0
7 0.0012 1.0
8 0.0007 1.0
9 0.0004 1.0
10 0.0002 1.0
11... | [
"One option is to avoid the use of apply() altogether.\nThe main idea is to create 2 'helper' columns:\n\nsign: boolean Series indicating if value is positive (True) or negative (False)\nid: group identical consecutive occurences together\n\nFinally, we can groupby the id and use cumulative count to isolate the row... | [
1,
0
] | [] | [] | [
"data_cleaning",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074478178_data_cleaning_dataframe_pandas_python.txt |
Q:
Parallelize nonlinear regression using multiprocessing or MPI
I have a simple nonlinear regression. It runs sequentially fine except for taking long time to complete. The process can speed up using MPI or multiprocess. How should I approach applying them to run my code?
Here is my code for nonlinear regression:
da... | Parallelize nonlinear regression using multiprocessing or MPI | I have a simple nonlinear regression. It runs sequentially fine except for taking long time to complete. The process can speed up using MPI or multiprocess. How should I approach applying them to run my code?
Here is my code for nonlinear regression:
data = pd.read_csv('....csv')
X = data.iloc[:, 0]
Y = data.iloc[:, 1]... | [
"Gradient descent is sequential by nature, you need the parameters from previous step in order to make update at the current step.\nFew optimizations you can add to improve your code include using numpy arrays instead of pandas series, and also moving the X*X outside the for loop as suggested by @Victor Eijkhout. H... | [
0
] | [] | [] | [
"mpi",
"multiprocessing",
"python",
"python_multiprocessing"
] | stackoverflow_0074479217_mpi_multiprocessing_python_python_multiprocessing.txt |
Q:
Pytorch gradient descent keeps sending me NaNs mean squared errors
I am trying to apply, within the framework of a course, a gradient descent to estimate a linear model. My code is the following :
model = torch.nn.Linear(1,1)
myModel = model(X)
ds = torch.utils.data.TensorDataset(X, Y)
dl = torch.utils.data.DataLo... | Pytorch gradient descent keeps sending me NaNs mean squared errors | I am trying to apply, within the framework of a course, a gradient descent to estimate a linear model. My code is the following :
model = torch.nn.Linear(1,1)
myModel = model(X)
ds = torch.utils.data.TensorDataset(X, Y)
dl = torch.utils.data.DataLoader(ds)
optimiser = torch.optim.SGD(model.parameters(), lr=0.01)
loss =... | [
"There is nothing wrong with your code but Nan values can be explained by gradients exploding depending on the data X and Y. You can try with a lower learning rate (1e-3 or 1e-4).\nFor instance if you test with this toy linear example:\nX = torch.randn(100, 1)\nY = X * 2 + 3\n\nThe loss will converge to 0 quickly.\... | [
1
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074476864_python_pytorch.txt |
Q:
How to set the title of a new tab when returning a fileresponse
I have an button that when pressed opens up a new tab and displays a PDF. When the new tab is opened the title looks like some sort of metadata about the PDF. ex: "Microsoft Powerpoint:The original.ppt" instead of the name of the PDF "Generated.pdf".... | How to set the title of a new tab when returning a fileresponse | I have an button that when pressed opens up a new tab and displays a PDF. When the new tab is opened the title looks like some sort of metadata about the PDF. ex: "Microsoft Powerpoint:The original.ppt" instead of the name of the PDF "Generated.pdf". How do I set the title of the tab to be the name of the actual PDF b... | [
"Think this is missing the disposition!\nTry\nresponse['Content-Disposition'] = 'attachment; filename=\"{}\"'.format(filename)\n\nor\nresponse['Content-Disposition'] = 'inline; filename=\"{}\"'.format(filename)\n\nattachment; should result in a browser window asking what you want to do with the file. \"Save as\" wi... | [
0
] | [] | [] | [
"browser",
"django",
"http",
"python"
] | stackoverflow_0074478099_browser_django_http_python.txt |
Q:
Please how do i form a dictionary from a file content that has header sections and body sections?
Given a File with the contents below :
******************
* Header title 1
* + trig apple
* + targ beans
* + trig grapes
* + targ berries
* Header title 2
* + trig beans
* + targ joke
* + trig help
* + targ me
The a... | Please how do i form a dictionary from a file content that has header sections and body sections? | Given a File with the contents below :
******************
* Header title 1
* + trig apple
* + targ beans
* + trig grapes
* + targ berries
* Header title 2
* + trig beans
* + targ joke
* + trig help
* + targ me
The above pattern repeats with every header title having a uniq string.
As i read the file i would like to c... | [
"The below code will create the file based on your sample input, then read it into an OrderedDict. This assumes headers start with * and records start with * +. It also presupposes that no records occur before the first header is set. You also likely want to clean up your text by removing new lines \\n.\nfrom colle... | [
1
] | [] | [] | [
"ordereddict",
"python"
] | stackoverflow_0074479767_ordereddict_python.txt |
Q:
Trying to compare different sized one-hot-encoded lists
I have run an autoencoder model, and returned a dictionary with each output and it's label, using FashionMNIST. My goal is to print 10 images only for the dress and coat class (class labels 3 and 4). I have one-hot-encoded the labels such that the dress class... | Trying to compare different sized one-hot-encoded lists | I have run an autoencoder model, and returned a dictionary with each output and it's label, using FashionMNIST. My goal is to print 10 images only for the dress and coat class (class labels 3 and 4). I have one-hot-encoded the labels such that the dress class appears as [0.,0,.0,1.,0.,0.,0.,0.,0.]. My dictionary output... | [
"I will post an example here.\nHere we have two arrays for you x is the label array and y the clothing . You can get in z the ones that are identical (the indexes). Finally by using the matching_indexes you can collect the onces you want from output and plot them\nx = np.array([[1., 0., 0., 0., 0., 0., 0.],\n ... | [
1
] | [] | [] | [
"arrays",
"mnist",
"python"
] | stackoverflow_0074478908_arrays_mnist_python.txt |
Q:
How to hide console window in python?
I am writing an IRC bot in Python.
I wish to make stand-alone binaries for Linux and Windows of it. And mainly I wish that when the bot initiates, the console window should hide and the user should not be able to see the window.
What can I do for that?
A:
Simply save it wit... | How to hide console window in python? | I am writing an IRC bot in Python.
I wish to make stand-alone binaries for Linux and Windows of it. And mainly I wish that when the bot initiates, the console window should hide and the user should not be able to see the window.
What can I do for that?
| [
"Simply save it with a .pyw extension. This will prevent the console window from opening.\n\nOn Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also... | [
159,
45,
28,
24,
11,
6,
1,
1,
0
] | [
"a decorator factory for this (windows version, unix version should be easier via os.fork)\ndef deco_factory_daemon_subprocess(*, flag_env_var_name='__this_daemon_subprocess__', **kwargs_for_subprocess):\n def deco(target):\n @functools.wraps(target)\n def tgt(*args, **kwargs):\n if os.e... | [
-1
] | [
"console",
"hide",
"python"
] | stackoverflow_0000764631_console_hide_python.txt |
Q:
Using win32com to control Excel and I need to update the color of Data Points but they seem to be read only
wb = excel.Workbooks.Open(f"C:\\Users\\user\\Downloads\\EXCEL\\Credits_Query.xlsx")
ws=wb.Sheets("OEM Pivot")
chart = ws.ChartObjects(1).Chart
chart.SeriesCollection(1).XValues
Returns: ('NTK553FAE5', '8DG6... | Using win32com to control Excel and I need to update the color of Data Points but they seem to be read only | wb = excel.Workbooks.Open(f"C:\\Users\\user\\Downloads\\EXCEL\\Credits_Query.xlsx")
ws=wb.Sheets("OEM Pivot")
chart = ws.ChartObjects(1).Chart
chart.SeriesCollection(1).XValues
Returns: ('NTK553FAE5', '8DG62496AA', 'TOM-100G-Q-LR4', 'ORM-CXH1', ...)
chart.SeriesCollection(1).Points(1).Fill.ForeColor.RGB
Returns: 3942... | [
"As usual, hours of researching with no luck, and 2 min after I post I find the answer.\nchart.SeriesCollection(1).Points(3).Fill.ForeColor.SchemeColor = 47\n\nThis allows you to change the color of the individual points.\n"
] | [
0
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0074479354_excel_python.txt |
Q:
How can I add a minimize / maximize buttons in GUI made with Qt Designer?
I've create a GUI in "Qt Designer". Now I'd like to open a simple window with a minimize/maximize buttons in the top right corner.
from PyQt5 import uic
window = uic.loadUi("Video_Player.ui") # Video_Player.ui is the name of my GUI main file... | How can I add a minimize / maximize buttons in GUI made with Qt Designer? | I've create a GUI in "Qt Designer". Now I'd like to open a simple window with a minimize/maximize buttons in the top right corner.
from PyQt5 import uic
window = uic.loadUi("Video_Player.ui") # Video_Player.ui is the name of my GUI main file.
window.show()
should be something like this:
window.setWindowFlag(Qt.WindowM... | [
"I think you should firstly hide the Windows bar in this way:\nself.setWindowFlag(Qt.FramelessWindowHint)\n\nAnd then add your own Minimize, Maximize and Close botton on QtDesigner. Finally for example you can make them work as follows in your code:\nself.maxBtn = self.findChild(QPushButton,'Maximize_btn')\nself.ma... | [
1,
0
] | [] | [] | [
"pyqt",
"pyqt5",
"python",
"qt_designer"
] | stackoverflow_0065165757_pyqt_pyqt5_python_qt_designer.txt |
Q:
Python script to export the all subfolders in a folder into separate .ZIP folders, but ignoring individual files?
I have a directory of subfolders that gets populated with another script. Each of those subfolders in the directory need to be compressed into a .ZIP folder.
However in that directory is also a number ... | Python script to export the all subfolders in a folder into separate .ZIP folders, but ignoring individual files? | I have a directory of subfolders that gets populated with another script. Each of those subfolders in the directory need to be compressed into a .ZIP folder.
However in that directory is also a number of files (PDFs, .TXTs etc) that are not in subfolders. I'm trying to create a script that will create zip folders out o... | [
"Use scandir instead of listdir. Then you can check to see if each is a file, a directory, or a symbolic link.\n"
] | [
0
] | [] | [] | [
"archive",
"compression",
"python",
"subdirectory",
"zip"
] | stackoverflow_0074476732_archive_compression_python_subdirectory_zip.txt |
Q:
How can i get a file extension from a filetype?
I have a list of filenames as follows
files = [
'/dl/files/4j55eeer_wq3wxxpiqm.jpg',
'/home/Desktop/hjsd03wnsbdr9rk3k',
'kd0dje7cmidj0xks03nd8nd8a3',
...
]
The problem is most of the files do not have an extension in the filenames, what would be the ... | How can i get a file extension from a filetype? | I have a list of filenames as follows
files = [
'/dl/files/4j55eeer_wq3wxxpiqm.jpg',
'/home/Desktop/hjsd03wnsbdr9rk3k',
'kd0dje7cmidj0xks03nd8nd8a3',
...
]
The problem is most of the files do not have an extension in the filenames, what would be the best way to get file extension of these files ?
I don... | [
"Once you use magic to get the MIME type, you can use mimetypes.guess_extension() to get the extension for it.\n",
"It can be done if you have an oracle that determines file types from their content. Happily at least one such oracle is already implemented in Python: https://github.com/ahupp/python-magic\n",
"T... | [
16,
3,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0016872139_file_python.txt |
Q:
Convert Eviews date format to python date
I have my vector dates in this format 2022M8,2022M09, etc... (eviews format). How do i read this type of string dates in python?
I wish convert this dates in this 20220801 format.
Thanks in advance!!
I have tried this:
date_time_str = '1973M10'
date_time_obj = datetime.st... | Convert Eviews date format to python date | I have my vector dates in this format 2022M8,2022M09, etc... (eviews format). How do i read this type of string dates in python?
I wish convert this dates in this 20220801 format.
Thanks in advance!!
I have tried this:
date_time_str = '1973M10'
date_time_obj = datetime.strptime(date_time_str, '%Y M /%m')
print ("The... | [
"small typo ?\nthis works just fine:\nfrom datetime import datetime\ndate_time_str = '1973M10'\ndate_time_obj = datetime.strptime(date_time_str, '%YM%m')\nprint (\"The type of the date is now\", type(date_time_obj))\nprint (\"The date is\", date_time_obj)\n\ngives:\nThe type of the date is now <class 'datetime.dat... | [
1
] | [] | [] | [
"date",
"python"
] | stackoverflow_0074469407_date_python.txt |
Q:
Python script to get username and password from text?
I have a script for creating accounts that outputs the following:
creating user in XYZ: username: testing firstName: Bob lastName:Test email:auto999@nowhere.com password:gWY6*Pja&4
So, I need to create a python script that will store the username and password ... | Python script to get username and password from text? | I have a script for creating accounts that outputs the following:
creating user in XYZ: username: testing firstName: Bob lastName:Test email:auto999@nowhere.com password:gWY6*Pja&4
So, I need to create a python script that will store the username and password in a csv file.
I tried splitting this string by spaces and ... | [
"Regex is almost always the answer to this type of issue:\nimport re\n\ntext = 'creating user in XYZ: username: testing firstName: Bob lastName:Test email:auto999@nowhere.com password:gWY6*Pja&4'\n\npattern = '.*username:\\s*(\\S+)\\s*firstName:\\s*(\\S+)\\s*lastName:\\s*(\\S+)\\s*email:\\s*(\\S+)\\s*password:\\s*(... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074479688_python.txt |
Q:
Converting .ui to .py with pyuic5?
When I convert a .ui file in QtDesigner to a .py file, the format changes and it runs differently.
When I run it in QtDesigner it looks like a normal page but once I convert it to a .py file and run it, the edges are cut off and I cannot see half the buttons/labels. Even once I e... | Converting .ui to .py with pyuic5? | When I convert a .ui file in QtDesigner to a .py file, the format changes and it runs differently.
When I run it in QtDesigner it looks like a normal page but once I convert it to a .py file and run it, the edges are cut off and I cannot see half the buttons/labels. Even once I expand the screen that has opened the lab... | [
"You firstly need to correctly set the layout and widgets inside them, in a way that the size of each object is guaranteed when moving to the code.\nTry to watch this tutorial, I found it very useful!\nQt Designer - create application GUI (DESIGN APPLICATION LAYOUT) - part 02\nAnd then you need to just import the .... | [
0
] | [] | [] | [
"pyqt5",
"python",
"qt_designer",
"user_interface"
] | stackoverflow_0073974721_pyqt5_python_qt_designer_user_interface.txt |
Q:
Data collation step causing "ValueError: Unable to create tensor..." due to unnecessary padding attempts to extra inputs
I am trying to fine-tune a Bart model from the huggingface transformers framework on a dialogue summarisation task. The Bart model by default takes in the conversations as a monolithic piece of ... | Data collation step causing "ValueError: Unable to create tensor..." due to unnecessary padding attempts to extra inputs | I am trying to fine-tune a Bart model from the huggingface transformers framework on a dialogue summarisation task. The Bart model by default takes in the conversations as a monolithic piece of text as the input and takes the summaries as the decoder input while training. I want to explicitly train the model on dialogu... | [
"I solved this by extending the DataCollatorForSeq2Seq class and overriding the __call__ method in it to also pad my 'spk_utt_pos' list appropriately.\n"
] | [
0
] | [] | [] | [
"huggingface",
"huggingface_transformers",
"python",
"pytorch",
"pytorch_dataloader"
] | stackoverflow_0074437271_huggingface_huggingface_transformers_python_pytorch_pytorch_dataloader.txt |
Q:
Sorting a list of lists by every list and return the final index
I want to sort a list with an arbitrary number of lists inside to sort by each of said lists.
Furthermore I do not want to use any libraries (neither python-native nor 3rd party).
data = [['a', 'b', 'a', 'b', 'a'], [9, 8, 7, 6, 5]]
I know I can achi... | Sorting a list of lists by every list and return the final index | I want to sort a list with an arbitrary number of lists inside to sort by each of said lists.
Furthermore I do not want to use any libraries (neither python-native nor 3rd party).
data = [['a', 'b', 'a', 'b', 'a'], [9, 8, 7, 6, 5]]
I know I can achieve this by doing
list(zip(*sorted(zip(*data))))
# [('a', 'a', 'a', '... | [
"Add a temporary index list to the end before sorting. The result will show you the pre-sorted indices in the appended list:\ndata = [['a', 'b', 'a', 'b', 'a'], [9, 8, 7, 6, 5]]\nassert all(len(sublist) == len(data[0]) for sublist in data)\ndata.append(range(len(data[0])))\n*sorted_data, indices = list(zip(*sorted(... | [
3,
1
] | [] | [] | [
"nested_lists",
"python",
"sorting"
] | stackoverflow_0074479939_nested_lists_python_sorting.txt |
Q:
Np.where change value in column if another column value is in another dataframe column
Let me explain the structure of the problem that I'm trying to solve.
Let's suppose that we have two dataframes
DF1:
ID
Value
AA
2
AB
1
AC
2
AD
1
AE
2
DF2:
ID
New Value
AA
1
AC
1
If the ID column row in DF1 is in DF2,... | Np.where change value in column if another column value is in another dataframe column | Let me explain the structure of the problem that I'm trying to solve.
Let's suppose that we have two dataframes
DF1:
ID
Value
AA
2
AB
1
AC
2
AD
1
AE
2
DF2:
ID
New Value
AA
1
AC
1
If the ID column row in DF1 is in DF2, then I would like to change the value in the same row in DF1 to the ... | [
"here is one way to to do it using map\n# set index on ID in DF2 and map to DF\n# replace failed mapping with the value in DF\ndf['Value']=df['ID'].map(df2.set_index(['ID'])['New Value']).fillna(df['Value'])\ndf\n\n ID Value\n0 AA 1.0\n1 AB 1.0\n2 AC 1.0\n3 AD 1.0\n4 AE 2.0\n\n",
"You can go st... | [
1,
1,
1
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074479898_dataframe_numpy_pandas_python.txt |
Q:
Azure Blob Storage with Python, create containers but not list them?
Azure Blob Storage v12.13.1
Python 3.9.15
I have no problem creating containers...
## Create the container
blob_service_client = BlobServiceClient(account_url=sas_url)
container_client = blob_service_client.create_container(container_... | Azure Blob Storage with Python, create containers but not list them? | Azure Blob Storage v12.13.1
Python 3.9.15
I have no problem creating containers...
## Create the container
blob_service_client = BlobServiceClient(account_url=sas_url)
container_client = blob_service_client.create_container(container_name)
but when I go to list them
all_containers = blob_service_client.lis... | [
"More than likely you are encountering this error is because your SAS token does not have list (l) permission.\nPlease try creating a blob service client with a SAS URL that has list permission in it.\n"
] | [
1
] | [] | [] | [
"azure",
"azure_blob_storage",
"python",
"python_3.x"
] | stackoverflow_0074479952_azure_azure_blob_storage_python_python_3.x.txt |
Q:
'int' object is not iterable in arrays with use height
I'm having a problem with this code, I need to calculate the height of a certain number of people and after that:
show the smallest and largest height of the group
the average height of the women
the percentage difference between the amount of men and women
... | 'int' object is not iterable in arrays with use height | I'm having a problem with this code, I need to calculate the height of a certain number of people and after that:
show the smallest and largest height of the group
the average height of the women
the percentage difference between the amount of men and women
When running the code, an error appears:
print('A menor e ma... | [
"altura_grupo = int(input('Digite a sua altura (em cm):'))\n\nis replacing the list with the input, not adding to the list. Use append() to add to a list.\naltura_grupo.append(int(input('Digite a sua altura (em cm):')))\n\nThen you will be able to get the minimum and maximum of the list.\n"
] | [
1
] | [] | [] | [
"arrays",
"conditional_statements",
"javascript",
"python"
] | stackoverflow_0074480174_arrays_conditional_statements_javascript_python.txt |
Q:
Machine Learning: Combining Binary Encoder and RobustScaler
I have a dataset with numerical and categorical data. The data includes outliner, which are essential for interpretation later. I’ve binary encoded the categorical data and used the RobustScaler on the numerical data.
The categorical binary encoded data d... | Machine Learning: Combining Binary Encoder and RobustScaler | I have a dataset with numerical and categorical data. The data includes outliner, which are essential for interpretation later. I’ve binary encoded the categorical data and used the RobustScaler on the numerical data.
The categorical binary encoded data does not get scaled. Is this combination possible or is there a lo... | [
"There's no reason why you couldn't do that, but there's also no point.\nThe reason why you scale input features to be on roughly the same scale is that lots of inference methods get tripped up by features which are on vastly different scales. See Why does feature scaling improve the convergence speed for gradient ... | [
0
] | [] | [] | [
"data_preprocessing",
"machine_learning",
"python",
"scaling"
] | stackoverflow_0074480076_data_preprocessing_machine_learning_python_scaling.txt |
Q:
Unable to install pwn package for python
I am trying to install the pwn library on my MacBook Air (M2, 2022) but it's failing while building the wheel for unicorn. I'm using python version 3.10.6.
This is the command I'm using: python3 -m pip install --upgrade pwn
without the --upgrade part I still get the same er... | Unable to install pwn package for python | I am trying to install the pwn library on my MacBook Air (M2, 2022) but it's failing while building the wheel for unicorn. I'm using python version 3.10.6.
This is the command I'm using: python3 -m pip install --upgrade pwn
without the --upgrade part I still get the same error message.
If I replace pwn with pwntools I ... | [
"I have an M1 mac and had the same issue—nothing worked for me either, so I eventually just tried installing an older version of unicorn (if you do pip install unicorn== without specifying the version, you can list all of them), and tried different ones until one worked.\n(For me, this was just downgrading to 2.0.0... | [
0
] | [] | [] | [
"pip",
"pwntools",
"python",
"unicorn"
] | stackoverflow_0073819091_pip_pwntools_python_unicorn.txt |
Q:
how do I input custom arrays into rows & columns in 2d character array
Rows = int(input("give the number of rows:"))
Columns = int(input("Give the number of columns:"))
matrix = []
for i in range(Rows):
matrix.append(['a', 'b', 'c','d', 'e'])
for vector in matrix:
print(matrix)
here'... | how do I input custom arrays into rows & columns in 2d character array | Rows = int(input("give the number of rows:"))
Columns = int(input("Give the number of columns:"))
matrix = []
for i in range(Rows):
matrix.append(['a', 'b', 'c','d', 'e'])
for vector in matrix:
print(matrix)
here's the output:
give the number of rows:3
Give the number of columns:3
[['a', ... | [
"There are many ways to initalize an array with a specific size. Below is one of the more concise ways.\nRows = int(input(\"Give the number of rows:\"))\nColumns = int(input(\"Give the number of columns:\"))\nmatrix = [[\"a\"]*Rows]*Columns\n\nprint(matrix)\n\nThis will give the output\nGive the number of rows:3\nG... | [
0
] | [] | [] | [
"arrays",
"matrix",
"python"
] | stackoverflow_0074480133_arrays_matrix_python.txt |
Q:
The view didn't return an HttpResponse object. It returned None instead
I have the following simple view. Why is it resulting in this error?
The view auth_lifecycle.views.user_profile didn't return an HttpResponse object. It returned None instead.
"""Renders web pages for the user-authentication-lifecycle project.... | The view didn't return an HttpResponse object. It returned None instead | I have the following simple view. Why is it resulting in this error?
The view auth_lifecycle.views.user_profile didn't return an HttpResponse object. It returned None instead.
"""Renders web pages for the user-authentication-lifecycle project."""
from django.shortcuts import render
from django.template ... | [
"Because the view must return render, not just call it. (Note that render is a simple wrapper around an HttpResponse). Change the last line to\nreturn render(request, 'auth_lifecycle/user_profile.html',\n context_instance=RequestContext(request))\n\n(Also note the render(...) function returns a HttpResp... | [
105,
13,
5,
2,
0,
0,
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0026258905_django_django_views_python.txt |
Q:
Computing average loop in Python based on certain conditions met in another column
First timer posting here and new to Python, so apologies in advance if I am missing any key information below.
Essentially, I have a large CSV file that I was able to clean up a bit on scripts that contains various numerical values ... | Computing average loop in Python based on certain conditions met in another column | First timer posting here and new to Python, so apologies in advance if I am missing any key information below.
Essentially, I have a large CSV file that I was able to clean up a bit on scripts that contains various numerical values over ~150 miles of data with each data line being one foot. After I clean the file up a ... | [
"Thank you for this interesting question.\nThe idea is to create a group for each continuous value 'A', 'B', or 'C' until it changes. I also assume that your data is already sorted by mile\ndf['change'] = np.where(df['ABC']!=df['ABC'].shift(1),1.0,0.0)\n\nNow you simply cumsum to create new group indicator\ndf['gr'... | [
1,
0,
0
] | [] | [] | [
"for_loop",
"mean",
"pandas",
"python"
] | stackoverflow_0074479749_for_loop_mean_pandas_python.txt |
Q:
how to get a specific objects in an API?
Hi i'm trying to consume an API in python, I made the connection and it works pretty well.
In that API I have 100 results, and I just want to get 10 of them, do you know how to do that?
import requests
import pprint
url='https://jsonplaceholder.typicode.com/post'
response=... | how to get a specific objects in an API? | Hi i'm trying to consume an API in python, I made the connection and it works pretty well.
In that API I have 100 results, and I just want to get 10 of them, do you know how to do that?
import requests
import pprint
url='https://jsonplaceholder.typicode.com/post'
response=requests.get(url)
pprint.pprint(response.jso... | [
"When you make your request, if it was valid, the response object has a json method which returns the json data of your response.\nIn your case response.json() gives you a list of json objects. You can manipulate that like any python list.\nresult = response.json()\nfirst_ten = result[:10]\n\nWhat the [:10] notati... | [
1
] | [] | [] | [
"api",
"dictionary",
"python"
] | stackoverflow_0074480201_api_dictionary_python.txt |
Q:
How to align text left on a plotly bar chart (example image contained) [Plotly-Dash]
I need help in adding text to my graph.
I have tried text = 'y' and text-position = 'inside' but the text goes vertical or gets squashed for small bar charts so it can fit inside the bar. I just want it to write across.
Here is a ... | How to align text left on a plotly bar chart (example image contained) [Plotly-Dash] | I need help in adding text to my graph.
I have tried text = 'y' and text-position = 'inside' but the text goes vertical or gets squashed for small bar charts so it can fit inside the bar. I just want it to write across.
Here is a working example of the code that needs fixing:
app = dash.Dash(__name__)
app.css.append_cs... | [
"You can pass text into go.Bar(), where you can set textposition=\"inside\" and insidetextanchor=\"start\", which should solve this issue.\n\nfig = go.Figure(go.Bar(\n x=[20, 14, 23],\n y=['giraffes', 'orangutans', 'monkeys'],\n orientation='h',\n # define the annotations... | [
6,
2,
1,
0
] | [] | [] | [
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0055396090_plotly_plotly_dash_python.txt |
Q:
Get starlette request body in the middleware context
I have such middleware
class RequestContext(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
request_id = request_ctx.set(str(uuid4())) # generate uuid to request
body = await request.body(... | Get starlette request body in the middleware context | I have such middleware
class RequestContext(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
request_id = request_ctx.set(str(uuid4())) # generate uuid to request
body = await request.body()
if body:
logger.info(...) # log req... | [
"I would not create a Middleware that inherits from BaseHTTPMiddleware since it has some issues, FastAPI gives you a opportunity to create your own routers, in my experience this approach is way better.\nfrom fastapi import APIRouter, FastAPI, Request, Response, Body\nfrom fastapi.routing import APIRoute\n\nfrom ty... | [
5,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"fastapi",
"http",
"middleware",
"python",
"starlette"
] | stackoverflow_0064115628_fastapi_http_middleware_python_starlette.txt |
Q:
I have a problem with the surface of my pygame script, I debug but can't find the answer
So, to start I was developing a game in pygame, and it worked very well until then, but when adding my animations for my characters, the script has an error, a surface problem; "TypeError: Source objects must be a surface".
I ... | I have a problem with the surface of my pygame script, I debug but can't find the answer | So, to start I was developing a game in pygame, and it worked very well until then, but when adding my animations for my characters, the script has an error, a surface problem; "TypeError: Source objects must be a surface".
I searched for several hours if someone already had my problem but without result...
I attach my... | [
"The problem is that self.image is used twice. First it is a pygame.Surface:\n\nself.image = self.get_image(0 ,0)\n\n\nThen it is a dictionary:\n\nself.image = {\n 'down' : self.get_image(0, 0),\n 'left': self.get_image(0, 32),\n 'right': self.get_image(0, 64),\n 'up': self.get_image(0, 96)\n}\n\n\nHowever,... | [
1
] | [] | [] | [
"pygame",
"pygame_surface",
"python"
] | stackoverflow_0074480212_pygame_pygame_surface_python.txt |
Q:
Mocking a HTTP server in Python
I'm writing a REST client and I need to mock a HTTP server in my tests. What would be the most appropriate library to do that? It would be great if I could create expected HTTP requests and compare them to actual.
A:
Try HTTPretty, a HTTP client mock library for Python helps you f... | Mocking a HTTP server in Python | I'm writing a REST client and I need to mock a HTTP server in my tests. What would be the most appropriate library to do that? It would be great if I could create expected HTTP requests and compare them to actual.
| [
"Try HTTPretty, a HTTP client mock library for Python helps you focus on the client side.\n",
"You can also create a small mock server on your own.\nI am using a small web server called Flask.\nimport flask\napp = flask.Flask(__name__)\n\ndef callback():\n return flask.jsonify(list())\n\napp.add_url_rule(\"use... | [
10,
8,
0,
0
] | [] | [] | [
"http",
"mocking",
"python",
"rest",
"unit_testing"
] | stackoverflow_0021877387_http_mocking_python_rest_unit_testing.txt |
Q:
sqlalchemy: rename a column on *query* level
I need to rename a column in a query, but I can't do it on column level, eg
session.query(MyModel.col_name.label('new_name'))
Is there any way to rename a column on the resulting query object?
Eg, something like
session.query(...).blah().blah().rename_column('old_name'... | sqlalchemy: rename a column on *query* level | I need to rename a column in a query, but I can't do it on column level, eg
session.query(MyModel.col_name.label('new_name'))
Is there any way to rename a column on the resulting query object?
Eg, something like
session.query(...).blah().blah().rename_column('old_name', 'new_name')
| [
"It doesn't look like there's any built in solution for that – but here's a workaround I've implemented which may help you:\nTo rename before the query has been executed:\n# Start off with your regular query – but as a subquery\nquery = session.query(MyModel.col_name.label('old_name')).subquery()\n\n# Now, perform ... | [
1,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0052718054_python_sqlalchemy.txt |
Q:
Tensorflow tensor loses dimension for some reason
I have a custom loss function that is reporting an error before any real processing happens.
I have a y_train of dimension (2717, 5, 5, 6) and a batch size of 25 with constants S1=S2=5. All I do is tf.reshape to make sure I get the desired dimension of (25,5,5,6), ... | Tensorflow tensor loses dimension for some reason | I have a custom loss function that is reporting an error before any real processing happens.
I have a y_train of dimension (2717, 5, 5, 6) and a batch size of 25 with constants S1=S2=5. All I do is tf.reshape to make sure I get the desired dimension of (25,5,5,6), then I want to extract one axis but its somehow not wor... | [
"It seems that the error is caused by the last batch of your y_train dataset, which has shape (17, 5, 5, 6) (17 * 5 * 5 * 1 = 425). This occurs because when tensorflow batches your data, the last batch contains all the remaining elements, number of whose does not have to be your specified batch_size (in your case 2... | [
1
] | [] | [] | [
"keras",
"loss_function",
"python",
"tensorflow"
] | stackoverflow_0074479259_keras_loss_function_python_tensorflow.txt |
Q:
How do you prevent SQLAlchemy from prefixing column names when using except_
I have a query like the following:
query = included_query.except_(excluded_query)
Both included_query and excluded_query query over a particular model called TestModel. However, when I create a subquery with that query (ie subquery = que... | How do you prevent SQLAlchemy from prefixing column names when using except_ | I have a query like the following:
query = included_query.except_(excluded_query)
Both included_query and excluded_query query over a particular model called TestModel. However, when I create a subquery with that query (ie subquery = query.subquery()), instead of having the direct columns of TestModel (eg subquery.c.i... | [
"I've figured out a way to do this:\ndef _except(included_query, excluded_query, Model, prefix):\n \"\"\"An SQLALchemy except_ that removes the prefixes on the columns, so they can be\n referenced in a subquery by their un-prefixed names.\"\"\"\n query = included_query.except_(excluded_query)\n subquery... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0073588253_python_sqlalchemy.txt |
Q:
Tox InterpreterNotFound Gitlab-CI Pipeline
I need some help with testing my python package using tox in a gitlab-ci pipeline:
I want to test my package on multiple versions. For this, I can write the following in my tox.ini:
[tox]
envlist = py{310, 311}
[testenv]
deps =
-rrequirements.txt
commands =
pytho... | Tox InterpreterNotFound Gitlab-CI Pipeline | I need some help with testing my python package using tox in a gitlab-ci pipeline:
I want to test my package on multiple versions. For this, I can write the following in my tox.ini:
[tox]
envlist = py{310, 311}
[testenv]
deps =
-rrequirements.txt
commands =
python -m pytest tests -s
Running the command tox wo... | [
"This is what I came up with for some of my projects:\n'.review':\n before_script:\n - 'python -m pip install tox'\n script:\n - 'export TOXENV=\"${CI_JOB_NAME##review}\"'\n - 'tox'\n\n'review py38':\n extends: '.review'\n image: 'python:3.8'\n\n'review py39':\n extends: '.review'\n image: 'python:3.... | [
1,
0
] | [] | [] | [
"gitlab_ci",
"python",
"tox"
] | stackoverflow_0074474552_gitlab_ci_python_tox.txt |
Q:
How do I capture the properties I want from a string?
I hope you are well I have the following string:
"{\"code\":0,\"description\":\"Done\",\"response\":{\"id\":\"8-717-2346\",\"idType\":\"CIP\",\"suscriptionId\":\"92118213\"},....\"childProducts\":[]}}"...
To which I'm trying to capture the attributes: id, idTy... | How do I capture the properties I want from a string? | I hope you are well I have the following string:
"{\"code\":0,\"description\":\"Done\",\"response\":{\"id\":\"8-717-2346\",\"idType\":\"CIP\",\"suscriptionId\":\"92118213\"},....\"childProducts\":[]}}"...
To which I'm trying to capture the attributes: id, idType and subscriptionId and map them as a dataframe, but the ... | [
"Considering your string is in JSON format, you can do this.\ndrop columns, transpose, and get headers right.\ntoEscape = \"{\\\"code\\\":0,\\\"description\\\":\\\"Done\\\",\\\"response\\\":{\\\"id\\\":\\\"8-717-2346\\\",\\\"idType\\\":\\\"CIP\\\",\\\"suscriptionId\\\":\\\"92118213\\\"}}\"\n\njson_string = toEscape... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074479810_dataframe_pandas_python.txt |
Q:
Error with cmap from a matplotlib defined list of colors in Folium - choropleth map
I'm triying to pass a customize list of colors to my choropleth map with geopandas.explore, but i get the error:
UnboundLocalError: local variable 'binning' referenced before assignment
if I specified a given list of colors ex: cma... | Error with cmap from a matplotlib defined list of colors in Folium - choropleth map | I'm triying to pass a customize list of colors to my choropleth map with geopandas.explore, but i get the error:
UnboundLocalError: local variable 'binning' referenced before assignment
if I specified a given list of colors ex: cmap= 'Blues', it displays with no problem
I copy the code below
import geopandas as gpd
imp... | [
"As noted this is a bug that I have patched and created a PR 2590\nThis will need to go through merge and release process. In interim you can download and use version of function from my patch which has been committed to GitHub\nimport geopandas as gpd\nimport matplotlib.colors\nimport folium\nimport numpy as np\n... | [
0,
0
] | [] | [] | [
"choropleth",
"folium",
"geopandas",
"matplotlib",
"python"
] | stackoverflow_0073979846_choropleth_folium_geopandas_matplotlib_python.txt |
Q:
Detect last zero-crossing
I'm generating an exponential sweep with the following function:
@jit(nopython=True)
def generate_exponential_sweep(time_in_seconds, sr):
time_in_samples = time_in_seconds * sr
exponential_sweep = np.zeros(time_in_samples, dtype=np.double)
for n in range(time_in_samples):
... | Detect last zero-crossing | I'm generating an exponential sweep with the following function:
@jit(nopython=True)
def generate_exponential_sweep(time_in_seconds, sr):
time_in_samples = time_in_seconds * sr
exponential_sweep = np.zeros(time_in_samples, dtype=np.double)
for n in range(time_in_samples):
t = n / sr
exponent... | [
"Since time_in_seconds, sr, starting_frequency and ending_frequency are all unknown, we can't guarantee that it will hit any zeroes or even cross it, without any giving them any constraints. The only way to properly do this is to use a window (or fade in/out), with a known frequency behaviour.\nThis rules out 1. We... | [
1
] | [] | [] | [
"acoustics",
"audio",
"python"
] | stackoverflow_0072650916_acoustics_audio_python.txt |
Q:
Network X remove edges and put it back
Hi is there a way to put the edges back after removing the edges from networkx?
The reason I remove it at first place is because I need to group the connected edges based on the attribute.
import networkx
# To create an empty undirected graph
G = networkx.Graph()
# To a... | Network X remove edges and put it back | Hi is there a way to put the edges back after removing the edges from networkx?
The reason I remove it at first place is because I need to group the connected edges based on the attribute.
import networkx
# To create an empty undirected graph
G = networkx.Graph()
# To add a node
G.add_node(1)
G.add_node(2)
G.add_... | [
"The easiest approach is probably to make a copy of G, and remove the edges from the copy so that you can always access the original graph G. For instance, consider the following:\nH = G.copy()\n\nfor v,w,d in G.edges(data=True):\n if d['color']=='e':\n H.remove_edge(v,w)\n\nfor c in nx.connected_compone... | [
0
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0074469075_networkx_python.txt |
Q:
How upload file with selenium
I trying to upload video file with selenium, it doesn't work
my code:
a = wait.until(EC.element_to_be_clickable((By.TAG_NAME, 'input'))) browser.execute_script("arguments[0].style.visibility = 'visible'", a) a.send_keys("C:/Users/NIKITA/Desktop/vk_clips/testvid.mp4")
This script work... | How upload file with selenium | I trying to upload video file with selenium, it doesn't work
my code:
a = wait.until(EC.element_to_be_clickable((By.TAG_NAME, 'input'))) browser.execute_script("arguments[0].style.visibility = 'visible'", a) a.send_keys("C:/Users/NIKITA/Desktop/vk_clips/testvid.mp4")
This script works but doesn't load the file and doe... | [
"The web element actually accepting the uploaded file is matching this XPath: \"//input[@type='file']\". This element is not visible. You can see yourself on picture you shared visibility: hidden.\nAgain, this is not an element you clicking when uploading file manually as a user via the GUI.\nSo, to upload file to ... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"webdriverwait",
"xpath"
] | stackoverflow_0074480471_python_selenium_selenium_webdriver_webdriverwait_xpath.txt |
Q:
How to write the division of two columns of a dataframe using asyncio?
def divis(data):
data['prom'] = data['total']/data['num2']
return data
async def divis(data):
data['prom'] = await (data['total']/data['num2'])
return data
await divis(df2)
TypeError: unhashable type: 'Series'
A:
Based on th... | How to write the division of two columns of a dataframe using asyncio? | def divis(data):
data['prom'] = data['total']/data['num2']
return data
async def divis(data):
data['prom'] = await (data['total']/data['num2'])
return data
await divis(df2)
TypeError: unhashable type: 'Series'
| [
"Based on the question fastest way to apply an async function to pandas dataframe and its accepted answer, this will look like:\nimport asyncio\n\nimport numpy as np\nimport pandas as pd\n\nasync def fun2(x, y):\n return x / y\n\nasync def divis(data):\n data['prom'] = await asyncio.gather(*(fun2(x, y) for x,... | [
0
] | [] | [] | [
"concurrency",
"python",
"python_asyncio"
] | stackoverflow_0074480252_concurrency_python_python_asyncio.txt |
Q:
How do I return a child class instance after running a super class method?
I have 2 python classes one subclasses the other
class A:
def __init__(some params):
do something()
def method(params):
return A_new_A_instance
class B(A)
def __init__(some params):
super().__init__(som... | How do I return a child class instance after running a super class method? | I have 2 python classes one subclasses the other
class A:
def __init__(some params):
do something()
def method(params):
return A_new_A_instance
class B(A)
def __init__(some params):
super().__init__(some params)
def new_method(params):
a_instance=super.method(params)
... | [
"As long as the constructor of both A and B are the same (they take the same parameters) you can use a factory function to create new instances of A and override it for B:\nclass A:\n def __init__(self, *params):\n pass\n\n def _create_new_instance(self, *params):\n return A(*params)\n\n def ... | [
1
] | [] | [] | [
"inheritance",
"oop",
"python",
"super"
] | stackoverflow_0074480394_inheritance_oop_python_super.txt |
Q:
Calculating a sum of characters converted to hex in python
Working in Python I need to calculate a checksum in a very specific way. The checksum is the lower byte of the sum of the hexadecimal representation of ASCII characters. Sounds confusing, here is the documentation with an example.
Here is my code in pytho... | Calculating a sum of characters converted to hex in python | Working in Python I need to calculate a checksum in a very specific way. The checksum is the lower byte of the sum of the hexadecimal representation of ASCII characters. Sounds confusing, here is the documentation with an example.
Here is my code in python.
chars = ['L', '3', '2', '0', '0']
checksum = hex(sum(int(hex(... | [
"\nint(hex(x), 16) converts a number to its hex representation, then back to an integer. You could just use x.\nOne byte is two hex digits. To get the lower byte of something, you just need to bitwise-and it with 0xff\n\nSo, your code would simply be written as:\nchecksum = sum(ord(c) for c in chars) & 0xff\n# or\n... | [
1
] | [] | [] | [
"hex",
"python"
] | stackoverflow_0074480483_hex_python.txt |
Q:
Drawing Directed Graph with Edge meta-data (with NetworkX in Python)
I have a directed multigraph that I want to represent as a (complete) directed graph with edge meta-data such that if there are e number of edges from node A to node B (in the original multigraph) then I save e as the meta-data for the edge (A,B)... | Drawing Directed Graph with Edge meta-data (with NetworkX in Python) | I have a directed multigraph that I want to represent as a (complete) directed graph with edge meta-data such that if there are e number of edges from node A to node B (in the original multigraph) then I save e as the meta-data for the edge (A,B) in the new (not-multi) directed graph.
I can construct the graph as follo... | [
"You should be able to do the following:\nedge_labels = nx.get_edge_attributes(G,'edge_count')\n\npos = nx.spring_layout(G)\nnx.draw(G, pos = pos, with_labels=True)\nnx.draw_networkx_edge_labels(G, pos=pos, edge_labels = edge_labels)\nplt.show()\n\n\nHere's an approach that uses curved arrows to avoid overlapping l... | [
1
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0074480392_networkx_python.txt |
Q:
How to read bangla dataframe json file with pandas
Here my code look like
import codecs
import pandas as pd
pd.read_json(codecs.open('/content/drive/MyDrive/content_colab_access/quotes_test.json', 'r', 'utf-8'))
print(data.shape)
data.head()
I have different quotes in quotes_test.json. Here some parts of datafram... | How to read bangla dataframe json file with pandas | Here my code look like
import codecs
import pandas as pd
pd.read_json(codecs.open('/content/drive/MyDrive/content_colab_access/quotes_test.json', 'r', 'utf-8'))
print(data.shape)
data.head()
I have different quotes in quotes_test.json. Here some parts of dataframe are,
[
{
"Quote": "যখন মানুষের খুব প্রিয় কে... | [
"The encoding is not of required type.\npd.read_json(codecs.open('/content/drive/MyDrive/content_colab_access/quotes_test.json', 'r', 'utf-8-sig'))\n\nI recommend module chardet to detect encoding.\n"
] | [
0
] | [] | [] | [
"dataframe",
"json",
"pandas",
"project",
"python"
] | stackoverflow_0074480440_dataframe_json_pandas_project_python.txt |
Q:
Unexpected calculation of number of trainable parameters (Pytorch)
Consider the following code
from torch import nn
from torchsummary import summary
from torchvision import models
model = models.efficientnet_b7(pretrained=True)
model.classifier[-1].out_features = 4 # because i have a 4-class problem; initially ... | Unexpected calculation of number of trainable parameters (Pytorch) | Consider the following code
from torch import nn
from torchsummary import summary
from torchvision import models
model = models.efficientnet_b7(pretrained=True)
model.classifier[-1].out_features = 4 # because i have a 4-class problem; initially the output is 1000 classes
model.classifier = nn.Sequential(*model.class... | [
"Resetting an attribute of an initialized layer does not necessarily re-initialize it with the newly-set attribute. What you need is model.classifier[-1] = nn.Linear(2560, 4).\n"
] | [
1
] | [] | [] | [
"conv_neural_network",
"pre_trained_model",
"python",
"pytorch",
"transfer_learning"
] | stackoverflow_0074479801_conv_neural_network_pre_trained_model_python_pytorch_transfer_learning.txt |
Q:
More efficient ways to self join a dataframe?
I'm trying to find the count of cars for the past 5 sales entries in a dataset.
My current approach using the code below is to:
Calculate the row number for each entry
Self join the dataframe to get the history for each dealership
Keep the 5 previous entries
Sum the s... | More efficient ways to self join a dataframe? | I'm trying to find the count of cars for the past 5 sales entries in a dataset.
My current approach using the code below is to:
Calculate the row number for each entry
Self join the dataframe to get the history for each dealership
Keep the 5 previous entries
Sum the sales for these 5
# Calculate row number for each s... | [
"From what it looks like, you are trying to find the sum of the car count for rolling past 5 days, for each dealer. So this would be a group by then rolling sum operation:\ndf = df.sort_values([\"dealership_id\", \"time\"], ascending=[True, True])\ndf['rolling_sum'] = df.groupby('dealership_id')['car_count'].rollin... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074479475_dataframe_pandas_python.txt |
Q:
How do I ignore keyword arguments when they are not used in the method?
I have a class with various functions that have default values for some keywords, but values can also be specified. However, the functions use different keywords.
This is a minimum reproducible example. The actual case has functions that are m... | How do I ignore keyword arguments when they are not used in the method? | I have a class with various functions that have default values for some keywords, but values can also be specified. However, the functions use different keywords.
This is a minimum reproducible example. The actual case has functions that are more complicated and inter-related.
Example Class:
class Things(object):
d... | [
"Use **kwargs for your inner functions as well, and then inside those functions check if the arguments exist.\nclass Things(object):\n def __init__(self, **kwargs):\n self.other = 999\n self.result = self.some_fcn(**kwargs)\n self.other2 = self.some_fcn2(**kwargs)\n\n def some_fcn(self, *... | [
0
] | [] | [] | [
"class",
"keyword_argument",
"methods",
"python"
] | stackoverflow_0074480565_class_keyword_argument_methods_python.txt |
Q:
I need to filter/copy/fetch only past 3 days data from 30-60 days data set
I've date variable "interview_start" which holds unique record start date. I just need to filter past 3 days including today's data into another or same dataframe. I've used below code which is working fine but not giving me today's data in... | I need to filter/copy/fetch only past 3 days data from 30-60 days data set | I've date variable "interview_start" which holds unique record start date. I just need to filter past 3 days including today's data into another or same dataframe. I've used below code which is working fine but not giving me today's data instead giving me past 3 days. I want to include today's data too.
from datetime i... | [
"Not the most practical approach, but you could loop through the rows in the dataframe, adding each row to a new dataframe, until the date is out of your date range.\nI'm going under the assumption you want today data + the three days before e.g. 17/11, 16/11, 15/11, 14/11\nfrom datetime import datetime, timedelta\... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074480529_pandas_python.txt |
Q:
What does the group_keys argument to pandas.groupby actually do?
In pandas.DataFrame.groupby, there is an argument group_keys, which I gather is supposed to do something relating to how group keys are included in the dataframe subsets. According to the documentation:
group_keys : boolean, default True
When calli... | What does the group_keys argument to pandas.groupby actually do? | In pandas.DataFrame.groupby, there is an argument group_keys, which I gather is supposed to do something relating to how group keys are included in the dataframe subsets. According to the documentation:
group_keys : boolean, default True
When calling apply, add group keys to index to identify pieces
However, I can'... | [
"group_keys parameter in groupby comes handy during apply operations that creates an additional index column corresponding to the grouped columns[group_keys=True] and eliminates in the case[group_keys=False] especially during the case when trying to perform operations on individual columns.\nOne such instance:\nIn ... | [
12,
6,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0038856583_pandas_python.txt |
Q:
Data Frame, panda
Trying to extract data from a single city in a dataset that contains data from different cities in the same column.
| City | Temp |
| -------- | -------- |
| New York | Warm |
| Boston | Cold |
I New York I Warm I
I Texas I Cold I
When i run my code it doesnt includ... | Data Frame, panda | Trying to extract data from a single city in a dataset that contains data from different cities in the same column.
| City | Temp |
| -------- | -------- |
| New York | Warm |
| Boston | Cold |
I New York I Warm I
I Texas I Cold I
When i run my code it doesnt include any data, just the he... | [
"df = pd.DataFrame(dict(a=[1,2,3,4,], b=[5,6,7,8], c=[1,2,3,4]))\nsub_df = df.query(f'a == 1').loc[:,['b','c']]\nsub_df\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074478923_dataframe_pandas_python.txt |
Q:
ModuleNotFoundError: No module named 'Crypto' Python Firebase
I know there are similar questions asked but I have read them and couldn't solved my problem I'm trying to import pyrebase; however it gives me these error messages:
Traceback (most recent call last):
File "c:\Users\yaman\OneDrive\Masaüstü\BİYOLOJİK Şİ... | ModuleNotFoundError: No module named 'Crypto' Python Firebase | I know there are similar questions asked but I have read them and couldn't solved my problem I'm trying to import pyrebase; however it gives me these error messages:
Traceback (most recent call last):
File "c:\Users\yaman\OneDrive\Masaüstü\BİYOLOJİK ŞİFRELEME\JustSth.py", line 1, in <module>
import pyrebase
Fil... | [
"Try :\nfrom Crypto.PubliCKey import *\n\nor:\nfrom Crypto import *\n\n",
"You installed the module in a different venv while you are in another. One way to resolve this is to copy and append the path of the installed module into your working env before you import it.\nNote: You can locate the path when you try t... | [
0,
0
] | [] | [] | [
"pycryptodome",
"python"
] | stackoverflow_0074479814_pycryptodome_python.txt |
Q:
How can I use a JSON file such as a database to store new and old objects?
I get the JSON objects from one of the sites and I want to attach these objects into a JSON file. the task is: I want to use JSON file as a database to save all information from the site I get objects from it so, the data I will show it bre... | How can I use a JSON file such as a database to store new and old objects? | I get the JSON objects from one of the sites and I want to attach these objects into a JSON file. the task is: I want to use JSON file as a database to save all information from the site I get objects from it so, the data I will show it breaking into 2 data which titled by the date like so:
first: will be new data tha... | [
"I suggest to use both read and write modes to fulfill this task.\nFirst you have to read the current content of the file by using the read state and then store them in a variable.\ntry:\nwith open('data.json') as json_file:\n json_data = json.load(json_file)\n\nNext, update the variable with the values you need... | [
1
] | [
"About File Handling:\nThere pysonDB. That`s DataBase based on JSON. Maybe it will help someone\nP.S: Version 2 is available - pysonDB-v2\n"
] | [
-1
] | [
"django",
"json",
"python",
"python_requests"
] | stackoverflow_0065288343_django_json_python_python_requests.txt |
Q:
python : aggregate dataframe values by bin
I have a dataset with that looks like that :
|col A|col B|
1 20
3 123
7 2
...
I would like to compute the mean value of col B over each bin of col A.
This would result in a new dataframe containing only one row per bin with :
| mid value of the ... | python : aggregate dataframe values by bin | I have a dataset with that looks like that :
|col A|col B|
1 20
3 123
7 2
...
I would like to compute the mean value of col B over each bin of col A.
This would result in a new dataframe containing only one row per bin with :
| mid value of the col A bin | avg value of col B over that bin |
| [
"As you haven't specified the number of bins and their properties, let me illustrate what you may do with pandas.cut to the example data you provided:\nimport pandas as pd\n\n# reproduce your example data\ndf = pd.DataFrame({'col A': [1, 3, 7],\n 'col B': [20, 123, 2]})\n\n# suggest only 2 bins wo... | [
1
] | [] | [] | [
"binning",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074479504_binning_dataframe_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.