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:
Why doesn't a python dict.update() return the object?
I 'm trying to do :
award_dict = {
"url" : "http://facebook.com",
"imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png",
"count" : 1,
}
def award(name, count, points, desc_string, my_size, parent) :
if my_size > count :... | Why doesn't a python dict.update() return the object? | I 'm trying to do :
award_dict = {
"url" : "http://facebook.com",
"imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png",
"count" : 1,
}
def award(name, count, points, desc_string, my_size, parent) :
if my_size > count :
a = {
"name" : name,
"desc... | [
"Python's mostly implementing a pragmatically tinged flavor of command-query separation: mutators return None (with pragmatically induced exceptions such as pop;-) so they can't possibly be confused with accessors (and in the same vein, assignment is not an expression, the statement-expression separation is there, ... | [
266,
43,
32,
24,
18,
6,
2,
2,
1,
1,
0
] | [] | [] | [
"dictionary",
"language_design",
"language_features",
"python"
] | stackoverflow_0001452995_dictionary_language_design_language_features_python.txt |
Q:
How to alter a variable via a dictionary?
How would you go about changing a variables value using a dictionary?
class Solution(object):
def __init__(self):
self.slot1 = ""
self.slot2 = ""
self.slot3 = ""
self.slot4 = ""
self.slot5 = ""
self.slotDictionary = {1: self.slot1, 2: self.slot2, ... | How to alter a variable via a dictionary? | How would you go about changing a variables value using a dictionary?
class Solution(object):
def __init__(self):
self.slot1 = ""
self.slot2 = ""
self.slot3 = ""
self.slot4 = ""
self.slot5 = ""
self.slotDictionary = {1: self.slot1, 2: self.slot2, 3: self.slot3, 4: self.slot4, 5: self.slot5}
... | [] | [] | [
"You can't change an immutable object (like str). You have initialized your attribute with an immutable object so, python will always create a new object in order to modify the value (the reference will be different between the one store in the attribut and the one store in your dictionary after modifying your attr... | [
-1,
-1,
-2
] | [
"python"
] | stackoverflow_0074130597_python.txt |
Q:
Unable to open .spydata in spyder: 'Object arrays cannot be loaded when allow_pickle=False'
I am having an issue when trying to import a .spydata file in Spyder. I created a .spydata file in a console using Spyder, then I opened a new console (same environment and everything) and tried to import the file.
Then Spy... | Unable to open .spydata in spyder: 'Object arrays cannot be loaded when allow_pickle=False' | I am having an issue when trying to import a .spydata file in Spyder. I created a .spydata file in a console using Spyder, then I opened a new console (same environment and everything) and tried to import the file.
Then Spyder throws an error:
'Unable to load .../.spydata'
The error message was:
'Object arrays cannot ... | [
"Found it!\nThe problem was a single numpy.ndarray\nIn my case, I just converted the numpy.ndarray into a list.\nNone of the other types of objects threw an error.\nThe .spydata file had basic Python structures, Pandas objects and even PuLP objects.\nIt is still an open issue for Spyder.\n"
] | [
2
] | [] | [] | [
"numpy",
"pandas",
"python",
"spyder"
] | stackoverflow_0074070493_numpy_pandas_python_spyder.txt |
Q:
How to save all occurences of a substring to an array in Python
I want to save each value between "(" and ")" from the string "obs1" to an array.
obs1 = "3341 - SSS - ELO CRED - (48,00)
4526 - SSS
7837 - SSS - MASTER DEB - (25,00)
2830 - SSS - VISA CRED - (35,00)"
I use the function
def find_between( s, first,... | How to save all occurences of a substring to an array in Python | I want to save each value between "(" and ")" from the string "obs1" to an array.
obs1 = "3341 - SSS - ELO CRED - (48,00)
4526 - SSS
7837 - SSS - MASTER DEB - (25,00)
2830 - SSS - VISA CRED - (35,00)"
I use the function
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )... | [
"You can use re.findall:\nimport re\n\nobs1 = \"\"\"3341 - SSS - ELO CRED - (48,00)\n\n4526 - SSS\n\n7837 - SSS - MASTER DEB - (25,00)\n\n2830 - SSS - VISA CRED - (35,00)\"\"\"\n\noutput = re.findall(r\"\\((.*?)\\)\", obs1)\nprint(output) # ['48,00', '25,00', '35,00']\n\n"
] | [
2
] | [] | [] | [
"arrays",
"between",
"loops",
"python",
"substring"
] | stackoverflow_0074130805_arrays_between_loops_python_substring.txt |
Q:
How to create a loop if contents of a list is in a variable?
I'm asking the user for a name, and if that name contains a number I want to print that they need to remove the numbers. But I can't exit the loop afterwards.
numbers=['1','2','3','4','5','6','7','8','9','0']
vad2=input("To what site are you goin... | How to create a loop if contents of a list is in a variable? | I'm asking the user for a name, and if that name contains a number I want to print that they need to remove the numbers. But I can't exit the loop afterwards.
numbers=['1','2','3','4','5','6','7','8','9','0']
vad2=input("To what site are you going to use the password? ")
for f in numbers:
if f in va... | [
"Break will jump over your 'for loop', not over your 'while loop'.\nModify your code like\nif not vad2.isalpha(): # if you want only alphabet from your input\n print()\n\n"
] | [
1
] | [] | [] | [
"if_statement",
"list",
"python",
"python_3.x"
] | stackoverflow_0074130814_if_statement_list_python_python_3.x.txt |
Q:
How to count how many maximum numbers there are among inputted in one line values?
I've got 4 integer inputs in one line separated by a space, and I have to output the largest of them and how many largest integers there are, also in one line and separated by a space. The first request can be easily done with a max... | How to count how many maximum numbers there are among inputted in one line values? | I've got 4 integer inputs in one line separated by a space, and I have to output the largest of them and how many largest integers there are, also in one line and separated by a space. The first request can be easily done with a max function, however I can't figure out how to do the second one. Example:
Input: 6 4 -3 6... | [
"Here is a way to do it:\nx = \"6 4 -3 6\"\nl = list(map(int, x.split()))\nprint(max(l), l.count(max(l)))\n\nWhere x is the string that you got from the call to input().\n"
] | [
1
] | [] | [] | [
"count",
"max",
"python"
] | stackoverflow_0074130823_count_max_python.txt |
Q:
Error installing geopandas:" A GDAL API version must be specified " in Anaconda
This error raised while installing geopandas. I've looking for its solution on the web, but none of them really explain what happened and how to solve it..
This is the full error:
Collecting geopandas
Using cached https://files.p... | Error installing geopandas:" A GDAL API version must be specified " in Anaconda | This error raised while installing geopandas. I've looking for its solution on the web, but none of them really explain what happened and how to solve it..
This is the full error:
Collecting geopandas
Using cached https://files.pythonhosted.org/packages/24/11/d77c157c16909bd77557d00798b05a5b6615ed60acb5900fbe6a65... | [
"pip install wheel\npip install pipwin\n\npipwin install numpy\npipwin install pandas\npipwin install shapely\npipwin install gdal\npipwin install fiona\npipwin install pyproj\npipwin install six\npipwin install rtree\npipwin install geopandas\n\nhere are the source links:\nhttp://geopandas.org/install.html#install... | [
162,
46,
27,
17,
10,
7,
7,
5,
4,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"anaconda",
"conda",
"geopandas",
"python"
] | stackoverflow_0054734667_anaconda_conda_geopandas_python.txt |
Q:
How to convert data and time to a number of days in python (pandas)
I have a column called "dateCreated" and it contains a date and time, and I want to convert it to a number of days.
This is my column
This is the data as a text: 2021-12-20T15:58:33.948Z
I tried this
train_data['dateCreated'] = (train_data['dateC... | How to convert data and time to a number of days in python (pandas) | I have a column called "dateCreated" and it contains a date and time, and I want to convert it to a number of days.
This is my column
This is the data as a text: 2021-12-20T15:58:33.948Z
I tried this
train_data['dateCreated'] = (train_data['dateCreated'] - date.today()).dt.days
| [
"first convert column type to datetime and add a column current date finally get number of days between this two date:\nfrom datetime import datetime\ndf['dateCreated']=pd.to_datetime(df['dateCreated'],format='%Y-%m-%dT%H:%M:%S:%fZ')\ndf['today']=pd.to_datetime(datetime.today())\ndf['days']=(df['today'] - df['dateC... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074130772_pandas_python.txt |
Q:
How to extract only this value ? bs4+requests+pandas
How to extract only this value ?
I have:
import requests
from bs4 import BeautifulSoup
from time import sleep
import pandas as pd
A:
This would be one way:
magic_number = soup.select_one('span:-soup-contains("people_alt")').next_sibling
BeautifulSoup document... | How to extract only this value ? bs4+requests+pandas |
How to extract only this value ?
I have:
import requests
from bs4 import BeautifulSoup
from time import sleep
import pandas as pd
| [
"This would be one way:\nmagic_number = soup.select_one('span:-soup-contains(\"people_alt\")').next_sibling\n\nBeautifulSoup documentation can be found here: https://beautiful-soup-4.readthedocs.io/en/latest/\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"parsing",
"python",
"web_scraping"
] | stackoverflow_0074130789_beautifulsoup_parsing_python_web_scraping.txt |
Q:
KeyError: 'skip_checks' on heroku run python manage.py migrate_schemas --shared
After deployment in Heroku a Django app, I run a command as follows:
heroku python manage.py migrate_schemas --shared
to create shared tables in DB, when using multitenancy (Django-tenant-schemas), and that migration throws this error... | KeyError: 'skip_checks' on heroku run python manage.py migrate_schemas --shared | After deployment in Heroku a Django app, I run a command as follows:
heroku python manage.py migrate_schemas --shared
to create shared tables in DB, when using multitenancy (Django-tenant-schemas), and that migration throws this error:
File "/app/.heroku/python/lib/python3.10/site-packages/tenant_schemas/migration_ex... | [
"I got the same error while updating to Django 4.1.1. After much effort, I found the following solution. You need to write a custom command to skip the checks:\nfrom django_tenants.management.commands.migrate_schemas import Command as BaseCommand\n\nclass Command(BaseCommand):\n help = (\n \"Updates datab... | [
3
] | [] | [] | [
"django",
"heroku",
"python"
] | stackoverflow_0073365190_django_heroku_python.txt |
Q:
How to dynamically extract numbers before text with regex?
I have a regex function that extracts the numbers before text. But I do it now with hard coded text.
But is it also possible to extract the numbers regardless of the text.
So I have this example string:
text = "[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoo... | How to dynamically extract numbers before text with regex? | I have a regex function that extracts the numbers before text. But I do it now with hard coded text.
But is it also possible to extract the numbers regardless of the text.
So I have this example string:
text = "[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. : 71201 Koopliedenweg 33\nDeb. nr. : 108636 ... | [
"One approach without regex. First, we cut the text by \\n, because all the numbers we need start on a new line. Then we discard those elements that do not start with a number. Next, we cut the remaining elements by spaces and get numbers.\ntext = \"[' \\n\\na)\\n\\n \\n\\nFactuur\\nVerdi Import Schoolfruit\\nFactu... | [
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074130034_python_regex.txt |
Q:
ModuleNotFoundError: No module named 'wikipedia'
I am trying to make a line of code, that searches Wikipedia for information. Here's my code:
import wikipedia
print(wikipedia.summary("Wikipedia"))
I have used the same module in the past, with no problem. Now here comes the error. When I run this SIMPLE 2 lines of... | ModuleNotFoundError: No module named 'wikipedia' | I am trying to make a line of code, that searches Wikipedia for information. Here's my code:
import wikipedia
print(wikipedia.summary("Wikipedia"))
I have used the same module in the past, with no problem. Now here comes the error. When I run this SIMPLE 2 lines of code, I get: Modulenotfounderror: No module named: "w... | [
"Alrighty, so the fix for my own question was that I needed to use the correct version of python. So I just installed a slightly older version of python (3.9) as I was using 3.10 currently, and then swapped the version of python I was using in vscode. Worked like a charm. If you're feeling lazy, you can also downlo... | [
0
] | [] | [] | [
"module",
"python",
"wikipedia_api"
] | stackoverflow_0070758605_module_python_wikipedia_api.txt |
Q:
The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() with if elif statement in python
I am facing issue in if else condition. In below code it check only first if condition remaining it skips. But as per my given scenario it should run 2nd elif condition. Not sure why it... | The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() with if elif statement in python | I am facing issue in if else condition. In below code it check only first if condition remaining it skips. But as per my given scenario it should run 2nd elif condition. Not sure why it is not checking 2nd elif statement.
In exception it throws """The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.it... | [
"Maybe try this:\n if len(df_src2)==0 or len(df_tgt2)==0:\n df_agg_diff = pd.DataFrame()\n return df_agg_diff\n\n elif len(df_src2)>0 and len(df_tgt2)>0:\n df_agg_merge = df_src2.merge(df_tgt2,\n indicator=True,\n how='... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074128761_python.txt |
Q:
How to filter dataset to not include data with pickup and dropoff times outside of range
I have a dataset of NYC taxi data that I am trying to filter through. The dataset has the schema like this:
root
|-- medallion: string (nullable = true)
|-- hack_license: string (nullable = true)
|-- vendor_id: string (nul... | How to filter dataset to not include data with pickup and dropoff times outside of range | I have a dataset of NYC taxi data that I am trying to filter through. The dataset has the schema like this:
root
|-- medallion: string (nullable = true)
|-- hack_license: string (nullable = true)
|-- vendor_id: string (nullable = true)
|-- rate_code: integer (nullable = true)
|-- store_and_fwd_flag: string (nulla... | [
"You can use native Spark functions. date_format when 'HH:mm:ss' format is provided will only extract the time.\nInput:\nfrom pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('2020-01-01 08:08:08', '2020-01-01 09:09:09'),\n ('2020-01-01 16:08:08', '2020-01-01 17:09:09'),\n ('2020-01-01 ... | [
1,
0
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"pyspark",
"python",
"timestamp"
] | stackoverflow_0074121693_apache_spark_apache_spark_sql_pyspark_python_timestamp.txt |
Q:
No matching distribution found for python3-requests
Taking a course: Using Python to Interact with the Operating System. I have very poor vision, so I am trying to install some python stuff on windows 10 (please see below) so I can edit and run some of the files at home.
How can I find and install the python3-requ... | No matching distribution found for python3-requests | Taking a course: Using Python to Interact with the Operating System. I have very poor vision, so I am trying to install some python stuff on windows 10 (please see below) so I can edit and run some of the files at home.
How can I find and install the python3-requests?
PS D:\ray\goapps\code4> C:\Users\raz\AppData\Local\... | [
"Just go into command line by typing cmd in the search bar and type in exactly pip install requests and that should work from there you can just use import requests at the top of your python file and use the library.\n"
] | [
0
] | [] | [] | [
"pip",
"python",
"python_3.x",
"windows",
"windows_10"
] | stackoverflow_0074130943_pip_python_python_3.x_windows_windows_10.txt |
Q:
getting empty data frames but there is no empty or NULL Values in my data
My data looks like this:
I have 648258 samples in total. The FROM_ID has 43 values, and TO_ID has 648258 values. I am finding the minimum value against each TO_ID.
Here is a sample code:
for i in range(1, len(df), 1):
A2C_TT= df_A2C.loc... | getting empty data frames but there is no empty or NULL Values in my data | My data looks like this:
I have 648258 samples in total. The FROM_ID has 43 values, and TO_ID has 648258 values. I am finding the minimum value against each TO_ID.
Here is a sample code:
for i in range(1, len(df), 1):
A2C_TT= df_A2C.loc[(df_A2C['TO_ID'] == i)].sort_values('DURATION_H').head(1)
print (A2C_TT)
... | [
"groupby to_id, take the minimum of Duration_h\ndf.groupby('TO_ID')['DURATION_H'].min()\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074130926_dataframe_jupyter_notebook_pandas_python_python_3.x.txt |
Q:
I have a text file with key values separated with comma. I want to use those key values to extract a complete row of each key in another .csv file
I want to use the key values basically person ID's present in file1.txt to extract a complete row of information for each of those values in file2.csv and store it in f... | I have a text file with key values separated with comma. I want to use those key values to extract a complete row of each key in another .csv file | I want to use the key values basically person ID's present in file1.txt to extract a complete row of information for each of those values in file2.csv and store it in file3.csv with rows indicating the ID's and columns indicating the information like age, height, weight etc.
I tried the following and it gives an error:... | [
"Let me try to understand:\n .txt has only 1 ID column\n csv2 has more columns , but not ID column\n You want to merge them into a csv3\n\nAs you describe .txt, it seems it desn't have any info in common, so the only way this can be able is if that txt follows the same order as your .csv rows, in that case, index m... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074130596_pandas_python.txt |
Q:
Compute average on pandas dataframe with based on another column criteria
I have the following dataframe:
CodigoCliente
Ene-2021
Feb-2021
Mar-2021
Abr-2021
May-2021
Jun-2021
Jul-2021
Ago-2021
Sep-2021
Oct-2021
Nov-2021
Diciembre-2021
Ceros
Promedio
GM
LM
IC
PromP
Cliente1
166
155
166
172
153
162
127
141
158
163
... | Compute average on pandas dataframe with based on another column criteria | I have the following dataframe:
CodigoCliente
Ene-2021
Feb-2021
Mar-2021
Abr-2021
May-2021
Jun-2021
Jul-2021
Ago-2021
Sep-2021
Oct-2021
Nov-2021
Diciembre-2021
Ceros
Promedio
GM
LM
IC
PromP
Cliente1
166
155
166
172
153
162
127
141
158
163
148
147
0
154.83
7
5
G
Cliente2
180
147
139
133
138
145
136
149
131
13... | [
"Use apply!\nWrite your function and apply your function. You might need lambda for that.\nLook here:\nhttps://www.statology.org/pandas-apply-lambda/\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074130912_dataframe_pandas_python.txt |
Q:
Discord Pypresence crashing custom application after pressing connect button
This is how the application looks like: [1]: https://i.stack.imgur.com/HUaix.png
[2]: https://i.stack.imgur.com/CYWdS.png
The second [2] image shows how the application should look after pressing the "Connect" button. However, after press... | Discord Pypresence crashing custom application after pressing connect button | This is how the application looks like: [1]: https://i.stack.imgur.com/HUaix.png
[2]: https://i.stack.imgur.com/CYWdS.png
The second [2] image shows how the application should look after pressing the "Connect" button. However, after pressing the button it looks the same (image [1]), although the Discord rich presence s... | [
"Try running your RPC code in a separate thread\nfrom threading import Thread\n\n\ndef _rpc_connect(client_id): # this will be your 'target' function, run in its own thread\n start = int(time.time())\n RPC = Presence(client_id)\n RPC.connect()\n\n while True:\n RPC.update(\n details =... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074130877_discord_discord.py_python_tkinter_user_interface.txt |
Q:
How to add another iterator to nested loop in python without additional loop?
I am trying to add a date to my nested loop without creating another loop.
End is my list of dates and end(len) is equal to len(year).
Alternatively I can add the date to the dataframe (data1) is that a better solution?
Data-Sample
state... | How to add another iterator to nested loop in python without additional loop? | I am trying to add a date to my nested loop without creating another loop.
End is my list of dates and end(len) is equal to len(year).
Alternatively I can add the date to the dataframe (data1) is that a better solution?
Data-Sample
state_list = ['A','B','C','D','E'] #possible states
data1 = pd.DataFrame({"cust_id": ['... | [
"If I understand correctly, the question boils down to this:\nThere is an\n\narray of values, e.g.\n\nvals = np.array([5500., 5600., 5700., 5800., 5900.]) # == res[-1] from the example\n\n\na constant loan rate, e.g.\n\nloan_rate = 0.12 # ... to continue with the example above\n\n\nand the goal is to perform a ca... | [
2
] | [] | [] | [
"loops",
"matrix_multiplication",
"numpy",
"pandas",
"python"
] | stackoverflow_0074039189_loops_matrix_multiplication_numpy_pandas_python.txt |
Q:
Find string in a dataframe from a list in another dataframe
I have 2 pandas dataframes in python which are set up as folows:
Dataframe 1:
ID Paragraph
1 'A B C D E'
2 'A F G H L'
3 'B J P Q W'
4 'G F D S A'
Where Paragraph is a string of multiple words.
Dataframe 2:
ID Name W... | Find string in a dataframe from a list in another dataframe | I have 2 pandas dataframes in python which are set up as folows:
Dataframe 1:
ID Paragraph
1 'A B C D E'
2 'A F G H L'
3 'B J P Q W'
4 'G F D S A'
Where Paragraph is a string of multiple words.
Dataframe 2:
ID Name Words
1 First ['A', 'F']
2 Second ['B', 'Z']
3 ... | [
"You can split and explode Paragraph. Then map the names for each word of the exploded df_2. Finally, aggregate as set to have unique values:\ns = df_2.explode('Words').set_index('Words')['Name']\ndf_1['Names'] = (df_1['Paragraph'].str.split()\n .explode().map(s).dropna()\n .groupby(... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074130476_dataframe_pandas_python.txt |
Q:
Setting ReLU inplace to 'False'
Below I have written code which accepts a pretrained model as argument (vgg, resnet, densenet etc) and returns the model with ReLU state as 'False'. It is written after testing many different specific architectures.
I would like to re-write it in a more compact way as this does not ... | Setting ReLU inplace to 'False' | Below I have written code which accepts a pretrained model as argument (vgg, resnet, densenet etc) and returns the model with ReLU state as 'False'. It is written after testing many different specific architectures.
I would like to re-write it in a more compact way as this does not seem optimal to me. However, I am not... | [
"This calls for a recursive solution.\ndef ReLU_inplace_to_False(module):\n for layer in module._modules.values():\n if isinstance(layer, nn.ReLU):\n layer.inplace = False\n ReLU_inplace_to_False(layer)\n\n"
] | [
1
] | [] | [] | [
"deep_learning",
"pre_trained_model",
"python",
"relu",
"transfer_learning"
] | stackoverflow_0074124725_deep_learning_pre_trained_model_python_relu_transfer_learning.txt |
Q:
How to check if a key exists in a word2vec trained model or not
I have trained a word2vec model using a corpus of documents with Gensim. Once the model is training, I am writing the following piece of code to get the raw feature vector of a word say "view".
myModel["view"]
However, I get a KeyError for the word w... | How to check if a key exists in a word2vec trained model or not | I have trained a word2vec model using a corpus of documents with Gensim. Once the model is training, I am writing the following piece of code to get the raw feature vector of a word say "view".
myModel["view"]
However, I get a KeyError for the word which is probably because this doesn't exist as a key in the list of k... | [
"Word2Vec also provides a 'vocab' member, which you can access directly.\nUsing a pythonistic approach:\nif word in w2v_model.vocab:\n # Do something\n\nEDIT Since gensim release 2.0, the API for Word2Vec changed. To access the vocabulary you should now use this:\nif word in w2v_model.wv.vocab:\n # Do somethi... | [
45,
35,
10,
1,
1,
0,
0,
0
] | [] | [] | [
"gensim",
"python",
"word2vec"
] | stackoverflow_0030301922_gensim_python_word2vec.txt |
Q:
Converting all elements in a 2D array to uppercase in python
I have a 2D array that looks a bit like this:
array =[['a', 'b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i', 'k', 'l']]
Is there a way of converting all elements of the array into capitals? The only methods I could fine only worked on 1D array or 2D arrays w... | Converting all elements in a 2D array to uppercase in python | I have a 2D array that looks a bit like this:
array =[['a', 'b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i', 'k', 'l']]
Is there a way of converting all elements of the array into capitals? The only methods I could fine only worked on 1D array or 2D arrays when the sub arrays are the same size.
| [
"Could this be what you need, quite simple list comprehension:\n[[item.upper() for item in sub] for sub in array]\n\n",
"You can use .join() and .split():\narray = [['a', 'b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i', 'k', 'l']]\n# 1. join letters with ' '. 2. UP them. 3. split them with ' '\nnew_array = [' '.join(a... | [
9,
3,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"arrays",
"multidimensional_array",
"python"
] | stackoverflow_0046075628_arrays_multidimensional_array_python.txt |
Q:
Drawing using matplotlib in pysimplegui
How can i clean up previous drawing before drawing again with matplotlib in PySimpleGui?
I wanted to draw a bar chart which i could be able to draw but not able to delete using the following code:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import ... | Drawing using matplotlib in pysimplegui | How can i clean up previous drawing before drawing again with matplotlib in PySimpleGui?
I wanted to draw a bar chart which i could be able to draw but not able to delete using the following code:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import PySimpleGUI as sg
im... | [
"I put your code into OpenAI's Codex, and this is what I got back:\nCode\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport PySimpleGUI as sg\nimport random\n\nlayout=[[sg.B('Draw'),sg.B('Delete')],[sg.Canvas(key='canvas1')]]\n\nwindow=sg.Window(\"Test\", layou... | [
0
] | [] | [] | [
"matplotlib",
"pysimplegui",
"python"
] | stackoverflow_0074129641_matplotlib_pysimplegui_python.txt |
Q:
How to get a sequence string per row from 2 columns in PySpark?
I have the following data structure:
The columns "s" and "d" are indicating the transition of the object in column "x". What I want to do is get a transition string per object present in column "x". E.g. with a "new" column as follows:
Is there a go... | How to get a sequence string per row from 2 columns in PySpark? | I have the following data structure:
The columns "s" and "d" are indicating the transition of the object in column "x". What I want to do is get a transition string per object present in column "x". E.g. with a "new" column as follows:
Is there a good way to do it using PySpark?
I tried the following PySpark code usi... | [
"If real values in columns \"s\" and \"d\" go in ascending order, then, using window partitions, you can:\n\nextract the first value from column \"s\"\nextract all the values from column \"d\"\narray_union all the extracted values\narray_sort and array_join into a string\n\nw = W.partitionBy('x')\narr = F.array_uni... | [
1,
0
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"pyspark",
"python",
"user_defined_functions"
] | stackoverflow_0074122314_apache_spark_apache_spark_sql_pyspark_python_user_defined_functions.txt |
Q:
after pip successful installed: ModuleNotFoundError
I am trying to install the SimPy module so that I can use it in IDLE. However, everytime I try to import in IDLE, I got an error. I already tried reinstalling Python and Pip and tried to modify the location of the apps. SimPy can be found in the directory of Pyth... | after pip successful installed: ModuleNotFoundError | I am trying to install the SimPy module so that I can use it in IDLE. However, everytime I try to import in IDLE, I got an error. I already tried reinstalling Python and Pip and tried to modify the location of the apps. SimPy can be found in the directory of Python 2.7. I'm using python 3.6.1.
After I correctly instal... | [
"Since you are using python 3.6.1, you may need to specify the type of python you want to install simpy for. Try running pip3 install simpy to install the simpy module to your python3 library.\n",
"Wherever you're running your code, try this\nimport sys\n\nsys.path\nsys.executable\n\nIt might be possible that you... | [
13,
11,
3,
2,
2,
0,
0,
0
] | [] | [] | [
"module",
"pip",
"python",
"python_idle"
] | stackoverflow_0044528638_module_pip_python_python_idle.txt |
Q:
How to extract NFORC data in usable form
I'm able to access the NFORC data in the abaqus output file correctly from abaqus output database but I'm not sure how to format the data so that it's usable since the bulkDataBlocks data is somewhat opaque.
The data is apparently in an array and the following code outputs ... | How to extract NFORC data in usable form | I'm able to access the NFORC data in the abaqus output file correctly from abaqus output database but I'm not sure how to format the data so that it's usable since the bulkDataBlocks data is somewhat opaque.
The data is apparently in an array and the following code outputs the correct nodal forces for the elements with... | [
"Usually, the bulkDataBlocks outputs the data in the M x N shape. M is number of components and N is the number of data points. \nHere, M is 1, hence the shape of the array is 1 x N. Now, we can convert 1 x N shape array into N shape array as below,\nimport numpy\n# bulk data blocks array for 1 component (or scala... | [
1,
0
] | [] | [] | [
"abaqus",
"python"
] | stackoverflow_0074118431_abaqus_python.txt |
Q:
dataframe: create DataFrame using two different dictionaries
I have two different functions which has two different dictionaries. First, I have to merge to dictionaries into one and then connect two dataframe.
import pandas as pd
output_df1 = {}
output_df1['diff_sum'] = 108
output_df1['cumsum'] = 232
out2 = {}
out... | dataframe: create DataFrame using two different dictionaries | I have two different functions which has two different dictionaries. First, I have to merge to dictionaries into one and then connect two dataframe.
import pandas as pd
output_df1 = {}
output_df1['diff_sum'] = 108
output_df1['cumsum'] = 232
out2 = {}
out2['carving'] = 1299
out2['bearing'] = 255
merge_dict = {**output_d... | [
"Try:\nnew_df = pd.DataFrame(merge_dict.values(), index=merge_dict, columns=[\"tata\"])\nprint(new_df)\n\nPrints:\n tata\ndiff_sum 108\ncumsum 232\ncarving 1299\nbearing 255\n\n",
"You can also just convert the merge_dict to dataframe directly by setting the index name to 'tata' and then trans... | [
2,
2,
0
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python"
] | stackoverflow_0074131028_dataframe_dictionary_pandas_python.txt |
Q:
python requests get aspx issue
Please look over my code. What am I doing wrong that my request response is empty? Any pointers?
URL in question: (should generate a results page)
https://www.ucr.gov/enforcement/343121222
But I cannot replicate it with python requests. Why?
import requests
headers = {'Host': 'www.uc... | python requests get aspx issue | Please look over my code. What am I doing wrong that my request response is empty? Any pointers?
URL in question: (should generate a results page)
https://www.ucr.gov/enforcement/343121222
But I cannot replicate it with python requests. Why?
import requests
headers = {'Host': 'www.ucr.gov',
'User-Agent' : '... | [
"The page at the link you provided is fully rendered on the client side using JavaScript. This means that you won't be able to obtain the same response using a simple HTTP request.\nIn this case a common solution is performing something that is called Headless Scraping, which involves automating a headless browser ... | [
0
] | [] | [] | [
"python",
"python_requests"
] | stackoverflow_0074131181_python_python_requests.txt |
Q:
Office 365 IMAP authentication via OAuth2 and python MSAL library
I'm trying to upgrade a legacy mail bot to authenticate via Oauth2 instead of Basic authentication, as it's now deprecated two days from now.
The document states applications can retain their original logic, while swapping out only the authenticatio... | Office 365 IMAP authentication via OAuth2 and python MSAL library | I'm trying to upgrade a legacy mail bot to authenticate via Oauth2 instead of Basic authentication, as it's now deprecated two days from now.
The document states applications can retain their original logic, while swapping out only the authentication bit
Application developers who have built apps that send, read, or
o... | [
"Try the below steps.\nFor Client Credentials Flow you need to assign “Application permissions” in the app registration, instead of “Delegated permissions”.\n\nAdd permission “Office 365 Exchange Online / IMAP.AccessAsApp” (application).\n\nGrant admin consent to you application\nService Principals and Exchange.\nO... | [
5,
1,
0
] | [] | [] | [
"email",
"imap",
"oauth_2.0",
"office365",
"python"
] | stackoverflow_0073902642_email_imap_oauth_2.0_office365_python.txt |
Q:
Discord bot that gives role to the user I react on part2
I've been working on my discord bot to make it give verified roles to members that I checkmark react to them, I've been running into issue lately and I hope someone can fix it
I'm trying to make the bot give "Temporary" role when I use ❎ but I keep getting t... | Discord bot that gives role to the user I react on part2 | I've been working on my discord bot to make it give verified roles to members that I checkmark react to them, I've been running into issue lately and I hope someone can fix it
I'm trying to make the bot give "Temporary" role when I use ❎ but I keep getting this message
UnboundLocalError: local variable 'role' reference... | [
"role is only declared inside of an if-statement, so if that if-statement is not entered then the variable role doesn't exist. Your error suggests that this is the case, as it is \"referenced before assignment\".\n if payload.emoji.id == '1032324082110304288':\n role = discord.utils.get(guild.roles... | [
2
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074129414_discord.py_python.txt |
Q:
How to count the number of keys where the values meet a criteria in a list of dictionaries?
I have a list of dictionaries (see below), and I would count the number of keys, whose values meet a specfic criteria. In this instance, I want to know the number of 'duration' keys, whose values are greater than 500.
{'tes... | How to count the number of keys where the values meet a criteria in a list of dictionaries? | I have a list of dictionaries (see below), and I would count the number of keys, whose values meet a specfic criteria. In this instance, I want to know the number of 'duration' keys, whose values are greater than 500.
{'test': [{'duration': 0,
'is_correct': True},
{'duration': 518,
'is_correct': False},
{'dur... | [
"Simple list comprehension would do:\nd = {'test': [{'duration': 0,\n 'is_correct': True},\n {'duration': 518,\n 'is_correct': False},\n {'duration': 500,\n 'is_correct': False},\n {'duration': 285,\n 'is_correct': True},\n {'duration': 300,\n 'is_correct': True}]}\nlen([i for i in d['test'] if i['dur... | [
2
] | [] | [] | [
"count",
"dictionary",
"key_value",
"python"
] | stackoverflow_0074131188_count_dictionary_key_value_python.txt |
Q:
Python packages on Rosetta M1 Macbook
I am trying to run a script from a repo which was using python 3.7 and other packages version that were not supported in M1.
I install a separate conda through open terminal under Rosetta, i can install those specific packages i need. but when i try to run some sample scripts ... | Python packages on Rosetta M1 Macbook | I am trying to run a script from a repo which was using python 3.7 and other packages version that were not supported in M1.
I install a separate conda through open terminal under Rosetta, i can install those specific packages i need. but when i try to run some sample scripts (repo comes with some pytest example) i alw... | [
"I don't know if it's solvable, but I think I'm running into the same issue.\nFor reasons (ortools package not supporting M1) I need to run Python under Rosetta 2, the following used to work, but now segfaults:\n# Install Homebrew with Rosetta 2 / Intel \narch -x86_64 /bin/bash -c \"$(curl -fsSL https://raw.githubu... | [
0
] | [] | [] | [
"apple_m1",
"apple_silicon",
"python",
"rosetta_2"
] | stackoverflow_0074089846_apple_m1_apple_silicon_python_rosetta_2.txt |
Q:
Extract and create a new email column dataframe pyspark
I have a df with a column with emails and more information that I don't want. Here are some examples:
Email_Col
"Snow, John" <john.snow@stackoverflow.com>, "Stark, Arya" <starkarya@got.com>
"YourBoss" <yourbosss1@yourcur... | Extract and create a new email column dataframe pyspark | I have a df with a column with emails and more information that I don't want. Here are some examples:
Email_Col
"Snow, John" <john.snow@stackoverflow.com>, "Stark, Arya" <starkarya@got.com>
"YourBoss" <yourbosss1@yourcurrentcompany.net>
"test1 <emailtest@tester.com>", "test2 <emai... | [
"Please refrain from udf - they are slow and nowadays not needed in the vast majority of cases. The following does the trick:\nF.expr(\"regexp_extract_all(Email_Col, '(?<=<).*?(?=>)', 0)\")\n\nregexp_extract_all is available from Spark 3.1+\nFull example:\nfrom pyspark.sql import functions as F\ndf = spark.createDa... | [
1
] | [] | [] | [
"apache_spark",
"dataframe",
"pyspark",
"python",
"regex"
] | stackoverflow_0074130634_apache_spark_dataframe_pyspark_python_regex.txt |
Q:
Discord.py - how do I make a command to check my bot's permissions?
How do I make a command to show what permissions my bot has in a server?
So for example, i do the command "-getperms"
Then it brings up:
✅ Manage Roles
✅ Manage Messages
✅ Manage Server
etc.
A:
Your permissions are accessible through Member.guil... | Discord.py - how do I make a command to check my bot's permissions? | How do I make a command to show what permissions my bot has in a server?
So for example, i do the command "-getperms"
Then it brings up:
✅ Manage Roles
✅ Manage Messages
✅ Manage Server
etc.
| [
"Your permissions are accessible through Member.guild_permissions.\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python",
"python_3.x"
] | stackoverflow_0074129159_discord_discord.py_python_python_3.x.txt |
Q:
I created a channel with "guild.create_text_channel" but I couldn't find how to send a message to the channel I created
I created a channel with "guild.create_text_channel" but I couldn't find how to send a message to the channel I created. I'm using discord.py
async def on_raw_reaction_add(payload):
messageID... | I created a channel with "guild.create_text_channel" but I couldn't find how to send a message to the channel I created | I created a channel with "guild.create_text_channel" but I couldn't find how to send a message to the channel I created. I'm using discord.py
async def on_raw_reaction_add(payload):
messageID = <myMessageID>
channell = bot.get_channel(payload.channel_id)
message = await channell.fetch_message(payload.messag... | [
"You can send a message in a channel using TextChannel.send.\nPS. Guild.create_text_channel is a coroutine so you should await it.\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074128354_discord_discord.py_python.txt |
Q:
xlwings Reports Quickstart throws errors
Just trying the quickstart described here:
https://docs.xlwings.org/en/stable/reports.html#quickstart
I've copied the small code sample and created the template sheet as described. When I run report.py, I get the following:
Traceback (most recent call last):
File "report.... | xlwings Reports Quickstart throws errors | Just trying the quickstart described here:
https://docs.xlwings.org/en/stable/reports.html#quickstart
I've copied the small code sample and created the template sheet as described. When I run report.py, I get the following:
Traceback (most recent call last):
File "report.py", line 17, in <module>
book = app.rende... | [
"Traditionally, xlwings only worked on Windows or macOS with an actual installation of Microsoft Excel. More recently (in 2022) it added Linux support for xlwings Server and xlwings File Reader, but xlwings Reports still has to be run in connection with Excel, i.e., runs on Windows and macOS only. While the install... | [
0
] | [] | [] | [
"python",
"xlwings"
] | stackoverflow_0074129031_python_xlwings.txt |
Q:
Key Error: 'Secret_Key' cant run server in django
Hello i just downloaded an open source Django CRM. Im using VSCode.
Installed all the requirements in the dir and inside the venv.
When I try to run the server there is a KeyError.
These are the final lines that the error comes with:
File "C:\Users....\Django-CRM-m... | Key Error: 'Secret_Key' cant run server in django | Hello i just downloaded an open source Django CRM. Im using VSCode.
Installed all the requirements in the dir and inside the venv.
When I try to run the server there is a KeyError.
These are the final lines that the error comes with:
File "C:\Users....\Django-CRM-master\crm\settings.py", line 12, in
SECRET_KEY = os.en... | [
"The error is telling you that the environment variable doesn't exist on your system by saying that the key \"SECRET_KEY\" is not in the os.environ dictionary-like object which represents all your environment variables.\nYou'll need to generate a long enough random string, then either set a SECRET_KEY environment v... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074131191_django_python.txt |
Q:
Python csv writer always skips last 15-30 lines
I have a csv file, in every line I have a random amount of integers (atleast 1) which could possibly be all 0, separated by a comma.
But the last 15-30 (different everytime I run it, data is always same length) lines are not saved. I even added a counter to check how... | Python csv writer always skips last 15-30 lines | I have a csv file, in every line I have a random amount of integers (atleast 1) which could possibly be all 0, separated by a comma.
But the last 15-30 (different everytime I run it, data is always same length) lines are not saved. I even added a counter to check how far the loop goes and the counter reaches the correc... | [
"Your application is probably dying an horrible death, due to the way it is launched, instead of shutting down normally.\nThat prevents Python from flushing the files contents.\nJust open the file using a context-manager block (the \"with\" command) to prevent this from happening:\nwith open(\"one_hot_encoded.csv\"... | [
2
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074131355_csv_python.txt |
Q:
Refactoring Python's code - with variables
Hi I'm learning Python by myself and I'm tying to refactor this code. I want to use declaration and invoke of the function.
So the original code is:
num1 = int(input("Enter a number: "))
num1 = num1**2
num1 = num1 - 5
num1 = num1 / 3
num2 = int(input("Enter another number... | Refactoring Python's code - with variables | Hi I'm learning Python by myself and I'm tying to refactor this code. I want to use declaration and invoke of the function.
So the original code is:
num1 = int(input("Enter a number: "))
num1 = num1**2
num1 = num1 - 5
num1 = num1 / 3
num2 = int(input("Enter another number: "))
num2 = num2**2
num2 = num2 - 5
num2 = num2... | [
"here is a way to make everything cleaner:\nimport math\ndef get_value(input_string): # reusable code should be functionized\n num1 = int(input(input_string)) # get user input with the various strings you would like to output\n return ((num1**2) - 5) / 3 # do all of the same math once, since these are basic f... | [
1,
0,
0
] | [] | [] | [
"function",
"invoke",
"python",
"python_3.x",
"refactoring"
] | stackoverflow_0074131377_function_invoke_python_python_3.x_refactoring.txt |
Q:
How to make separate Keras model with dependent weights?
I have to create a network with keras like in the picture below, where NN - individual neural networks.
The problem is, that they all must have same weights
I can't use shared layers (at least to my understanding), because then one network will get all the ... | How to make separate Keras model with dependent weights? | I have to create a network with keras like in the picture below, where NN - individual neural networks.
The problem is, that they all must have same weights
I can't use shared layers (at least to my understanding), because then one network will get all the inputs in it and I need each to get specially one
Is there any... | [
"Use the functional api. You can reuse a layer for different inputs. For example:\ninp1 = Input(...)\ninp2 = Input(...)\nlayer1 = Dense(...)\na1 = layer1(inp1)\na2 = layer1(inp2)\n\nlayer1 will be applied on inp1 and on inp2. It is just one layer instance, the same weights will be used for inp1 and inp2.\n"
] | [
1
] | [] | [] | [
"keras",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0074131086_keras_neural_network_python_tensorflow.txt |
Q:
How to add a new subplot to a figure created by pandas?
I'm creating a plot from pandas dataframe using pandas.DataFrame.plot(), which creates 3x2 subplots. I want to add a new subplot to the final spot. However, it doesn't appear. What could be the solution?
ax = DF.plot(x = 'time',
y = ['A', 'B', 'C', ... | How to add a new subplot to a figure created by pandas? | I'm creating a plot from pandas dataframe using pandas.DataFrame.plot(), which creates 3x2 subplots. I want to add a new subplot to the final spot. However, it doesn't appear. What could be the solution?
ax = DF.plot(x = 'time',
y = ['A', 'B', 'C', 'D', 'E'],
kind = 'line',
subplots ='True'... | [
"Unhide the last subplot using set_visible:\nDF.plot(x = 'A', \n y = 'B', \n kind = 'line',\n ax = ax[2, 1])\nax[2, 1].set_visible(True)\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074131365_matplotlib_pandas_python.txt |
Q:
Extracting data from table using Beautiful Soup where tags have both and tags
There are some tables I am trying to get data from. I have been able to do this before when the tags have only tags, however in this specific table they are mixed on several rows:
Picture of HTML Element
I was able to extract and ... | Extracting data from table using Beautiful Soup where tags have both and tags | There are some tables I am trying to get data from. I have been able to do this before when the tags have only tags, however in this specific table they are mixed on several rows:
Picture of HTML Element
I was able to extract and tags separately using below, but then it's difficult to put the data back together.
ur... | [
"read_html returns a list of dataframes index 5 is the table you want.\nimport pandas as pd\n\n\nurl = \"https://www.pge.com/pipeline/operations/cgt_pipeline_status.page#flows\"\ndf = pd.read_html(url)[5].rename(columns={\"Unnamed: 0\": \"\"}).set_index(\"\")\n\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"html",
"pandas",
"python"
] | stackoverflow_0074131310_beautifulsoup_html_pandas_python.txt |
Q:
Calling py-script function from button-click with "pys-onClick=..." doesn't work?
I'm relatively new to PyScript and would like to run a function when a button is clicked.
However, no matter what code I try, it doesn't seem to work. The button is clickable but doesn't appear to do anything.
When I call the functio... | Calling py-script function from button-click with "pys-onClick=..." doesn't work? | I'm relatively new to PyScript and would like to run a function when a button is clicked.
However, no matter what code I try, it doesn't seem to work. The button is clickable but doesn't appear to do anything.
When I call the function manually (inside the py-script tag) it works fine.
Am I missing something?
Here's my ... | [
"As it develops, some things in PyScript are moving targets. A couple of things about your code. First pys-onClick has been deprecated in favor of py-onClick in the more recent releases (including 'latest', which you use here). Second, to call the function from the button element, the syntax should currently read p... | [
1
] | [] | [] | [
"button",
"javascript",
"pyscript",
"python"
] | stackoverflow_0074005057_button_javascript_pyscript_python.txt |
Q:
How to sum all "bid" and find MAX "bid" in nesting dictionary in a List?
s = [
{"name": "Jordan",
"bid": 100
},
{"name": "Jane",
"bid": 200
},
]
A:
You need to use map, sum and max built-in functions to accomplish this task.
sum_of_all = sum(map(lambda x: x["bid"], s))
print(sum_of_all) # 300
max_bid = max(s, k... | How to sum all "bid" and find MAX "bid" in nesting dictionary in a List? | s = [
{"name": "Jordan",
"bid": 100
},
{"name": "Jane",
"bid": 200
},
]
| [
"You need to use map, sum and max built-in functions to accomplish this task.\nsum_of_all = sum(map(lambda x: x[\"bid\"], s))\nprint(sum_of_all) # 300\n\nmax_bid = max(s, key=lambda x: x[\"bid\"])\nprint(max_bid) # {'name': 'Jane', 'bid': 200}\n\nHere lambda x (aka lamda expression) is used to define an anonymou... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074131387_python.txt |
Q:
All DAGs broken after MWAA update from 2.0.2 to 2.2.2
I am getting the following errors in AWS MWAA UI after I updated from 2.0.2 to 2.2.2
I have exhaustively searched for more details on these errors to no avail
from airflow.providers.slack.operators.slack_webhook import SlackWebhookOperator
ModuleNotFoundError: ... | All DAGs broken after MWAA update from 2.0.2 to 2.2.2 | I am getting the following errors in AWS MWAA UI after I updated from 2.0.2 to 2.2.2
I have exhaustively searched for more details on these errors to no avail
from airflow.providers.slack.operators.slack_webhook import SlackWebhookOperator
ModuleNotFoundError: No module named 'airflow.providers.slack'
Broken plugin: [... | [
"With MWAA 2.2.2 the plugins zip file and the requirements.txt need to be downloaded from here\nAny version conflicts in requirements.txt and Airflow should be cross-checked from here\nWith these two files I was able to fix the broken DAGs in 2.2.2\n",
"Using a public VPC (but tested first on the local runner con... | [
0,
0
] | [] | [] | [
"airflow",
"airflow_2.x",
"airflow_webserver",
"mwaa",
"python"
] | stackoverflow_0073111225_airflow_airflow_2.x_airflow_webserver_mwaa_python.txt |
Q:
Airflow Custom Operator Waiting In Scheduled Status
I try to customize SSHOperator like CustomSSHOperator. Because I need to assign dynamic values to ssh_conn_id and pool variables of SSHOperator. However these two are not in template_fields. So I've create a custom class like below
class CustomSSHOperator(SSHOper... | Airflow Custom Operator Waiting In Scheduled Status | I try to customize SSHOperator like CustomSSHOperator. Because I need to assign dynamic values to ssh_conn_id and pool variables of SSHOperator. However these two are not in template_fields. So I've create a custom class like below
class CustomSSHOperator(SSHOperator):
template_fields: Sequence[str] = ('command', '... | [
"Template fields are rendered after the task has been scheduled, while the task pool field is used before the task is scheduled (by the Airflow scheduler itself).\nThis is the reason why a template cannot be used for the pool field. See also this discussion.\nWhat is happening in your case is that the task remains ... | [
0
] | [] | [] | [
"airflow",
"python"
] | stackoverflow_0074113140_airflow_python.txt |
Q:
Returning a specific value from a column based on the value of another column in the same row in Python Pandas Dataframe
I am quite new to Python dataframes.
In the following case:
id
name
result
1
Cara
A
2
Ben
B
3
Evie
A
4
Mel
C
I want to return the name of the student who has the first occurrence of result... | Returning a specific value from a column based on the value of another column in the same row in Python Pandas Dataframe | I am quite new to Python dataframes.
In the following case:
id
name
result
1
Cara
A
2
Ben
B
3
Evie
A
4
Mel
C
I want to return the name of the student who has the first occurrence of result A (Cara). I want to then go and do the same for the second occurrence of A (Evie) and repeat until 5 occurrences.... | [
"Try this:\nstudents=df.loc[df[result]==\"A\"].head(5)\nprint(student[\"name\"].to_list())\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074131442_dataframe_pandas_python.txt |
Q:
Asyncio yielding results from multiple futures as they arrive
I currently have a function, which yields results from an external source, which may arrive over a long time period.
async def run_command(data):
async with httpx.AsyncClient() as client:
url = f"http://hostname.com:8000/"
async with... | Asyncio yielding results from multiple futures as they arrive | I currently have a function, which yields results from an external source, which may arrive over a long time period.
async def run_command(data):
async with httpx.AsyncClient() as client:
url = f"http://hostname.com:8000/"
async with client.stream("POST", url, json=data, timeout=None) as r:
... | [
"If I understand your requirements correctly, this sounds like a textbook case for a queue producer-consumer setup.\nLet me try and abstract this for you. You have some asynchronous generator that you create by supplying some input data. Once it's running, it yields results at irregular intervals.\nNow you have mul... | [
2
] | [] | [] | [
"async_iterator",
"generator",
"python",
"python_asyncio",
"yield"
] | stackoverflow_0074130544_async_iterator_generator_python_python_asyncio_yield.txt |
Q:
Sending a file path from .py to another .py
I'm trying to call a foo.py passing a filePath to bar.py
foo.py
for path in Path('./csvs').rglob('*.csv'):
exec(open('bar.py').read())
exec(open('bar2.py').read())
exec(open('bar3.py').read())
bar.py
df = pd.read_csv(path, usecols=cols)
#rest of code
Is it ... | Sending a file path from .py to another .py | I'm trying to call a foo.py passing a filePath to bar.py
foo.py
for path in Path('./csvs').rglob('*.csv'):
exec(open('bar.py').read())
exec(open('bar2.py').read())
exec(open('bar3.py').read())
bar.py
df = pd.read_csv(path, usecols=cols)
#rest of code
Is it possible?
| [
"I dont know the exact format of your bar.py, but you can try:\nfor filePath in Path('./csvs').rglob('*.csv'):\n for i in range(1, 4):\n with open(f`bar{i}.py`) as f;\n bar_py_str = f.read()\n\n bar_py_str = bar_py_str.replace(\n 'df = pd.read_csv(filePath, usecols=cols)',\n ... | [
0,
0
] | [] | [] | [
"path",
"python"
] | stackoverflow_0074131437_path_python.txt |
Q:
Moving A Tkinter Label To The Center Of My Concurrent Window Size
I'm working on a python program that has a "sign in page" and right now only has a button that signs in as I have not added areas for input (password and username) and such, and added a placeholder button that when you press it should take you to so... | Moving A Tkinter Label To The Center Of My Concurrent Window Size | I'm working on a python program that has a "sign in page" and right now only has a button that signs in as I have not added areas for input (password and username) and such, and added a placeholder button that when you press it should take you to some sort of a homepage.
Now here's the issue. The button is rendering be... | [
"It's unclear what your ultimate goal is, but I'm guessing you're wanting the button to appear centered, at or near the bottom of the window.\nThe solution for that is to remove the egregious amount of padding you've added to the title, and then pack the button on the bottom rather than defaulting to the top.\nhp_s... | [
1
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074130919_python_tkinter_user_interface.txt |
Q:
parsing json to extract data using python
All I know about my input is, it's a json.
I need to get a src and destination path extracted from it.
The input "text" below is a command line argument.
I think text might look like this '{"destination":"/home/usr/item/, "src":"files/"}'
If I do this,
json_dict = json.d... | parsing json to extract data using python | All I know about my input is, it's a json.
I need to get a src and destination path extracted from it.
The input "text" below is a command line argument.
I think text might look like this '{"destination":"/home/usr/item/, "src":"files/"}'
If I do this,
json_dict = json.dumps(text, separators=(" , ", " : "))
des = j... | [
"From your question, I understand that you want to read in a JSON string from command line and parse that JSON to extract \"destination\".\nWith this rough understanding of your objective, I think you are using json.dumps and json.loads incorrectly.\n\njson.loads() : is used to \"load\" or read in a JSON string. Us... | [
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074128897_json_python.txt |
Q:
does fit give whole batch size in tensorflow
i am triying to train a model with tensorflow.
i have a custom loss function and ste the batch size to 1960 but the fit only seems to be giving my loss func one value at atime. my loss function processes the hole batch though.
code:
import tensorflow as tf
from tensorfl... | does fit give whole batch size in tensorflow | i am triying to train a model with tensorflow.
i have a custom loss function and ste the batch size to 1960 but the fit only seems to be giving my loss func one value at atime. my loss function processes the hole batch though.
code:
import tensorflow as tf
from tensorflow import keras
import math
import numpy as np
... | [
"You need to create valid pairs of training data similar to the random functions and create a dataset with data and labels.\nSee the fixed custom loss function and a sample of them from the website and codes example. Loss functions\nSample: Target layer name and fixed function name mismatch because of the versions ... | [
0
] | [] | [] | [
"deep_learning",
"keras",
"numpy",
"python",
"tensorflow"
] | stackoverflow_0074108880_deep_learning_keras_numpy_python_tensorflow.txt |
Q:
Check If a List of Substrings Is Within Pandas DF Column AND Replace DF Value With Substring If True
I am using python 3.8 in a Jupyter Notebook
What is the best way to see if a string in our dataframe column contains a substring within a list and then REPLACE our dataframe column value with the substring it conta... | Check If a List of Substrings Is Within Pandas DF Column AND Replace DF Value With Substring If True | I am using python 3.8 in a Jupyter Notebook
What is the best way to see if a string in our dataframe column contains a substring within a list and then REPLACE our dataframe column value with the substring it contained? Note: there will only be one match. Mutliple substrings will not match on our comparison.
Ex: '/goog... | [
"You can use apply to pass the values to the function:\ndef check(x):\n for i in compare_list:\n if i in x:\n return i\n return x\n\ndf['page'] = df['page'].apply(check)\n\nOutputs:\n\n\n\n\n\nchannel\npage\n\n\n\n\n0\ngoogle\ncars?exp\n\n\n1\nbing\ngoogle\n\n\n2\nfacebook\n/toytrucks\n\n\n3... | [
0
] | [] | [] | [
"list",
"pandas",
"python"
] | stackoverflow_0074131305_list_pandas_python.txt |
Q:
Pandas: assign a datetime by condition
I have to assign a given datetime value into timestamp column to rows with NaT values if a condition is met in another column. All the values in timestamp are either datetime64[ns] or NaT.
EDIT:
sample data:
dates = [pd.to_datetime('2022-10-14 10:13:52', format = "%Y-%m-%d %H... | Pandas: assign a datetime by condition | I have to assign a given datetime value into timestamp column to rows with NaT values if a condition is met in another column. All the values in timestamp are either datetime64[ns] or NaT.
EDIT:
sample data:
dates = [pd.to_datetime('2022-10-14 10:13:52', format = "%Y-%m-%d %H:%M:%S"),
pd.to_datetime('2022-10-... | [
"The type of the null_date value does not match the type of the df['timestamp'] value. both must be datetime64. use this:\nthreshold = 0.65\nnull_date = pd.to_datetime('2022-09-01 09:00:00', format = \"%Y-%m-%d %H:%M:%S\")\nnull_date = np.datetime64(null_date)\ndf['timestamp'] = np.where(df['A'] >= threshold, null_... | [
0,
0
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074130733_datetime_pandas_python.txt |
Q:
Sum matrix using recursion in python
I need to create a func that calculate the sum of 2d arr (matrix) for example sum of [[1,1,1],[2,2,2]] would give 9.
I tried solving it using two functions - one calls the other but had an error.
It seems that when it gets to the second arr and on, it passes an arr in arr like ... | Sum matrix using recursion in python | I need to create a func that calculate the sum of 2d arr (matrix) for example sum of [[1,1,1],[2,2,2]] would give 9.
I tried solving it using two functions - one calls the other but had an error.
It seems that when it gets to the second arr and on, it passes an arr in arr like that [[]] so it iterates threw another arr... | [
"I think your problem is that you accidentally are not recursively calling sum_mat. You call sum_arr on arr[0] then call it again on arr[1:]. Try:\ndef sum_arr(arr):\n s = 0\n if len(arr) == 1:\n s += arr[0]\n else:\n s += (arr[0] + sum_arr(arr[1:]))\n return s\n\ndef sum_mat(mtx):\n sm... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074131643_python.txt |
Q:
How to remove spaces before pattern and after it in python with regex?
Problem:
I have a list of strings and I need to get rid of whitespaces before and after substring that looks like 'digit / digit'. Been stuck on this for quite a while and still don't understand how to fix itI will appreciate any help.
Sample i... | How to remove spaces before pattern and after it in python with regex? | Problem:
I have a list of strings and I need to get rid of whitespaces before and after substring that looks like 'digit / digit'. Been stuck on this for quite a while and still don't understand how to fix itI will appreciate any help.
Sample input:
steps = [
'mix butter , flour , 1 / 3 c',
'sugar and 1-1 / 4 t',
'vani... | [
"You can use\nimport re\nsteps = ['mix butter , flour , 1 / 3 c', 'sugar and 1-1 / 4 t', 'vanilla']\nsteps_new = [re.sub(r'(\\d+\\s*/\\s*\\d+)|\\s+', lambda x: x.group(1) or \"\", x) for x in steps]\nprint(steps_new) # => ['mixbutter,flour,1 / 3c', 'sugarand1-1 / 4t', 'vanilla']\n\nSee the Python demo online.\nThe ... | [
1,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074131150_python_regex.txt |
Q:
Extract values from a dict made of a list made of another dict
I have the following dict which is composed of a list
response = client.describe_auto_scaling_groups()
print(type(response),'\n')
for key,value in response.items():
print(type(value))
print(len(value))
the result to this is
<class 'dict'>
<... | Extract values from a dict made of a list made of another dict | I have the following dict which is composed of a list
response = client.describe_auto_scaling_groups()
print(type(response),'\n')
for key,value in response.items():
print(type(value))
print(len(value))
the result to this is
<class 'dict'>
<class 'list'>
2
<class 'dict'>
4
I am interested only in the list o... | [
"You can iterate through the response['AutoScalingGroups'] (list) and fetch values from the dictionary using dict-comprehension\nresult = {\n item['AutoScalingGroupName']:item['DesiredCapacity'] \n for item in response['AutoScalingGroups']\n }\n\nResult:\n{'eks-core-20221011202902697400000006... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074131561_python.txt |
Q:
pyscript not working properly, its loading only
when i trying to run this code on web, its loading only. result is not showing, please help me in this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>it's me</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript... | pyscript not working properly, its loading only | when i trying to run this code on web, its loading only. result is not showing, please help me in this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>it's me</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/late... | [
"A couple of other quick observations. First <py-env> is being deprecated in favor of <py-config> (See deprecation warning in console and the relevant section of the tutorial 1). Second, \"requests\" is not currently supported by PyScript (although that is one of the features that seems to be in the most demand). T... | [
1,
0
] | [] | [] | [
"pyscript",
"python"
] | stackoverflow_0074097612_pyscript_python.txt |
Q:
How to round number to one decimal places python?
I'm trying to round my numbers to 1 decimal places. This could be with any number with many decimal places or no decimal places.
But now I'm trying to go with 8.25 as an example because when I try rounding it it always be cut or rounded to 8.2 but I'm looking for i... | How to round number to one decimal places python? | I'm trying to round my numbers to 1 decimal places. This could be with any number with many decimal places or no decimal places.
But now I'm trying to go with 8.25 as an example because when I try rounding it it always be cut or rounded to 8.2 but I'm looking for it to be 8.3 . Pls help
print(round(result,1)) #result -... | [
"You can still use round().\nresult = 8.2546535\nprint(round(result,2))\n\nOutput\n8.25\n\nIf you always want to round up you can use math.ceil()\nimport math\nmath.ceil(8.211234 * 10) / 10\n\nResult\n8.3\n\n",
"import math \ndef round_up(n, decimals=0):\n multiplier = 10 ** decimals\n return mat... | [
0,
0
] | [] | [] | [
"decimal",
"python",
"rounding"
] | stackoverflow_0074131752_decimal_python_rounding.txt |
Q:
How do I make sprites in pygame not move through eachother?
I'm making a game in pygame and I'm having some trouble with object collisions.
import pygame, sys
from pygame.math import Vector2
pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
#Environment Variables
gravity = -1
... | How do I make sprites in pygame not move through eachother? | I'm making a game in pygame and I'm having some trouble with object collisions.
import pygame, sys
from pygame.math import Vector2
pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
#Environment Variables
gravity = -1
jumpForce = 20
moveSpeed = 10
#Game Objects
playerPos = Vector2(... | [
"It is not enough to change the position of the player when the player hits the obstacle. You need to constrain the player's box (pygame.Rect object) with the obstacle rectangle and update the player's position. Clamp and calculate the position of the player before checking for collision:\ndef PlayerVelocity():\n ... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074131714_pygame_python.txt |
Q:
Compare Dataframes based on ID
I have two dataframes created from a SQL table. I want to find what new rows were added based on new IDs (ID coulmn). Any suggestions?
PS: New to this forum.
ID Name Desc
1 A AA
2 B BB
3 C CC
Table 2
ID Name Desc
1 A AA
2 B BB
3 C CC
4 D DD
5 E ... | Compare Dataframes based on ID | I have two dataframes created from a SQL table. I want to find what new rows were added based on new IDs (ID coulmn). Any suggestions?
PS: New to this forum.
ID Name Desc
1 A AA
2 B BB
3 C CC
Table 2
ID Name Desc
1 A AA
2 B BB
3 C CC
4 D DD
5 E EE
Expected Output
ID Name Desc
4... | [
"if you combine the two dataframes then you can remove all rows with duplicates:\nimport pandas as pd\ndfA = pd.DataFrame([\n [1,'A','AA'],\n [2,'B','BB'],\n [3,'C','CC']\n])\n\ndfB = pd.DataFrame([\n [1,'A','AA'],\n [2,'B','BB'],\n [3,'C','CC'],\n [4,'D','DD'],\n [5,'E','EE']\n])\n\ndfA.app... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074131438_dataframe_pandas_python.txt |
Q:
logical "if" statement with function for a word level neural language model
I've followed this word level neural language model and everything works right up until the last generate_seq() function. Below is the code to set up the function and the error message I get. I've looked up this error but the solutions I'm... | logical "if" statement with function for a word level neural language model | I've followed this word level neural language model and everything works right up until the last generate_seq() function. Below is the code to set up the function and the error message I get. I've looked up this error but the solutions I'm seeing don't solve this issue. Ultimately I'm trying to see what additional word... | [
"When you compare an array with an array, the result will also be an array with boolean values. For example:\nnp.ones((2,)) == np.ones((2,))\n\nwill return:\narray([ True, True])\n\nIf you want to check if all values in that boolean array are true – meaning the arrays contain equal values – you have to use all:\na... | [
0
] | [] | [] | [
"deep_learning",
"keras",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0074131781_deep_learning_keras_neural_network_python_tensorflow.txt |
Q:
Calculating the area of the irregular darker circle in the image below using python
I wanted to use this particular image and calculate the area of the darker region which is irregular shaped. I have many such images in different folders (each folder having each image). This way if I iterate the process in a for l... | Calculating the area of the irregular darker circle in the image below using python |
I wanted to use this particular image and calculate the area of the darker region which is irregular shaped. I have many such images in different folders (each folder having each image). This way if I iterate the process in a for loop I should be able to get a table outlining area of the each image in one go. How can ... | [
"You can binarize your image and then sum the pixels for an approximated area, in terms of pixels. For realistic approximation, you should convert from pixels to your dimension according to your resolution.\nFor your image, I got the following:\nimpot cv2\nimg = cv2.imread('67EAS.jpg', cv2.IMREAD_GRAYSCALE)\n\n\nBi... | [
1
] | [] | [] | [
"annotations",
"computer_vision",
"image_processing",
"python"
] | stackoverflow_0074129782_annotations_computer_vision_image_processing_python.txt |
Q:
Get the Views of Athena editor using boto3
On Athena query editor there is the Tables list section and the Views list section. Is there a way to obtain the Views list section using python's boto3 module? (get view names and the actual sql that makes up the view)
From what I see, we can only obtain the Saved Querie... | Get the Views of Athena editor using boto3 | On Athena query editor there is the Tables list section and the Views list section. Is there a way to obtain the Views list section using python's boto3 module? (get view names and the actual sql that makes up the view)
From what I see, we can only obtain the Saved Queries list using the "list_named_queries" function:
... | [
"Amazon Athena uses the AWS Glue Data Catalog.\nTherefore, you can obtain the list of tables by using get_tables() in the AWS Glue API.\nIt seems to include a few fields that are specifically populated by Views (eg ViewOriginalText) so you should be able to identify which ones are Views rather than Tables.\n"
] | [
0
] | [] | [] | [
"amazon_web_services",
"boto3",
"python"
] | stackoverflow_0074127536_amazon_web_services_boto3_python.txt |
Q:
Key Error when Merging columns from 2 Data Frames
I am trying to create a new df with certain columns from 2 others:
The first called visas_df:
And the second called cpdf:
I only need the highlighted columns. But when I try this:
df_joined = pd.merge(cpdf,visas_df["visas"],on="date")
The error appearing is: Key... | Key Error when Merging columns from 2 Data Frames | I am trying to create a new df with certain columns from 2 others:
The first called visas_df:
And the second called cpdf:
I only need the highlighted columns. But when I try this:
df_joined = pd.merge(cpdf,visas_df["visas"],on="date")
The error appearing is: KeyError: 'date'
I imagine this is due to how I created cp... | [
"df['visas'] in merge function is not a dataframe and its not contain date column. İf you want to df as a dataframe, you have to use double square bracket [[]] like this:\ndf_joined = pd.merge(cpdf,visas_df[[\"date\",\"visas\"]],on=\"date\")\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074131532_dataframe_pandas_python.txt |
Q:
How to get the earliest date from list of dictionaries?
I have a list of dictionaries and would like to get the earliest date value (and date only!) from the list. See example below:
{'taps': [{'duration': 0,
'datetime': '2022-06-05T09:35:56.131498'},
{'duratin': 518,
'datetime': '2022-06-05T09:35:56.64984... | How to get the earliest date from list of dictionaries? | I have a list of dictionaries and would like to get the earliest date value (and date only!) from the list. See example below:
{'taps': [{'duration': 0,
'datetime': '2022-06-05T09:35:56.131498'},
{'duratin': 518,
'datetime': '2022-06-05T09:35:56.649846',
{'duration': 500,
'datetime': '2022-06-06T09:35:57.1... | [
"In your example, datetimes are strings only, so this will print the earliest date: (working if strings are all in the format : YYYY-MM-DD...)\nitems = {\n 'taps': [{\n 'duration': 0,\n 'datetime': '2022-06-05T09:35:56.131498'\n }, {\n 'duratin': 518,\n 'datetime': '2022-06-05T09:3... | [
1,
1
] | [] | [] | [
"datetime",
"dictionary",
"key_value",
"python"
] | stackoverflow_0074131922_datetime_dictionary_key_value_python.txt |
Q:
Pandas giving me different outputs when compared to Python datetime
This pandas documentation says pandas datetime works with reference to python default strftime. But, It giving me different results with same dates in part of my code.
As here it is referencing to input format same as python strftime.
Using pytho... | Pandas giving me different outputs when compared to Python datetime | This pandas documentation says pandas datetime works with reference to python default strftime. But, It giving me different results with same dates in part of my code.
As here it is referencing to input format same as python strftime.
Using python strptime
import datetime
date = '19981128'
date_python = datetime.datet... | [
"The documentation says:\n\nReturns\ndatetime\nIf parsing succeeded. Return type depends on input (types in parenthesis correspond to fallback in case of unsuccessful timezone or out-of-range timestamp parsing):\nscalar: Timestamp (or datetime.datetime)\n\n(emphasis mine)\nand\n\nNotes\nMany input types are support... | [
1,
1
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074131418_datetime_pandas_python.txt |
Q:
macos Big Sur matplotlib chart displaying extra data, while Windows, Linux Mint working properly
Pls help, I'm desperate and behind schedule , I've tried to solve this over 1 week for a solution but nothing!
I have been working on a relatively simple cross platform python app. This app works correctly in Windows 1... | macos Big Sur matplotlib chart displaying extra data, while Windows, Linux Mint working properly | Pls help, I'm desperate and behind schedule , I've tried to solve this over 1 week for a solution but nothing!
I have been working on a relatively simple cross platform python app. This app works correctly in Windows 10/11 and Linux Mint but not in MacOS, Big Sur.
The app uses matplotlib + tkinter to display an animate... | [
"It looks a lot like an offset rather than the newest value to me.\nHave you tried to\nax.xaxis.get_major_formatter().set_useOffset(False)\n\nJust to see if it changes something (or even solve the problem)?\nAnother thing you could try, in case it is really a label, not an offset, is to specify a formatter\nimport ... | [
1
] | [] | [] | [
"macos_big_sur",
"matplotlib",
"python"
] | stackoverflow_0074131234_macos_big_sur_matplotlib_python.txt |
Q:
Pass user input to authorization header in post request using python
I want to send user input (username and password) to the Header in post request. I have this so far-
import requests ... | Pass user input to authorization header in post request using python | I want to send user input (username and password) to the Header in post request. I have this so far-
import requests
import urllib3 ... | [
"Username and password go in the auth keyword of requests. Remove them from headers but pass them in requests.post\nheaders = { ... | [
2
] | [] | [] | [
"post",
"python",
"xml"
] | stackoverflow_0074131964_post_python_xml.txt |
Q:
unable to install pyspark
I am trying to install pyspark as this:
python setup.py install
I get this error:
Could not import pypandoc - required to package PySpark
pypandoc is installed already
Any ideas how can I install pyspark?
A:
I faced the same issue and solved it as below
install pypandoc before install... | unable to install pyspark | I am trying to install pyspark as this:
python setup.py install
I get this error:
Could not import pypandoc - required to package PySpark
pypandoc is installed already
Any ideas how can I install pyspark?
| [
"I faced the same issue and solved it as below\ninstall pypandoc before installing pyspark\npip install pypandoc\npip install pyspark\n\n",
"Try installing pypandoc with python3 with pip3 install pypandoc.\n",
"If you are using window follow the following steps:\n1) install Jdk in the computer from link: https:... | [
41,
5,
1,
1,
0,
0,
0
] | [
"As of version 2.2 you can directly install pyspark using pip\npip install pyspark\n\n"
] | [
-3
] | [
"pyspark",
"python"
] | stackoverflow_0051500288_pyspark_python.txt |
Q:
update table using a DataFrame
I have a DataFrame(click_df2):
date L120_active_cohort_logins L120_active_cohort percentage_L120_active_cohort_logins
0 2022-09-03 45000 199000 22.621906
1 2022-09-04 40000 2000... | update table using a DataFrame | I have a DataFrame(click_df2):
date L120_active_cohort_logins L120_active_cohort percentage_L120_active_cohort_logins
0 2022-09-03 45000 199000 22.621906
1 2022-09-04 40000 200000 19.09... | [
"Just use to_dict('records') to run the mutation inside loop. Here is an example:\n# docker-compose.yaml\nversion: \"3\"\nservices:\n click_server:\n image: yandex/clickhouse-server\n expose:\n - \"8123\"\n ports:\n - \"8123:8123\"\n - \"9000:9000\"\n - \"9009:9009\"\n\nrun clickhouse contain... | [
0
] | [] | [] | [
"clickhouse",
"pandas",
"python",
"sql_update"
] | stackoverflow_0073665108_clickhouse_pandas_python_sql_update.txt |
Q:
Pandas group by without losing type information while ensuring all data is retained
I am using this function to group a pandas dataframe. I have a frame with float64, int64, and object columns. This function groupbyFlatCount is adapted from dask. I was encountering issues with missing data when grouping over an in... | Pandas group by without losing type information while ensuring all data is retained | I am using this function to group a pandas dataframe. I have a frame with float64, int64, and object columns. This function groupbyFlatCount is adapted from dask. I was encountering issues with missing data when grouping over an int64 column. I isolated this column and was able to get it to work with an object dtype.
d... | [
"The robust solution to this issue is to convert to object columns and then back again.\ndef groupbyFlatCount(frame, by):\ndtypes = frame[by].dtypes.to_dict()\nfor col in by:\n frame[col] = frame[col].map(str)\nreturn frame.groupby(by=by).size().reset_index().rename(columns={0:'count'}).astype(dtypes)\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074132145_dataframe_pandas_python.txt |
Q:
Any easy way to extract details from a HTM webpage?
I am trying to extract the following address from the 10-Q on this webpage and need help getting it to work: https://www.sec.gov/ix?doc=/Archives/edgar/data/1318605/000095017022012936/tsla-20220630.htm
1 Tesla Road
Austin, Texas
URL = f'https://www.sec.gov/ix?doc... | Any easy way to extract details from a HTM webpage? | I am trying to extract the following address from the 10-Q on this webpage and need help getting it to work: https://www.sec.gov/ix?doc=/Archives/edgar/data/1318605/000095017022012936/tsla-20220630.htm
1 Tesla Road
Austin, Texas
URL = f'https://www.sec.gov/ix?doc=/Archives/edgar/data/{cik}/{accessionNumber}/{primaryDoc... | [
"Unfortently, because I am running this on DataBricks, using Selenium isn't an immediate solution I can take. However, it does look like this method works!\nr = requests.get(f'https://www.sec.gov/Archives/edgar/data/{cik}/{accessionNumber.replace(\"-\", \"\")}/{accessionNumber}.txt', headers=headers)\nraw_10k = r.t... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074129022_beautifulsoup_python.txt |
Q:
Increase Python Stack Size
Right off the bat: Yes I've tried threading.stack_size(biggest_number_windows10_allows) with Thread(target=some_function, args=(arg1, arg2)).
I also increased the maximum recursion depth to 4 million + (this depth is much larger than my code will ever need).
Print statements show the rec... | Increase Python Stack Size | Right off the bat: Yes I've tried threading.stack_size(biggest_number_windows10_allows) with Thread(target=some_function, args=(arg1, arg2)).
I also increased the maximum recursion depth to 4 million + (this depth is much larger than my code will ever need).
Print statements show the recursive function executing, but t... | [
"I ultimately figured out my own question.\nSolution:\nI used numba to implement the recursive function. This allowed me to both use the size of C types (true int size vs. Python's 24 byte behemoths).\nIn addition, I specified 16 bit ints, which further reduced the stack size of each call.\nNice bonus, each recursi... | [
0
] | [] | [] | [
"cython",
"python",
"stack_size",
"windows"
] | stackoverflow_0074105815_cython_python_stack_size_windows.txt |
Q:
Python: how to iterate thru a folder to find all "docx"
I need help writing a for loop to find all ".docx" files then edit them and save them under a new name.
I have some code that works for a single file
I need code that iterates thru a folder and picks up only the "docx."
After editing, save them into another ... | Python: how to iterate thru a folder to find all "docx" | I need help writing a for loop to find all ".docx" files then edit them and save them under a new name.
I have some code that works for a single file
I need code that iterates thru a folder and picks up only the "docx."
After editing, save them into another folder.
a) Retain the *current file name and put it in anothe... | [
"A simple answer but effective, you could use the glob module as this has direct pattern searching builtin. See the following example\nimport glob\nfor i in glob.glob('E:\\drivers\\\\**\\\\*.pdf', recursive=True):\n print(i) \n\nThis would look at all the files in E:\\Drivers\\ then look through every sub direc... | [
0,
0
] | [] | [] | [
"global",
"python",
"text"
] | stackoverflow_0074116523_global_python_text.txt |
Q:
moduleerror pil not found
when i run my program in python it works but when i use pyinstaller it doesnt work. my app (login.py) imports another file (app.py) which imports PIL
even though i use hidden import to import PIL, i get this when i launch the exe
Traceback (most recent call last):
File "login.py", line 5... | moduleerror pil not found | when i run my program in python it works but when i use pyinstaller it doesnt work. my app (login.py) imports another file (app.py) which imports PIL
even though i use hidden import to import PIL, i get this when i launch the exe
Traceback (most recent call last):
File "login.py", line 5, in
from app import App
File ... | [
"You should use import Image or from PIL import Image instead of import PIL, as you can check in this answer.\n"
] | [
1
] | [] | [] | [
"pyinstaller",
"python",
"python_imaging_library"
] | stackoverflow_0074131896_pyinstaller_python_python_imaging_library.txt |
Q:
For Buildfire app maker can python code be used?
I'm using vgg face and require user input. Can python work in any way with Buildfire?
A:
If you’re creating a server side api call in Python, then no problem. If you want to build on top of the BuildFire.JS SDK for code to live on the phone, then it needs to be in... | For Buildfire app maker can python code be used? | I'm using vgg face and require user input. Can python work in any way with Buildfire?
| [
"If you’re creating a server side api call in Python, then no problem. If you want to build on top of the BuildFire.JS SDK for code to live on the phone, then it needs to be in JavaScript\n"
] | [
0
] | [] | [] | [
"buildfire",
"python"
] | stackoverflow_0074117006_buildfire_python.txt |
Q:
Anaconda ImportError: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found
I am getting the following import error when I am trying to run a Python script in a conda environment
(squad) azada@scholar-fe00:~/Desktop/Toy-Problem-Team-2 $ python3 train.py
Traceback (most recent call last):
File "train.py"... | Anaconda ImportError: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found | I am getting the following import error when I am trying to run a Python script in a conda environment
(squad) azada@scholar-fe00:~/Desktop/Toy-Problem-Team-2 $ python3 train.py
Traceback (most recent call last):
File "train.py", line 21, in <module>
from tensorboardX import SummaryWriter
File "/home/azada/min... | [
"I spent a day working on this having encountered the same exact problem working on my research university's computing cluster with the same specs as you, and I finally found the right Stack Overflow thread. None of the above answers here work, unfortunately, but I can say with very high confidence that the details... | [
24,
2,
1
] | [
"Run this code and your problem should be solved,\nconda install -c conda-forge gcc\n\n"
] | [
-2
] | [
"anaconda",
"c++",
"glibc",
"python",
"tensorflow"
] | stackoverflow_0058424974_anaconda_c++_glibc_python_tensorflow.txt |
Q:
looping over model inference that has 2 outputs
I am working with the openVINO zoo that has lots of pre-trained models. How does one handle in the post process of the data after inference when the model has 2 outputs, like this model? I am only looking to draw bounding boxes around people in the video or picture f... | looping over model inference that has 2 outputs | I am working with the openVINO zoo that has lots of pre-trained models. How does one handle in the post process of the data after inference when the model has 2 outputs, like this model? I am only looking to draw bounding boxes around people in the video or picture frame.
Output 1:
The boxes is a blob with the shape 1... | [
"So as stated in the description:\n\nIn case of person detection, it is equal to 1 for each detected box\nwith person in it and 0 for the background.\n\nyou may need to take both outputs into account because output2 may contain a background class. You can reuse most part of the your code:\n# output1, output2 = mode... | [
1
] | [] | [] | [
"computer_vision",
"machine_learning",
"openvino",
"python"
] | stackoverflow_0074131683_computer_vision_machine_learning_openvino_python.txt |
Q:
Changing pickup and dropoff dates in turo using playwright
Hi I'm trying to scrape some data from this site https://turo.com/us/en/car-rental/united-states/austin-tx/tesla/model-s/1733237?endDate=11%2F09%2F2022&endTime=11%3A00&startDate=11%2F05%2F2022&startTime=11%3A00 using playwright but I'm struggling with chan... | Changing pickup and dropoff dates in turo using playwright | Hi I'm trying to scrape some data from this site https://turo.com/us/en/car-rental/united-states/austin-tx/tesla/model-s/1733237?endDate=11%2F09%2F2022&endTime=11%3A00&startDate=11%2F05%2F2022&startTime=11%3A00 using playwright but I'm struggling with changing the date and time. At first I tried to make my bot click on... | [
"It is not possible to do it with the URL as I can see\nAnyways, I prepared an script for making what you wanted. I used an auxiliar function that you can use. I hope it works for you.\nimport time\nfrom playwright.sync_api import Playwright, sync_playwright, expect\n\n#This function wait for an element, if the ele... | [
0
] | [] | [] | [
"api",
"playwright",
"python",
"url"
] | stackoverflow_0074105133_api_playwright_python_url.txt |
Q:
How to subset Nested Dictionaries
I have a dictionary like the following:
original = {"Triclusters":{"0":{"%Missings":"0","ColumnPattern":"Constant","Data":
{"0":[["-1.72","-1.72","-1.72","-1.72"],["-1.72","-1.72","-1.72","-1.72"]
,["-1.72","-1.72... | How to subset Nested Dictionaries | I have a dictionary like the following:
original = {"Triclusters":{"0":{"%Missings":"0","ColumnPattern":"Constant","Data":
{"0":[["-1.72","-1.72","-1.72","-1.72"],["-1.72","-1.72","-1.72","-1.72"]
,["-1.72","-1.72","-1.72","-1.72"],["-1.72","-1.72","-1... | [
"You could do it via:\nd = {k: {nk: nv for nk, nv in v['Data'].items()} for k, v in original['Triclusters'].items()}\n\nd\n{'0': {'0': [['-1.72', '-1.72', '-1.72', '-1.72'], ['-1.72', '-1.72', '-1.72', '-1.72'], ['-1.72', '-1.72', '-1.72', '-1.72'], ['-1.72', '-1.72', '-1.72', '-1.72']], '1': [['-1.72', '-1.72', '-... | [
0,
0,
0
] | [] | [] | [
"dictionary",
"dictionary_comprehension",
"list",
"nested",
"python"
] | stackoverflow_0074132152_dictionary_dictionary_comprehension_list_nested_python.txt |
Q:
How to include header file in source distribution?
I am trying to create a source distribution containing a simple c function. Here are the files I have.
# file setup.py
from setuptools import setup
setup(
name="example",
version="0.1",
py_modules=["example", "build"], # If i dont include build.py, it... | How to include header file in source distribution? | I am trying to create a source distribution containing a simple c function. Here are the files I have.
# file setup.py
from setuptools import setup
setup(
name="example",
version="0.1",
py_modules=["example", "build"], # If i dont include build.py, it will not find it.
cffi_modules=["build.py:ffibuilde... | [
"Add in the file setup.py, inside the setup function package_data={\"\": [\"*.h\"]}. This will include all the header files in the source distribution.\nsetup(\n name=\"example\",\n version=\"0.1\",\n py_modules=[\"example\", \"build\"], # If i dont include build.py, it will not find it.\n cffi_modules=... | [
1,
1
] | [] | [] | [
"c",
"cffi",
"pip",
"python",
"setuptools"
] | stackoverflow_0071183800_c_cffi_pip_python_setuptools.txt |
Q:
Discord bot import module error after downloading the discord module
I am trying to make a discord bot, and I have installed the discord.py through the python pip. However, VSCODE throw an importerror and ask me to download the discord.py again. How should I fix the issue. Thank you very much!
A:
This looks to b... | Discord bot import module error after downloading the discord module | I am trying to make a discord bot, and I have installed the discord.py through the python pip. However, VSCODE throw an importerror and ask me to download the discord.py again. How should I fix the issue. Thank you very much!
| [
"This looks to be some error on their end not yours. I don't see anything in your code that's trying to import a module named disco. Try saving, closing VSCode, opening it back up and rerunning your code. Sometimes it is a bit behind in processing what you've typed. Also, I would suggest not displaying your bot's t... | [
0
] | [] | [] | [
"discord",
"python"
] | stackoverflow_0074130202_discord_python.txt |
Q:
One to one self relationship in SQLAlchemy
I need to create an SQLAlchemy version of a linked list. It's actually more complex than that, but it boils down to this:
I need a one-to-one, self-referential, bidirectional relationship in a class. Every element may only have a single parent or none at all, and up to on... | One to one self relationship in SQLAlchemy | I need to create an SQLAlchemy version of a linked list. It's actually more complex than that, but it boils down to this:
I need a one-to-one, self-referential, bidirectional relationship in a class. Every element may only have a single parent or none at all, and up to one child.
I simplified my class so it looks like ... | [
"As exception says you need to set remote_side keyword for relationship. Otherwise sqlalchemy cannot select reference direction.\nclass Node(declarative_base()):\n ...\n prev = relationship(\n 'Node',\n uselist=False,\n remote_side=[id],\n backref=backref('next', uselist=False)\n ... | [
14,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0012872873_python_sqlalchemy.txt |
Q:
Can't find element in Selenium Python
I have been working on this problem for quite a bit now, and can't figure out why this is happening. I am trying to click a button. The button and the corresponding text always changes, but the XPATH stays the same.
Button I am trying to click
It doesn't work with CSS Selector... | Can't find element in Selenium Python | I have been working on this problem for quite a bit now, and can't figure out why this is happening. I am trying to click a button. The button and the corresponding text always changes, but the XPATH stays the same.
Button I am trying to click
It doesn't work with CSS Selector either. I am using Chrome web version 106.... | [
"Try this:\ndriver.find_element(\"xpath\", '//*[@id=\"root\"]/div/div/div[2]/div[3]/div/div/div/div[2]/button[2]').click()\n\nMay be you using not correct syntax\n"
] | [
0
] | [] | [] | [
"automation",
"python",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0074132157_automation_python_selenium_selenium_chromedriver.txt |
Q:
Django mail attachments blank except for 1st email sent, when looping through recipients
I have a newsletter being sent out using Django forms, with multiple files that can be attached.
I'm looping through the list of recipients (if they are verified, and agreed to receive the newsletter, etc.)
It all works fine, ... | Django mail attachments blank except for 1st email sent, when looping through recipients | I have a newsletter being sent out using Django forms, with multiple files that can be attached.
I'm looping through the list of recipients (if they are verified, and agreed to receive the newsletter, etc.)
It all works fine, emails are received to these users, including 1 or more attached files.
The problem is only t... | [
"The file read function: f.read() reads through the file and returns it as a string but leaves the read cursor at the end of the file. So when you call it a second time it returns nothing.\nSome options might be to use attach_file instead of attach:\nemail.attach_file(f.name, f.content_type)\n\nor reading each file... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074132064_django_python.txt |
Q:
what does these python3 output line mean "Input In [1], in ()" as a result from the following code
what does these python3 output line mean "Input In [1], in <cell line: 18>()" as a result from the following code
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.las... | what does these python3 output line mean "Input In [1], in ()" as a result from the following code | what does these python3 output line mean "Input In [1], in <cell line: 18>()" as a result from the following code
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname... | [
"It's a string representation of your class Employee. When you print the instance of the class it prints the string representation of your class.\nYou can check that by emp_1.__str__.\nYou can change your string representation of class like this,\nclass Employee:\n\n def __init__(self, first, last, pay):\n ... | [
0
] | [] | [] | [
"class",
"line",
"output",
"python",
"semantics"
] | stackoverflow_0074132263_class_line_output_python_semantics.txt |
Q:
Python summing selected values in a column that match given condition
Here's the data after the preliminary data cleaning.
year
country
employees
2001
US
9
2001
Canada
81
2001
France
22
2001
Japan
31
2001
Chile
7
2001
Mexico
15
2001
Total
165
2002
US
5
2002
Canada
80
2002
France
20
2002
Japan
30
2002
... | Python summing selected values in a column that match given condition | Here's the data after the preliminary data cleaning.
year
country
employees
2001
US
9
2001
Canada
81
2001
France
22
2001
Japan
31
2001
Chile
7
2001
Mexico
15
2001
Total
165
2002
US
5
2002
Canada
80
2002
France
20
2002
Japan
30
2002
Egypt
35
2002
Total
170
...
...
...
2010
US
32
...... | [
"You may consider dropping Total from your dataframe.\nHowever, as stated, your question can be solved by using Series.where to map away values that you don't recognize:\ncountry = df[\"country\"].where(df[\"country\"].isin([\"US\", \"Canada\", \"France\", \"Japan\", \"Total\"]), \"Others\")\ndf.groupby([df[\"year\... | [
0
] | [] | [] | [
"for_loop",
"if_statement",
"pandas",
"python",
"sum"
] | stackoverflow_0074131587_for_loop_if_statement_pandas_python_sum.txt |
Q:
Python Selenium in AWS Lambda returns empty HTML
I'm using Python's Selenium lib for crawling and my scripts are Lambdas on AWS.
This is how my config looks like:
def get_headless_driver():
options = Options()
options.binary_location = '/opt/headless-chromium'
options.add_argument('--headless')
opt... | Python Selenium in AWS Lambda returns empty HTML | I'm using Python's Selenium lib for crawling and my scripts are Lambdas on AWS.
This is how my config looks like:
def get_headless_driver():
options = Options()
options.binary_location = '/opt/headless-chromium'
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argu... | [] | [] | [
"If you selenium version > 4.3\nThen try this:\ndriver.find_element('xpath','//*[@id=\"x-widget-9\"]/div[2]/div[1]/div/div/div[1]/div/div[8]/div[2]/div[1]/table/tbody[2]/tr/td[1]/div/div/div[1]').text\n\nlink\n"
] | [
-1
] | [
"amazon_web_services",
"python",
"selenium"
] | stackoverflow_0074132020_amazon_web_services_python_selenium.txt |
Q:
Thread fails to return the value of an asynchronous function / TypeError: 'coroutine' object is not subscriptable
I need to asynchronously execute a function and then save the return value for it to be returned when I need it.
I have the following code:
class EncodingThread(Thread):
def __init__(self):
... | Thread fails to return the value of an asynchronous function / TypeError: 'coroutine' object is not subscriptable | I need to asynchronously execute a function and then save the return value for it to be returned when I need it.
I have the following code:
class EncodingThread(Thread):
def __init__(self):
Thread.__init__(self)
self.value = None
self.frame = None
def setFrame(self,frame):
self.f... | [
"Fixing the asyncio issue is not going to completely fix this code. As soon as you start the EnclosingThread, its run method will execute; at that point, the variable self.frame is None. When you try to set it by calling thread.setFrame(some_value), that will be too late: the call to publish_message has already h... | [
0
] | [] | [] | [
"asynchronous",
"multithreading",
"python",
"python_asyncio"
] | stackoverflow_0074131337_asynchronous_multithreading_python_python_asyncio.txt |
Q:
How to replace the first n numbers of a specific character in a string
I’m new to computer science and really stuck on this question so any help would be great :).
Firstly I was given the following global variable:
ARROWS = ‘<>^v’
The idea is to create a function that takes in a string and an integer (n). The fu... | How to replace the first n numbers of a specific character in a string | I’m new to computer science and really stuck on this question so any help would be great :).
Firstly I was given the following global variable:
ARROWS = ‘<>^v’
The idea is to create a function that takes in a string and an integer (n). The function should then replace the first n number of characters with ‘X’. So far... | [
"Hi it seems to me (if you want to avoid using libraries) that you can iterate over the characters in the string and do comparisons to decide if the character needs to be changed. Here is some sample code which should help you.\nARROWS = '<>^v'\n\n\ndef replace_up_to(in_str, n):\n # store the new character in th... | [
1,
1,
0,
0
] | [] | [] | [
"python",
"replace",
"str_replace",
"string"
] | stackoverflow_0074132130_python_replace_str_replace_string.txt |
Q:
Python Pandas create multiple dataframe with cicle for
There is a way to create a multiple dataframe in Pandas with a cicle for?
I post a piece of code to make you understand what I mean.
tickers = ['BTCUSDT', 'ETHUSDT']
for t in tickers:
klines = client.get_historical_klines(t, Client.KLINE_INTERVAL_5MINUTE, "10... | Python Pandas create multiple dataframe with cicle for | There is a way to create a multiple dataframe in Pandas with a cicle for?
I post a piece of code to make you understand what I mean.
tickers = ['BTCUSDT', 'ETHUSDT']
for t in tickers:
klines = client.get_historical_klines(t, Client.KLINE_INTERVAL_5MINUTE, "100 minutes ago UTC")
data = pd.DataFrame(klines).reset_ind... | [
"At the bottom-of-the-loop put the objects in a container like a list.\ntickers = ['BTCUSDT', 'ETHUSDT']\nstuff = []\nfor t in tickers:\n ...\n data = pd.DataFrame(klines).reset_index()\n ...\n stuff.append[data]\n\nOr a dict if you want to associate them with something.\ntickers = ['BTCUSDT', 'ETHUSDT'... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074131665_dataframe_pandas_python.txt |
Q:
Best approach to assigning existing data to a new django user
I am new in Django and I wanted to know what is the right approach to the following problem:
I have a table of companies, which is m2m with the table of users. Since they can be created by the users.
So what I want to do is, every time a user is created... | Best approach to assigning existing data to a new django user | I am new in Django and I wanted to know what is the right approach to the following problem:
I have a table of companies, which is m2m with the table of users. Since they can be created by the users.
So what I want to do is, every time a user is created, I take a "default" company with a certain id and copy it to this ... | [
"This should work:\ndef create_default_company_for_user(user: User):\n create_kwargs = {} # Whatever values you want for the new company fields\n default_company = Company.objects.create(**create_kwargs)\n user.company_set.add(default_company)\n\nCall this where you create users. The best way would probab... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074129596_django_python.txt |
Q:
Renaming columns using the first part of the string in the first row of a dataframe
I imported a dataset with different column names that all start with Area, Mean, StdDev but have () with different strings inside.
What I want to do is split the string in each column by the "( )" and set the first part as the colu... | Renaming columns using the first part of the string in the first row of a dataframe | I imported a dataset with different column names that all start with Area, Mean, StdDev but have () with different strings inside.
What I want to do is split the string in each column by the "( )" and set the first part as the column headers and the second part as a row under that header. I was looking into stacking an... | [
"Using pivot\ndf = df.transpose()\ndf = (\n df\n .assign(\n Aggregate=df[\"1\"].str.replace(r\"\\(.*\\)\", \"\", regex=True),\n Label=df.pop(\"1\").str.extract(r\"\\((.*?)\\)\", expand=True)\n )\n .pivot(index=\"Label\", columns=\"Aggregate\", values=\"2\")\n .astype(int)\n .reset_in... | [
1
] | [] | [] | [
"pandas",
"python",
"reformatting",
"split"
] | stackoverflow_0074132026_pandas_python_reformatting_split.txt |
Q:
pandas datetime to unix timestamp seconds
From the official documentation of pandas.to_datetime we can say,
unit : string, default ‘ns’
unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer or
float number. This will be based off the origin. Example, with
unit=’ms’ and origin=’unix’ (the default), t... | pandas datetime to unix timestamp seconds | From the official documentation of pandas.to_datetime we can say,
unit : string, default ‘ns’
unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer or
float number. This will be based off the origin. Example, with
unit=’ms’ and origin=’unix’ (the default), this would calculate the
number of milliseconds ... | [
"I think you misunderstood what the argument is for. The purpose of origin='unix' is to convert an integer timestamp to datetime, not the other way.\npd.to_datetime(1.547559e+09, unit='s', origin='unix') \n# Timestamp('2019-01-15 13:30:00')\n\nHere are some options:\nOption 1: integer division\nConversely, you can ... | [
108,
25,
1,
1
] | [
"In case you are accessing a particular datetime64 object from the dataframe, chances are that pandas will return a Timestamp object which is essentially how pandas stores datetime64 objects.\nYou can use pd.Timestamp.to_datetime64() method of the pd.Timestamp object to convert it to numpy.datetime64 object with ns... | [
-2
] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0054313463_datetime_pandas_python.txt |
Q:
Add column Heroku database
Goodnight.
I have a project done in Python and Django and today I added one more Model Table and added a column manually and it worked in the development environment.
But when deploying to Heroku , Heroku cannot find this manually created column and returns this error "column does not ex... | Add column Heroku database | Goodnight.
I have a project done in Python and Django and today I added one more Model Table and added a column manually and it worked in the development environment.
But when deploying to Heroku , Heroku cannot find this manually created column and returns this error "column does not exist" .
How do I manually add a c... | [
"I'm not sure you should be managing your tables manually but if you must do it manually and you're using Heroku Postgres, you can use the Heroku CLI to open a psql session:\nheroku pg:psql\n\nNote you will need PostgreSQL installed locally. See docs for more details.\n",
"\nHeroku cannot find this manually creat... | [
0,
0
] | [] | [] | [
"database",
"django",
"heroku",
"python"
] | stackoverflow_0074132219_database_django_heroku_python.txt |
Q:
Python Killed: 9 when running a code using dictionaries created from 2 csv files
I am running a code that has always worked for me. This time I ran it on 2 .csv files: "data" (24 MB) and "data1" (475 MB). "data" has 3 columns of about 680000 elements each, whereas "data1" has 3 columns of 33000000 elements each. W... | Python Killed: 9 when running a code using dictionaries created from 2 csv files | I am running a code that has always worked for me. This time I ran it on 2 .csv files: "data" (24 MB) and "data1" (475 MB). "data" has 3 columns of about 680000 elements each, whereas "data1" has 3 columns of 33000000 elements each. When I run the code, I get just "Killed: 9" after some 5 minutes of processing. If this... | [
"Most likely kernel kills it because your script consumes too much of memory.\nYou need to take different approach and try to minimize size of data in memory. \nYou may also find this question useful: Very large matrices using Python and NumPy\nIn the following code snippet I tried to avoid loading huge data1.csv i... | [
12,
1,
1,
0,
0
] | [] | [] | [
"csv",
"dictionary",
"python"
] | stackoverflow_0034268471_csv_dictionary_python.txt |
Q:
nested for loop repeets my code is there a way to not do this?
i've recently started to learn programming and I'm following a course and have some code that I don't know how to fix if anyone can help that would be great :) its meant to be a decoder for the vigenere cipher
def vigenere(message,keyword):
alphabe... | nested for loop repeets my code is there a way to not do this? | i've recently started to learn programming and I'm following a course and have some code that I don't know how to fix if anyone can help that would be great :) its meant to be a decoder for the vigenere cipher
def vigenere(message,keyword):
alphabet = "abcdefghijklmnopqrstuvwxyz"
new_message = ""
punctuatio... | [
"I'm pleasantly surprised to know that I remember how Vigenere ciphers work from that one time I got into cryptography 15 years ago. Here's a working version of your code, where I did my best to make minimal changes.\ndef vigenere(message,keyword):\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n new_message = \... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074132287_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.