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:
Python Requests hanging when cURL is working just fine
I'm experiencing a strange issue where Python post Requests are hanging, while cURL post requests are working just fine. I'm making a request to the NIH Reporter API.
Here's the Python code that keeps hanging:
headers = {
"accept": "application/json",
... | Python Requests hanging when cURL is working just fine | I'm experiencing a strange issue where Python post Requests are hanging, while cURL post requests are working just fine. I'm making a request to the NIH Reporter API.
Here's the Python code that keeps hanging:
headers = {
"accept": "application/json",
"Content-Type": "application/json"
}
data = {
"criteria"... | [] | [] | [
"str(data) is not the same as converting it to json. You need to use data=json.dumps(data) or use json=data. Using the latter will also add the \"Content-Type\": \"application/json\" header for you, so you could skip that.\n"
] | [
-1
] | [
"curl",
"post",
"python",
"python_requests"
] | stackoverflow_0074342070_curl_post_python_python_requests.txt |
Q:
Can't combine two df
I have two df,
dataset2:
0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ... c11 c12 c13 c14 c15 c16 c17 c18 c19 c20
0 s1 5 4 4 5 4 4 4 4 4 ... 4 4 3 3 4 3 4 4 3 3
1 s2 3 4 3 4 4 5 3 5 3 ... 5 3 3 2 3 3 3 5 5 1
2 s3 4... | Can't combine two df | I have two df,
dataset2:
0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ... c11 c12 c13 c14 c15 c16 c17 c18 c19 c20
0 s1 5 4 4 5 4 4 4 4 4 ... 4 4 3 3 4 3 4 4 3 3
1 s2 3 4 3 4 4 5 3 5 3 ... 5 3 3 2 3 3 3 5 5 1
2 s3 4 4 5 5 4 4 4 ... | [
"Your issue is likely caused by a single level MultiIndex in the second DataFrame.\nHere is an example:\ndf = pd.DataFrame([[1, 2]], columns=['A', 'B'])\ndf2 = pd.DataFrame([[3, 4]], columns=pd.MultiIndex.from_arrays([['A', 'B']]))\n\npd.concat([df, df2])\n\n# A B (A,) (B,)\n# 0 1.0 2.0 NaN NaN\n# 0... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"nan",
"pandas",
"python"
] | stackoverflow_0074341621_dataframe_nan_pandas_python.txt |
Q:
Python list comprehension when creating a list
I'm trying to generate a list of random numbers. I thought this would be a good time to use list comprehension to shorten the code. The only problem is that now I have this unused "i" variable. Is there a way to write it without needing that variable, or should I not ... | Python list comprehension when creating a list | I'm trying to generate a list of random numbers. I thought this would be a good time to use list comprehension to shorten the code. The only problem is that now I have this unused "i" variable. Is there a way to write it without needing that variable, or should I not worry about it too much?
int_list = [random.randrang... | [
"You can use the _ instead which acts like a placeholder for variables you don't need either in loops\nint_list = [random.randrange(0, 50) for _ in range(10)]\n\ndef print_hello():\n print(\"Hello\")\n\nfor _ in range(10): # we don't need the value of \"range(10)\" in \n print_hello # each iteration.\n ... | [
3,
0
] | [] | [] | [
"python",
"variable_assignment"
] | stackoverflow_0074341964_python_variable_assignment.txt |
Q:
String to Integer in Django Template
I have rendering one string in django template but in django template, I want to convert it into integer. I have tried many thing like |add:to_int but it doesn't work.
A:
@Vaibhav Mishra,
Does it work for you? https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#add... | String to Integer in Django Template | I have rendering one string in django template but in django template, I want to convert it into integer. I have tried many thing like |add:to_int but it doesn't work.
| [
"@Vaibhav Mishra, \nDoes it work for you? https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#add\nLike: {% value|add:\"0\" %}\nIf it does not work for you: then create a custom template filter and register it:\nYOUR_APP_FOLDER/\n__init__.py\nmodels.py\ntemplatetags/\n __init__.py\n your_app_name_e... | [
2,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0059464995_django_django_templates_python.txt |
Q:
pandas groupby and return a series of one column
I have a dataframe like below
df = pd.DataFrame({'subject_id':[1,1,1,1,1,1,1,2,2,2,2,2],
'time_1' :['2017-04-03 12:35:00','2017-04-03 12:50:00','2018-04-05 12:59:00','2018-05-04 13:14:00','2017-05-05 13:37:00','2018-07-06 13:39:00','2018-07-08 11:... | pandas groupby and return a series of one column | I have a dataframe like below
df = pd.DataFrame({'subject_id':[1,1,1,1,1,1,1,2,2,2,2,2],
'time_1' :['2017-04-03 12:35:00','2017-04-03 12:50:00','2018-04-05 12:59:00','2018-05-04 13:14:00','2017-05-05 13:37:00','2018-07-06 13:39:00','2018-07-08 11:30:00','2017-04-08 16:00:00','2019-04-09 22:00:00','20... | [
"if you want to get array without index\nuse values attribute :\ndf.groupby(['subject_id',pd.Grouper(key='time_1', freq='3M')])['Prod_id'].nunique().values\n\noutput:\narray([2, 1, 1, 3, 2, 1, 2], dtype=int64)\n\n\nif you want to get range index series\nuse reset_index(drop=True):\ndf.groupby(['subject_id',pd.Group... | [
1,
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python",
"series"
] | stackoverflow_0074342102_dataframe_group_by_pandas_python_series.txt |
Q:
PyautoGUI- How to use If - Else with pyautogui.locateCenterOnScreen
Essentially I want my Python script to perform this...
x = True
if x == True:
print('Congratulations, you won!')
else:
print('I'm sorry but you lost.')
with this...
a, b = pyautogui.locateCenterOnScreen('~/home/file_01.png', region=(1065... | PyautoGUI- How to use If - Else with pyautogui.locateCenterOnScreen | Essentially I want my Python script to perform this...
x = True
if x == True:
print('Congratulations, you won!')
else:
print('I'm sorry but you lost.')
with this...
a, b = pyautogui.locateCenterOnScreen('~/home/file_01.png', region=(1065,250,385,700), confidence=0.9)
In other words, how can I have my script ... | [
"You could first check if ~/home/file_01.png exists before executing your statement, like so:\nimport os\n \nif os.path.exists(\"~/home/file_01.png\"):\n a, b = pyautogui.locateCenterOnScreen(\"~/home/file_01.png\", region=(1065,250,385,700), confidence=0.9)\n\n",
"import pyautogui\n\ntry:\n a, b = pyaut... | [
2,
1
] | [] | [] | [
"pyautogui",
"python"
] | stackoverflow_0069450752_pyautogui_python.txt |
Q:
How to combine and load data in django like this?
this is my models
class model1(models.Model):
name = models.charField()
class model2(models.Model):
model1 = models.Foriegnkey(model1)
id = models.IntegerField(primarykey=True)
title = models.charFiled()
I wanted some thing like this
{"model_name1... | How to combine and load data in django like this? | this is my models
class model1(models.Model):
name = models.charField()
class model2(models.Model):
model1 = models.Foriegnkey(model1)
id = models.IntegerField(primarykey=True)
title = models.charFiled()
I wanted some thing like this
{"model_name1":[{"id":1,"title":"title1"},{"id":2,"title":"title2"}]... | [
"[\n {\n \"model\": \"app_name.model_name1\",\n \"fields\": { \"title\": \"title1\" }\n },\n {\n \"model\": \"app_name.model_name1\",\n \"fields\": { \"title\": \"title2\" }\n },\n {\n \"model\": \"app_name.model_name2\",\n \"fields\": { \n \"title... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_views",
"python",
"python_3.8"
] | stackoverflow_0074341074_django_django_rest_framework_django_views_python_python_3.8.txt |
Q:
How to end a regular expression when one of several possible phrases are found?
I basically know nothing about regex but with the help of Google I'm attempting to use it to create an address parser that only extracts the street number and name (ex. 123 Random Boulevard) from a string of text (ex. "Hey I live at 12... | How to end a regular expression when one of several possible phrases are found? |
I basically know nothing about regex but with the help of Google I'm attempting to use it to create an address parser that only extracts the street number and name (ex. 123 Random Boulevard) from a string of text (ex. "Hey I live at 123 Random Boulevard if you were wondering". To do this, I created a list of words tha... | [
"What you want to do is separate the words you want to search for with pipe ('|') characters and place them inside a set of parens. Here's how to do that with a list of valid street types:\nimport re\n\nstreet_types = ['Way', 'Ave', 'Rd', 'Blvd', 'St.', 'Pl.', 'Dr.', 'Cir.', 'Ln', 'Ct', 'Hwy', 'Pkwy', 'Plaza',\n ... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074342210_python_regex.txt |
Q:
Error when installing mpi4py
I'm trying to install mpi4py using pip install mpi4py, but I'm getting the following error:
error: Cannot find 'mpi.h' header. Check your configuration!!!
Earlier in the same error report I have,
clang: error: linker command failed with exit code 1 (use -v to see invocation)
What... | Error when installing mpi4py | I'm trying to install mpi4py using pip install mpi4py, but I'm getting the following error:
error: Cannot find 'mpi.h' header. Check your configuration!!!
Earlier in the same error report I have,
clang: error: linker command failed with exit code 1 (use -v to see invocation)
What might the problem be?
Thanks!
| [
"As the error says, there are libraries missing. I solved it by installing libopenmpi-dev package\nsudo apt-get install libopenmpi-dev\n\nand then installed the mpi4py using pip\npip install mpi4py\n\n",
"I met with the similar problem and fixed this by firstly \nbrew install mpich\n\nAnd then \npip install mpi4p... | [
51,
37,
12,
8,
5,
1,
1,
0
] | [
"first post here and new to python , sorry if im off topic. \ni finally installed mpi4py \n1) by downloading the right version from here https://www.lfd.uci.edu/~gohlke/pythonlibs/#mpi4py \n2) open cmd ,change directory to where the downloaded file is \n3) pip install some-package.whl ( How do I install a... | [
-3
] | [
"installation",
"macos",
"mpi",
"python"
] | stackoverflow_0028440834_installation_macos_mpi_python.txt |
Q:
How to check if all elements in a list are whole numbers
If I have a list such as :
List = [12,6,3,5,1.2,5.5]
Is there a way I can check if all the numbers are whole numbers? I tried something like
def isWhole(d):
if (d%1 == 0 ) : for z in List return true.
That is obviously terribly wrong. What can I do?
A:... | How to check if all elements in a list are whole numbers | If I have a list such as :
List = [12,6,3,5,1.2,5.5]
Is there a way I can check if all the numbers are whole numbers? I tried something like
def isWhole(d):
if (d%1 == 0 ) : for z in List return true.
That is obviously terribly wrong. What can I do?
| [
"So you want integers and floats that are equal to integers?\ndef is_whole(d):\n \"\"\"Whether or not d is a whole number.\"\"\"\n return isinstance(d, int) or (isinstance(d, float) and d.is_integer())\n\nIn use:\n>>> for test in (1, 1.0, 1.1, \"1\"):\n print(repr(test), is_whole(test))\n\n\n1 True # integ... | [
6,
1,
1,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0026892185_list_python_python_3.x.txt |
Q:
Regex doesn't match \n in Python
I am using the following regex to extract email from message.
Hi Helpdesk, I'm reaching out to you to ask for help about an accident I had. Is this the correct contact for accidental damages?\nTommaso Massari\nData Scientist\ntommaso_massari@gmail.com
My code:
from_email = str(re.f... | Regex doesn't match \n in Python | I am using the following regex to extract email from message.
Hi Helpdesk, I'm reaching out to you to ask for help about an accident I had. Is this the correct contact for accidental damages?\nTommaso Massari\nData Scientist\ntommaso_massari@gmail.com
My code:
from_email = str(re.findall('\s*[a-zA-Z]*.*\s*[\\n]([a-zA-Z... | [] | [] | [
"You're looking for the DOTALL flag.\nhttps://docs.python.org/3/library/re.html#re.DOTALL\nAlso, sometimes the MULTILINE flag\nis relevant for text containing newlines.\n"
] | [
-1
] | [
"newline",
"python",
"regex"
] | stackoverflow_0074342368_newline_python_regex.txt |
Q:
adding a relative value per group in python
I have a dataframe
df =pd. DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'two', 'three', 'three', 'four', 'five'],
'C' : [2,3,4,9,12,12,17,13]})
I would like to add a new colum... | adding a relative value per group in python | I have a dataframe
df =pd. DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'two', 'three', 'three', 'four', 'five'],
'C' : [2,3,4,9,12,12,17,13]})
I would like to add a new column New, equal to C value/ C value where B= 'one' p... | [
"First, set up a new dataframe which just consists of rows where B == 'one':\ndf2 = df.loc[df['B'] == 'one',:]\n\nThen merge these two dataframes on the A column:\ndf.merge(df2, left_on = 'A', right_on = 'A')\n\n A B_x C_x B_y C_y\n0 foo one 2 one 2\n1 foo two 4 one 2\n2 foo three ... | [
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074342105_pandas_python.txt |
Q:
ImportError: cannot import name 'regression_report' from 'sklearn.metrics'
3 from sklearn.metrics import regression_report,confusion_matrix
4 print(confusion_matrix(y_train,predict_train))
5 print(Regression_report(y_train,predict_train))
ImportError: cannot import name 'regression_report' from 'skle... | ImportError: cannot import name 'regression_report' from 'sklearn.metrics' | 3 from sklearn.metrics import regression_report,confusion_matrix
4 print(confusion_matrix(y_train,predict_train))
5 print(Regression_report(y_train,predict_train))
ImportError: cannot import name 'regression_report' from 'sklearn.metrics' (C:\Users\charl\Anaconda\lib\site-packages\sklearn\metrics\__init__... | [
"May be you are looking for classification_report\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_train, predict_train))\n\n"
] | [
0
] | [] | [] | [
"importerror",
"python",
"scikit_learn"
] | stackoverflow_0074341271_importerror_python_scikit_learn.txt |
Q:
pandas: How do I enforce that die faces of type np.int8 stored in the index of a pandas data frame remain of type np.int8?
I create a numpy array of die faces of type np.int8. I create a pandas data frame with an index of those die faces and a weights column of ones. I try to set the type of the die faces in the i... | pandas: How do I enforce that die faces of type np.int8 stored in the index of a pandas data frame remain of type np.int8? | I create a numpy array of die faces of type np.int8. I create a pandas data frame with an index of those die faces and a weights column of ones. I try to set the type of the die faces in the index to np.int8. The first element of the index is of type np.int64.
import numpy as np
import pandas as pd
array_of_die_faces =... | [
"This is currently not supported. You cannot convert your index to int8:\ndata_frame_of_faces_and_weights.index.astype(np.int8)\n\nOr\npd.Index(array_of_die_faces, dtype=np.int8)\n\nboth result in:\nInt64Index([1, 2, 3, 4], dtype='int64')\n\nThere is a plan to remove Int64Index to replace it with NumericIndex:\n\nD... | [
2
] | [] | [] | [
"numpy",
"pandas",
"python",
"types"
] | stackoverflow_0074341881_numpy_pandas_python_types.txt |
Q:
How to get POSTed JSON in Flask?
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the POST with the Postman Chrome extension, and the JSON I POST is simply {"text":"lalala"}. I try to read the JSON using the following method:
@app.route('/api/add_message/<uuid>', met... | How to get POSTed JSON in Flask? | I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the POST with the Postman Chrome extension, and the JSON I POST is simply {"text":"lalala"}. I try to read the JSON using the following method:
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(... | [
"First of all, the .json attribute is a property that delegates to the request.get_json() method, which documents why you see None here. \nYou need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None otherwise. See... | [
605,
180,
92,
32,
16,
11,
10,
5,
1,
1,
0,
0
] | [
"Try to set force attribute as True in get_json() method to resolve this issue.\nrequest.get_json(force = True)\n\n"
] | [
-1
] | [
"flask",
"json",
"post",
"python"
] | stackoverflow_0020001229_flask_json_post_python.txt |
Q:
Setting maximum number of workers in Dask map function
I have a Dask process that triggers 100 workers with a map function:
worker_args = .... # array with 100 elements with worker parameters
futures = client.map(function_in_worker, worker_args)
worker_responses = client.gather(futures)
I use docker where each... | Setting maximum number of workers in Dask map function | I have a Dask process that triggers 100 workers with a map function:
worker_args = .... # array with 100 elements with worker parameters
futures = client.map(function_in_worker, worker_args)
worker_responses = client.gather(futures)
I use docker where each worker is a container. I have configured docker to spawn 20... | [
"dask does not dynamically adjust worker resources depending on how many workers are idle. In the example you provided, once 20 workers are initiated, if only 5 workers are used, then they will not be allocated the resources from the remaining 15 workers that are idle.\nIf that's acceptable (e.g. because the idle r... | [
1
] | [] | [] | [
"dask",
"dask_dataframe",
"dask_delayed",
"dask_distributed",
"python"
] | stackoverflow_0074304427_dask_dask_dataframe_dask_delayed_dask_distributed_python.txt |
Q:
How to handle non-generic errors in python?
I have a loop that I run via the statement:
os.system('python3 wrapper.py') which generates some files.
And every so often it hits an error such as this:
pybullet.error: Cannot load URDF file.
Error: InMemoryFile::~InMemoryFileIO (numAllocs 1 numFrees 2
This message is ... | How to handle non-generic errors in python? | I have a loop that I run via the statement:
os.system('python3 wrapper.py') which generates some files.
And every so often it hits an error such as this:
pybullet.error: Cannot load URDF file.
Error: InMemoryFile::~InMemoryFileIO (numAllocs 1 numFrees 2
This message is printed to the terminal. I would like to know how... | [
"python3 file.py > outputLog.txt\nLog the output of your file to a .txt file, and then you can read through it. You can conditionally re-run your wrapper if the non-generic error statements are in outputLog.txt.\n"
] | [
0
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0074342311_error_handling_python.txt |
Q:
Group and create three new columns by condition [Low, Hit, High]
I have a large dataset (~5 Mio rows) with results from a Machine Learning training. Now I want to check to see if the results hit the "target range" or not. Lets say this range contains all values between -0.25 and +0.25. If it's inside this range, i... | Group and create three new columns by condition [Low, Hit, High] | I have a large dataset (~5 Mio rows) with results from a Machine Learning training. Now I want to check to see if the results hit the "target range" or not. Lets say this range contains all values between -0.25 and +0.25. If it's inside this range, it's a Hit, if it's below Low and on the other side High.
I now would c... | [
"You could use cut to define the groups and pivot_table to reshape:\n(df.assign(group=pd.cut(df['Value'],\n [float('-inf'), -0.25, 0.25, float('inf')],\n labels=['Low', 'Hit', 'High']))\n .pivot_table(index='Type', columns='group', values='Value', aggfunc='count')\n ... | [
11,
4,
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0071068392_pandas_python.txt |
Q:
Python - Convert CSV to JSON based on headers dynamically
I am trying to convert a python dataframe to Json. Below is my csv format
policyID|Name | Description | Contact_Telephone | Contact_Email |
--------|-----| ------------|-------------------|---------------|
1221 |ABC | New Policy | 1234567890 | a... | Python - Convert CSV to JSON based on headers dynamically | I am trying to convert a python dataframe to Json. Below is my csv format
policyID|Name | Description | Contact_Telephone | Contact_Email |
--------|-----| ------------|-------------------|---------------|
1221 |ABC | New Policy | 1234567890 | abc@mail.com |
1223 |DEF | Old Policy | 2341243324 ... | [
"First get all columns names without _ to MultiIndex by DataFrame.set_index, split columns names by _ to MultiIndex in columns and create dictionaries by convert all groups to dictionaries by DataFrame.to_dict with Series constructor, last convert df1 to final dictionary:\nprint (df)\n policyID Name Description ... | [
0
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074342549_json_pandas_python.txt |
Q:
Apply tf.gather row-wise to a tensor
I'd like to operate tf.gather separately to each row of a tensor, given that I have the required indices for each row. For example, if a tensor:
A = tf.constant([[2., 5., 12., 9., 0., 0., 3.],
[0., 12., 2., 0., 0., 0., 5.],
[0., 0., 10., 0., 4.... | Apply tf.gather row-wise to a tensor | I'd like to operate tf.gather separately to each row of a tensor, given that I have the required indices for each row. For example, if a tensor:
A = tf.constant([[2., 5., 12., 9., 0., 0., 3.],
[0., 12., 2., 0., 0., 0., 5.],
[0., 0., 10., 0., 4., 4., 3.]], dtype=tf.float32)
has indices... | [
"idxs need to be converted to full indices and then use tf.gather_nd:\nii = tf.cast(tf.range(idxs.shape[0])[...,None], tf.float32)*tf.ones(idxs.shape[1], dtype=tf.float32)\nindices = tf.stack([tf.cast(ii, tf.int32), idxs], axis=-1)\n\nusing,\ntf.gather_nd(A, indices)\n\n[[ 2., 5., 9., 3., 2., 2., 2.],\n [12.,... | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074342031_keras_python_tensorflow.txt |
Q:
How to fix: TypeError: lmplot() got multiple values for argument 'data'
I am trying to plot with seaborn.
Using:
df=pd.read_csv("breast-cancer.data.txt",na_values=['?'])
df.drop(["id"],axis=1,inplace=True)
df["label"].replace(2,0,inplace=True)
df["label"].replace(4,1,inplace=True)
df.dropna(inplace=True)
full_dat... | How to fix: TypeError: lmplot() got multiple values for argument 'data' | I am trying to plot with seaborn.
Using:
df=pd.read_csv("breast-cancer.data.txt",na_values=['?'])
df.drop(["id"],axis=1,inplace=True)
df["label"].replace(2,0,inplace=True)
df["label"].replace(4,1,inplace=True)
df.dropna(inplace=True)
full_data=df.astype(float).values.tolist()
df.head()
for i in range(1,10):
sns.l... | [
"The first argument to lmplot is data.\nIn this call, the third argument is also data:\nsns.lmplot(str('x'+str(i)), 'label', data=df, fit_reg=False)\n\nSo, data is given twice, which is wrong.\n"
] | [
1
] | [] | [] | [
"jupyter_notebook",
"python",
"seaborn"
] | stackoverflow_0074342437_jupyter_notebook_python_seaborn.txt |
Q:
What is spacy spangroup. When and How do we use it? Will it help in overlapping spans?
I've used the code below to create spans using spacy.
from collections import Counter
from spacy.tokens import DocBin
def make_spans(lst):
"""
Split list of numbers into a list of (start,end) tuples,
e.g. [1,2,3,4,1... | What is spacy spangroup. When and How do we use it? Will it help in overlapping spans? | I've used the code below to create spans using spacy.
from collections import Counter
from spacy.tokens import DocBin
def make_spans(lst):
"""
Split list of numbers into a list of (start,end) tuples,
e.g. [1,2,3,4,10,11,12] of indexes becomes [(1,5), (10,13)] (exclusive end index)
"""
start = None... | [
"A SpanGroup is basically just a list of Spans - there's a little more to it, but not much. You really shouldn't have to think about the SpanGroups in particular.\nEntities on a Doc are specifically defined as a list of non-overlapping spans. If you need overlapping spans, then yes, you can save them in a SpanGroup... | [
1
] | [] | [] | [
"python",
"spacy",
"spacy_3",
"spacy_transformers"
] | stackoverflow_0074325620_python_spacy_spacy_3_spacy_transformers.txt |
Q:
Why do I keep coming up with an error at the end of my code?
So when inputting my third elif variable in my main function, my other functions don't work. My question, is what's stopping it. Lines 123, 124, 125, keep receiving the "UnboundLocalError: totalcost referenced before assignement"
`
def welcome():
pri... | Why do I keep coming up with an error at the end of my code? | So when inputting my third elif variable in my main function, my other functions don't work. My question, is what's stopping it. Lines 123, 124, 125, keep receiving the "UnboundLocalError: totalcost referenced before assignement"
`
def welcome():
print("Hello and Welcome Super Maids")
def LC (a , b):
totalco... | [
"So I ran your code and I got an error on line 129 and 122 and I think I figured out what the error problem is.\nI think you might have an error with not globalizing the variable so try doing:\nglobal totalcost\n\nfor each of the variables or something like that. Good luck!\n",
"You have a typo in main():\nelif Y... | [
0,
0
] | [] | [] | [
"function",
"python",
"return"
] | stackoverflow_0074342555_function_python_return.txt |
Q:
How do I determine the number of files that contain a particular word using numpy?
I have a group of files each with containing a letter and a number. (A4, for example). Each file only either has A or B before the number and I want to know how to determine the number of files that have an A in them.
This is what I... | How do I determine the number of files that contain a particular word using numpy? | I have a group of files each with containing a letter and a number. (A4, for example). Each file only either has A or B before the number and I want to know how to determine the number of files that have an A in them.
This is what I've done so far. The output looks like this:
1
0
0
1
1
0.. ect.
import numpy as np
file... | [
"I don't think you would need numpy for this scenario and also you should define the variable number outside the loop so that you can do the arthimetic properly. Since you have defined the variable inside the loop it redefines itself as 0 for each file.\nnumber = 0\nfor....:\n with open(filename,'r') as file:\n ... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074342434_python_python_3.x.txt |
Q:
Read Last Row of CSV file from FTP
I have a csv file sitting in an FTP Server. I am able to download the file completely using the ftplib in python, but it is like extra compute and internet burden for me.
My main concern is to read the last line only, from the csv file. Any help would be really appreciated.
Thank... | Read Last Row of CSV file from FTP | I have a csv file sitting in an FTP Server. I am able to download the file completely using the ftplib in python, but it is like extra compute and internet burden for me.
My main concern is to read the last line only, from the csv file. Any help would be really appreciated.
Thanks!!!
| [
"You cannot read last line with FTP. There's no API for that. But you can read last several bytes of the file. Enough to be sure you have at least one complete (last) line.\nUse FTP.size to tell size of the file. Calculate your estimate of beginning of the last line based on that. And then when downloading, use res... | [
2
] | [] | [] | [
"ftp",
"ftp_client",
"ftp_server",
"ftplib",
"python"
] | stackoverflow_0074342468_ftp_ftp_client_ftp_server_ftplib_python.txt |
Q:
Why is Python giving the error cannot cvtColor missing src
I am creating an alarm system that when you press t it turns on the alarm and if too much movement is detected it will sound an alarm. When I press t to activate the alarm it gives this error:
frame_bw = cv2.cvtColor(frame = cv2.COLOR_BGR2GRAY)
cv2.error:... | Why is Python giving the error cannot cvtColor missing src | I am creating an alarm system that when you press t it turns on the alarm and if too much movement is detected it will sound an alarm. When I press t to activate the alarm it gives this error:
frame_bw = cv2.cvtColor(frame = cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'cvtCol... | [
"Please check this line:\nframe_bw = cv2.cvtColor(frame = cv2.COLOR_BGR2GRAY)\n\nIt should be:\nframe_bw = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n"
] | [
1
] | [] | [] | [
"imutils",
"opencv",
"python"
] | stackoverflow_0074337747_imutils_opencv_python.txt |
Q:
Pandas resample based on string like PeriodIndex
I have a dataframe like as below
df = pd.DataFrame({'subject_id':[1,1,1,1,1,2,2,2,2,2],
'qtr_info' :['2017Q1','2017Q3','2017Q4','2018Q1','2018Q4','2017Q1','2017Q4','2018Q2','2018Q4','2019Q1'],
'val' :[5,5,5,5,1,6,5,5,8,3],
... | Pandas resample based on string like PeriodIndex | I have a dataframe like as below
df = pd.DataFrame({'subject_id':[1,1,1,1,1,2,2,2,2,2],
'qtr_info' :['2017Q1','2017Q3','2017Q4','2018Q1','2018Q4','2017Q1','2017Q4','2018Q2','2018Q4','2019Q1'],
'val' :[5,5,5,5,1,6,5,5,8,3],
'Prod_id':['A','B','C','A','E','Q','G','... | [
"Create PeriodIndex first and for resample use Resampler.agg with dictionary, for replace missing values by means use Series.fillna with GroupBy.transform:\ndf_time['qtr_info'] = pd.PeriodIndex(df_time['qtr_info'], freq='Q')\ndf = (df_time.set_index('qtr_info')\n .groupby('subject_id')\n .re... | [
4
] | [] | [] | [
"dataframe",
"fillna",
"pandas",
"python",
"time_series"
] | stackoverflow_0074342681_dataframe_fillna_pandas_python_time_series.txt |
Q:
Is there a way to split the list in a row ?(Python pandas)
here is a code for my data frame's grouping:
import pandas as pd
#create a list
product_list = ["bag","necklece"]
sold__commentlist = [['nice to use',"bad"],["good",'can be improved']]
#dataframe
data = pd.DataFrame (columns = ['product','sold_comment'])... | Is there a way to split the list in a row ?(Python pandas) | here is a code for my data frame's grouping:
import pandas as pd
#create a list
product_list = ["bag","necklece"]
sold__commentlist = [['nice to use',"bad"],["good",'can be improved']]
#dataframe
data = pd.DataFrame (columns = ['product','sold_comment'])
#plug the list into the dataframe
data['product'] = product_li... | [
"Try something like this:\nimport pandas as pd\n\n#create a list\nproduct_list = [\"bag\",\"necklece\"]\nsold__commentlist = [['nice to use',\"bad\"],[\"good\",'can be improved']]\n\n#dataframe\ndata = pd.DataFrame (columns = ['product','sold_comment'])\n\n#plug the list into the dataframe\ndata['product'] = produc... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074342688_pandas_python.txt |
Q:
Python Sqlparser - Replace :: with cast()
I am trying to create a script which will convert Redshift SQL into SparkSQL. One specific conversion is giving me troubles - converting '::' into cast() function. Sql parser seems to mark '::' as punctuation, and doesn't parse out the entire statement that the double colo... | Python Sqlparser - Replace :: with cast() | I am trying to create a script which will convert Redshift SQL into SparkSQL. One specific conversion is giving me troubles - converting '::' into cast() function. Sql parser seems to mark '::' as punctuation, and doesn't parse out the entire statement that the double colon is applying to. Could use some suggestions!
E... | [
"You can use sqlglot to do this.\n>>> from sqlglot import transpile\n>>> transpile(\"select colA::numeric(18, 2) as colA from tableA\", read=\"redshift\", write=\"spark\")[0]\n'SELECT CAST(colA AS DECIMAL(18, 2)) AS colA FROM tableA'\n\n"
] | [
0
] | [] | [] | [
"python",
"sql_parser",
"string"
] | stackoverflow_0073674519_python_sql_parser_string.txt |
Q:
Python scripts work great when testing but not combined. Speech Controlled Assistant using Amazon Polly
I have a voice controlled bot I am creating to control my PC. I recently switched to Amazon Polly from Windows built in STT and started to notice that some of the functions would have a delay between the functio... | Python scripts work great when testing but not combined. Speech Controlled Assistant using Amazon Polly | I have a voice controlled bot I am creating to control my PC. I recently switched to Amazon Polly from Windows built in STT and started to notice that some of the functions would have a delay between the function being triggered and returning. I did notice that all the functions work great without any delay if I bypass... | [
"I have not tested it, but while True: pass would have consumed a significant amount of CPU. This may explain why everything else is so slow. Instead, ensure to include a pause in such a loop to give the CPU a breather. Example:\nwhile True:\n time.sleep(1)\n\nAlso if the Recognizer is listening in the backgroun... | [
1
] | [] | [] | [
"amazon_polly",
"amazon_web_services",
"delay",
"lag",
"python"
] | stackoverflow_0074342455_amazon_polly_amazon_web_services_delay_lag_python.txt |
Q:
pyautogui.locateOnScreen and pyautogui.position gives different results
I am using pyautogui 0.9.53 version with python 3.7.8.
When I try to locate an image using:
pyautogui.locateOnScreen(img_path)
I get the result:
Box(left=538, top=701, width=718, height=1280)
but when I put my cursor on the top left of the im... | pyautogui.locateOnScreen and pyautogui.position gives different results | I am using pyautogui 0.9.53 version with python 3.7.8.
When I try to locate an image using:
pyautogui.locateOnScreen(img_path)
I get the result:
Box(left=538, top=701, width=718, height=1280)
but when I put my cursor on the top left of the image on screen, and use the command:
pyautogui.position()
I get the result:
P... | [
"Found the answer here:\nhttps://github.com/asweigart/pyautogui/issues/735\nApparently, the retina screen on mac os is multiplying the pixels by 2.\nThe solution is to divide the result by 2\n"
] | [
0
] | [] | [] | [
"pyautogui",
"python",
"python_3.x"
] | stackoverflow_0074338130_pyautogui_python_python_3.x.txt |
Q:
Can I extend a generic type in Python?
This is what I want to do:
from typing import TypeVar, Generic
T = TypeVar('T')
class Parent:
def __init__(self) -> None:
print("Parent's constructor called")
self.value = 2
def get(self):
return self.value
class Child(T):
def __init_... | Can I extend a generic type in Python? | This is what I want to do:
from typing import TypeVar, Generic
T = TypeVar('T')
class Parent:
def __init__(self) -> None:
print("Parent's constructor called")
self.value = 2
def get(self):
return self.value
class Child(T):
def __init__(self):
print("Child's constructor ... | [
"Python has multiple inheritance for this purpose.\nclass Child(Parent, Generic[T]):\n\nThe Generic is only a type-hint, it doesn't affect the interpreter behaviour, you still have to inherit Parent.\nEdit: there's also composition\nclass Child(Generic[T]):\n def __init__(self, parent: T):\n print(\"Child... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074342440_python.txt |
Q:
What am I missing for determining the winner by votes?
I'm trying to think of a way to make functions that determine the winner of an election by most votes, as well as a function that determines a winner-takes-all rule.
My code is as follows:
_base_dict = {}
def add_state(name: str, votes: dict[str, int]) ->... | What am I missing for determining the winner by votes? | I'm trying to think of a way to make functions that determine the winner of an election by most votes, as well as a function that determines a winner-takes-all rule.
My code is as follows:
_base_dict = {}
def add_state(name: str, votes: dict[str, int]) -> None:
global _base_dict
for name, votes in _base_d... | [
"I think this fixes it:\nFirst off, I suggest _base_dict needs to be a defaultdict - so you can add keys to it that it doesn't already have. Like so:\nfrom collections import defaultdict\n\n_base_dict = defaultdict(lambda: defaultdict(lambda: 0))\n\nDefined thus, every time you invoke _base_dict[<some state name>],... | [
0,
0
] | [] | [] | [
"dictionary",
"global",
"python",
"python_3.x"
] | stackoverflow_0074341855_dictionary_global_python_python_3.x.txt |
Q:
How to cache SerializerMethodField result
I have the below serializer:
class OrderItemResponseSerializer(serializers.ModelSerializer):
prepack_qty = serializers.SerializerMethodField()
product_description = serializers.SerializerMethodField()
class Meta:
model = OrderItem
fields = (
... | How to cache SerializerMethodField result | I have the below serializer:
class OrderItemResponseSerializer(serializers.ModelSerializer):
prepack_qty = serializers.SerializerMethodField()
product_description = serializers.SerializerMethodField()
class Meta:
model = OrderItem
fields = (
"product",
"qty_ordered",... | [
"Well, first of all, I should say that what you have implemented in this piece of code below:\n ...\n @cached_property\n def item_product_description(self):\n return self.product.product_description\n\nAnd using @cached_property alone doesn't cache the data for you, you just created a property in th... | [
1,
0
] | [] | [] | [
"django",
"django_orm",
"django_rest_framework",
"python"
] | stackoverflow_0074172200_django_django_orm_django_rest_framework_python.txt |
Q:
Convert binary columns into columns with string values based on their column headers?
This is my dataset:
Dept
Cell culture
Bioinfo
Immunology
Trigonometry
Algebra
Microbio
Optics
Biotech
1
1
1
0
0
0
0
Biotech
1
0
1
0
0
0
0
Math
0
0
0
1
1
0
0
Biotech
0
0
0
0
0
1
0
Physics
0
0
0
0
0
0
1
This is how I want my... | Convert binary columns into columns with string values based on their column headers? | This is my dataset:
Dept
Cell culture
Bioinfo
Immunology
Trigonometry
Algebra
Microbio
Optics
Biotech
1
1
1
0
0
0
0
Biotech
1
0
1
0
0
0
0
Math
0
0
0
1
1
0
0
Biotech
0
0
0
0
0
1
0
Physics
0
0
0
0
0
0
1
This is how I want my result:
|Biotech|Cell culture|Bioinfo |Immunology|
|Biotech|Cell culture|Im... | [
"Convert column Dept to index and for values with 1 convert columns names to lists and then to new DataFrame:\ndf2 = df.set_index('Dept')\n\ncols = df2.columns.to_numpy()\ndf2 = pd.DataFrame([cols[m] for m in df2.eq(1).to_numpy()], index=df2.index)\nprint (df2)\n 0 1 2\nDept ... | [
1
] | [] | [] | [
"binary",
"dataframe",
"multiple_columns",
"pandas",
"python"
] | stackoverflow_0074342720_binary_dataframe_multiple_columns_pandas_python.txt |
Q:
(python) matplotlib.pyplot saving error to picture
python matplotlib.pyplot saving error to picture
tool: with CV2 4.6.0 on Ubuntu 22.04.1 LTS
Problem:
my code can output plt.imshow(image) but cannot plt.imsavesave
AttributeError: 'tuple' object has no attribute 'shape'
the .py script:
import numpy as np
impor... | (python) matplotlib.pyplot saving error to picture | python matplotlib.pyplot saving error to picture
tool: with CV2 4.6.0 on Ubuntu 22.04.1 LTS
Problem:
my code can output plt.imshow(image) but cannot plt.imsavesave
AttributeError: 'tuple' object has no attribute 'shape'
the .py script:
import numpy as np
import glob
import matplotlib.pyplot as plt
import skimage.... | [
"Use plt.imsave(\"output_remove_gray_area.png\", binary_mask, cmap=\"gray\") instead of saving aaa which is the return value of plt.imshow() and not your actual image.\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074314299_matplotlib_python.txt |
Q:
How to loop through and scrape data from collapsibles on a website using Selenium?
pretty beginner coder here but I am trying to scrape email addresses of tux rental places from this website (https://www.jimsformalwear.com/stores) using Selenium. The email addresses are displayed once the 'Details' link is clicked... | How to loop through and scrape data from collapsibles on a website using Selenium? | pretty beginner coder here but I am trying to scrape email addresses of tux rental places from this website (https://www.jimsformalwear.com/stores) using Selenium. The email addresses are displayed once the 'Details' link is clicked. I am able to loop through and click details under each stores' name but am only able t... | [
"A note on debugging: when using try...except, debugging is easier if you print the exception - something like\ntry:\n ### CODE THAT MIGHT RAISE EXCEPTION ###\nexcept Exception as err:\n print(str(err))\n ######### HANDLE EXCEPTION #########\n\nthat way, you might have a better idea of what went wrong.\... | [
1
] | [] | [] | [
"automation",
"beautifulsoup",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074342009_automation_beautifulsoup_python_selenium_web_scraping.txt |
Q:
print the unique values in every column in a pandas dataframe
I have a dataframe (df) and want to print the unique values from each column in the dataframe.
I need to substitute the variable (i) [column name] into the print statement
column_list = df.columns.values.tolist()
for column_name in column_list:
prin... | print the unique values in every column in a pandas dataframe | I have a dataframe (df) and want to print the unique values from each column in the dataframe.
I need to substitute the variable (i) [column name] into the print statement
column_list = df.columns.values.tolist()
for column_name in column_list:
print(df."[column_name]".unique()
Update
When I use this: I get "Unexp... | [
"It can be written more concisely like this:\nfor col in df:\n print(df[col].unique())\n\nGenerally, you can access a column of the DataFrame through indexing using the [] operator (e.g. df['col']), or through attribute (e.g. df.col).\nAttribute accessing makes the code a bit more concise when the target column ... | [
109,
19,
10,
5,
4,
3,
2,
1,
1,
0,
0,
0
] | [
"The best way to do that:\nSeries.unique()\n\nFor example students.age.unique() the output will be the different values that occurred in the age column of the students' data frame.\nTo get only the number of how many different values:\nSeries.nunique()\n\n"
] | [
-3
] | [
"for_loop",
"pandas",
"python"
] | stackoverflow_0027241253_for_loop_pandas_python.txt |
Q:
When using Tkinter, error: TclError: image "pyimage8" doesn't exist
I keep getting the error, TclError: image "pyimage8" doesn't exist.
It is strange, as the number increases every time I run it?
I'm running python using spyder, dunno whether this affects anything.
Here is my code:
#import tkinter
import Tkinter a... | When using Tkinter, error: TclError: image "pyimage8" doesn't exist | I keep getting the error, TclError: image "pyimage8" doesn't exist.
It is strange, as the number increases every time I run it?
I'm running python using spyder, dunno whether this affects anything.
Here is my code:
#import tkinter
import Tkinter as tk
homescreenImage = PhotoImage(file="Homescreen.gif")
#create a G... | [
"I found that my script would run once and then give me an error on subsequent runs. If I restarted the console, it would run again. I solved the problem by using the following code in the beginning of my script:\nimport sys\nif \"Tkinter\" not in sys.modules:\n from Tkinter import *\n\nIt works every time now.... | [
2,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"spyder",
"tkinter"
] | stackoverflow_0050012062_python_spyder_tkinter.txt |
Q:
Python -- Limits On Number of Imports?
I have 1000s of custom (compiled to '.so') modules that I'd like to use in python at the same time. Each such module is of size (100 [KB]) on average.
My question is, is there any limit on the number of imports in python? what are the consequences of many imports? (for exampl... | Python -- Limits On Number of Imports? | I have 1000s of custom (compiled to '.so') modules that I'd like to use in python at the same time. Each such module is of size (100 [KB]) on average.
My question is, is there any limit on the number of imports in python? what are the consequences of many imports? (for example, will this require a lot of memory)?
Can I... | [
"There's no Python limit on number of imports in a module. If there's a limit in any particular implementation, it's probably because of resource limits outside the Python interpreter.\n",
"The amount of memory consumed by a single imported module is going to be at least as big as the size of the module on disk. ... | [
10,
9,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006012022_python.txt |
Q:
Value error when converting json file into csv
I have json file something looks like as below and I want to convert this json file into csv file.
When I run the code, it gives me value error.
Can someone please let me know how to convert below json into csv?
[{"VESSEL_NO":"99999","SYSTEM_NAME":"ANEMOMETER","SYSTEM... | Value error when converting json file into csv | I have json file something looks like as below and I want to convert this json file into csv file.
When I run the code, it gives me value error.
Can someone please let me know how to convert below json into csv?
[{"VESSEL_NO":"99999","SYSTEM_NAME":"ANEMOMETER","SYSTEM_INSTANCE":"1","EVENT_TIME":"2022-03-05 00:00:00.000... | [
"read_json() is used to read JSON files:\nimport pandas as pd\n\ndf = pd.read_json(\"data.json\")\ndf.to_csv(\"data.csv\", index=False)\n\n",
"you can use json_normalize():\nimport json\nimport ast\n\nwith open ('your_json_file_path') as json_file:\n json = json.load(json_file)\n \ndf=pd.DataFrame(data={'a':js... | [
1,
0,
0
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074342823_json_pandas_python.txt |
Q:
How to insert specific dataframe column(s) into databse?
I need to insert a dataframe by column or columns into an SQLite database table. Adding fraction of dataframe columns.
VendorID
tpep_pickup_datetime
tpep_dropoff_datetime
passenger_count
1
2020-01-01 00:28:15
2020-01-01 00:33:03
1.0
1
2020-01-01 00:35:39
... | How to insert specific dataframe column(s) into databse? | I need to insert a dataframe by column or columns into an SQLite database table. Adding fraction of dataframe columns.
VendorID
tpep_pickup_datetime
tpep_dropoff_datetime
passenger_count
1
2020-01-01 00:28:15
2020-01-01 00:33:03
1.0
1
2020-01-01 00:35:39
2020-01-01 00:43:04
1.0
1
2020-01-01 00:47:41
2020-01... | [
"You do not do it like this at all. You use the Panda's to_sql feature. For a more detailed answer, you, of course, need to provide a proper question.\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"sql",
"sqlite"
] | stackoverflow_0074342391_pandas_python_sql_sqlite.txt |
Q:
Create list from nested list in dictionary
With below dictionary, I want to make a new single list with all directories:
nominated = {1931: ['Norman Taurog', 'Wesley Ruggles', 'Clarence Brown', 'Lewis Milestone', 'Josef Von Sternberg'],
1932: ['Frank Borzage', 'King Vidor', 'Josef Von Sternberg'],
... | Create list from nested list in dictionary | With below dictionary, I want to make a new single list with all directories:
nominated = {1931: ['Norman Taurog', 'Wesley Ruggles', 'Clarence Brown', 'Lewis Milestone', 'Josef Von Sternberg'],
1932: ['Frank Borzage', 'King Vidor', 'Josef Von Sternberg'],
1933: ['Frank Lloyd', 'Frank Capra', '... | [
"all_directors = [\n director for year, nominated_directors in nominated.items() \n for director in nominated_directors\n ]\n\nYou can just remove the list notation from attempt 1 and re-order the for loops in list comprehension.\n",
"The problem you have here is the order you are iterating over items.\n... | [
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074332890_python_python_3.x.txt |
Q:
How to check if a pip package exists in certain given custom index?
I've to check whether a package exists in the given index-url (authenticated) using python script.
For example:
I've to check if package package-1 exists in index https://mytestdomain.com/pypi/pypi/simple/
Is there any method to achieve this?
What... | How to check if a pip package exists in certain given custom index? | I've to check whether a package exists in the given index-url (authenticated) using python script.
For example:
I've to check if package package-1 exists in index https://mytestdomain.com/pypi/pypi/simple/
Is there any method to achieve this?
What I've tried?
I've tried the cli method, like configuring pip.conf with th... | [
"Use subprocess.run with the --no-deps and --dry-run options:\nimport subprocess, sys\n\ndef check_exists(package_name: str, index_url: str = \"https://pypi.org/simple\") -> bool:\n return not subprocess.run(\n [\n sys.executable,\n \"-m\",\n \"pip\",\n \"instal... | [
2,
0
] | [] | [] | [
"pip",
"pypi",
"python"
] | stackoverflow_0074327317_pip_pypi_python.txt |
Q:
iterate over multiple tables in HANA
I have 4-5 tables in my SAP HANA database. My requirement is to list all tables and iterate over each table and store each table data to individual csv files.
I want to perform these activity using python. I am using the hdbcli library for this.
Thank you.
A:
You can use the ... | iterate over multiple tables in HANA | I have 4-5 tables in my SAP HANA database. My requirement is to list all tables and iterate over each table and store each table data to individual csv files.
I want to perform these activity using python. I am using the hdbcli library for this.
Thank you.
| [
"You can use the collect() method of the hana-ml dataframe and subsequently export using Pandas to_csv(..) method.\nconnectionContext.table('my_table').collect().to_csv(..)\n\nFor this approach, you need to use hana-ml instead of hdbcli.\n"
] | [
1
] | [] | [] | [
"hana",
"python",
"python_3.x",
"sql"
] | stackoverflow_0074331517_hana_python_python_3.x_sql.txt |
Q:
Not able to used "Times New Roman" font in google colab
I'm using google colab, and I'm trying to use the "Times New Roman" font for my matplotlib plotting. since the ttf file in google colab is located in/usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf so what i did is downloaded the ttf file ... | Not able to used "Times New Roman" font in google colab | I'm using google colab, and I'm trying to use the "Times New Roman" font for my matplotlib plotting. since the ttf file in google colab is located in/usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf so what i did is downloaded the ttf file for "Times New Roman" from https://github.com/trishume/OpenTu... | [
"import matplotlib.pyplot as plt\nplt.rcParams['font.family'] = 'serif'\nplt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcParams['font.serif']\n\nI think this will work.\n",
"import matplotlib.pyplot as plt\nplt.rcParams['font.family'] = 'serif'\nplt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcPa... | [
5,
0
] | [] | [] | [
"fonts",
"google_colaboratory",
"matplotlib",
"python"
] | stackoverflow_0058207721_fonts_google_colaboratory_matplotlib_python.txt |
Q:
my excel sheet did not display result after webscrapping using selenium and export to excel
I would like to extract the serial number and and the expirydate from this link into excel sheet
https://www.dell.com/support/home/en-sg/product-support/servicetag/0-ZUQwbW14d28xZHZBYTZWNDdHVy80Zz090/overview
After watching... | my excel sheet did not display result after webscrapping using selenium and export to excel | I would like to extract the serial number and and the expirydate from this link into excel sheet
https://www.dell.com/support/home/en-sg/product-support/servicetag/0-ZUQwbW14d28xZHZBYTZWNDdHVy80Zz090/overview
After watching tutorial on how to extract using selenium and run the code on python (using pycharm) my excel sh... | [
"[I am unfamiliar with just passing a string as the first argument (by=\"xpath\" rather that By.XPATH); if it works for you, great, but otherwise you might want to check out the documentation.]\nThe xpaths for serialnumber and expirydate might be the issue. When I inspected the page, I saw that they were inside p t... | [
0
] | [] | [] | [
"excel",
"python",
"selenium",
"web_scraping",
"xpath"
] | stackoverflow_0074342077_excel_python_selenium_web_scraping_xpath.txt |
Q:
Add character to column based on text condition using pandas
I'm trying to do some data cleaning using pandas. Imagine I have a data frame which has a column call "Number" and contains data like: "1203.10", "4221","3452.11", etc. I want to add an "M" before the numbers, which have a point and a zero at the end. Fo... | Add character to column based on text condition using pandas | I'm trying to do some data cleaning using pandas. Imagine I have a data frame which has a column call "Number" and contains data like: "1203.10", "4221","3452.11", etc. I want to add an "M" before the numbers, which have a point and a zero at the end. For this example, it would be turning the "1203.10" into "M1203.10".... | [
"You can use boolean indexing:\npointzero = '[0-9]+[.][0-9]+[0]$'\nm = df.Number.str.match(pointzero)\n\ndf.loc[m, 'Number'] = 'M' + df.loc[m, 'Number']\n\nAlternatively, using str.replace and a slightly different regex:\npointzero = '([0-9]+[.][0-9]+[0]$)'\ndf['Number'] = df['Number'].str.replace(pointzero, r'M\\1... | [
2,
2
] | [] | [] | [
"database",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074343024_database_dataframe_pandas_python.txt |
Q:
The same structure as Recordtype in Python 3.9
I have the following recordtype
from recordtype import recordtype
sending_interval = datetime.timedelta(days = 1)
last_sent_time = datetime.datetime.now() - sending_interval
thermometer = recordtype('thermometer', 'sent, last_sent_time, name, group, where')
thermo... | The same structure as Recordtype in Python 3.9 | I have the following recordtype
from recordtype import recordtype
sending_interval = datetime.timedelta(days = 1)
last_sent_time = datetime.datetime.now() - sending_interval
thermometer = recordtype('thermometer', 'sent, last_sent_time, name, group, where')
thermometers = {
"29FF069605000009": th... | [
"Any reason you don't like a simple class for this?\n class thermometer:\n def __init__( sent, last_sent_time, name, group, where ):\n self.sent = sent\n self.last_sent_time = last_sent_time\n self.name = name\n self.group = group\n self.where... | [
1
] | [] | [] | [
"python",
"python_3.10",
"recordtype"
] | stackoverflow_0074342969_python_python_3.10_recordtype.txt |
Q:
Tkinter: Referencing child windows
Hi i have two tkinter classes:
note.py-opens a notepad editor and
cp.py-control panel where i can select apps ( like note.py and other future apps)
I have it so that the control panel can open and close the note.py in the menu of control panel. I was using subprocess to open the ... | Tkinter: Referencing child windows | Hi i have two tkinter classes:
note.py-opens a notepad editor and
cp.py-control panel where i can select apps ( like note.py and other future apps)
I have it so that the control panel can open and close the note.py in the menu of control panel. I was using subprocess to open the file then tracking the pids of the runni... | [
"To summarize the code below:\n\nI've created a list where I store the instance of my App1.\nI do this by access the master of the Toplevel\nI remove the instance of my list when the app gets destroyed\nI check the existence of the app by iterating over the list an check for the instance of the class\n\nI've left c... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074342670_python_tkinter.txt |
Q:
How to display images to match prediction data with a keras datagen?
My test_data (Used to feed into the CNN AI for predictions) is not showing the data I want properly. I have managed to only show data through a forloop (Which is commented out) but this only shows random images. I thought that I could trying choo... | How to display images to match prediction data with a keras datagen? |
My test_data (Used to feed into the CNN AI for predictions) is not showing the data I want properly. I have managed to only show data through a forloop (Which is commented out) but this only shows random images. I thought that I could trying choosing specific images to match with the predictions (Predictions are call... | [
"train_generator.flow_from_directory is not random you can name your sample to make them pick it up in order or sequences. The train_generator.flow_from_directory also attached class_name as folders name or custom value with its result too. ( I use this as the template for some data sources they accept train_genera... | [
0
] | [] | [] | [
"conv_neural_network",
"dataset",
"keras",
"python",
"tensorflow"
] | stackoverflow_0074341218_conv_neural_network_dataset_keras_python_tensorflow.txt |
Q:
Import CSV files to database by date
I have list of CSV files named by date like :
2020-01-01, 2020-01-02... 2020-01-31
I need to import them into an SQLite database in batch. My script:
file_name = '2020-01-{}.csv'
test = pd.concat([pd.read_csv(file_name.format(i)) for i in range(1, 9)])
test.to_sql('test', conn... | Import CSV files to database by date | I have list of CSV files named by date like :
2020-01-01, 2020-01-02... 2020-01-31
I need to import them into an SQLite database in batch. My script:
file_name = '2020-01-{}.csv'
test = pd.concat([pd.read_csv(file_name.format(i)) for i in range(1, 9)])
test.to_sql('test', conn, if_exists='append', index=False)
But I ... | [
"You can do this process by following the steps\n\nMake a list of all the files\nRun a loop and add them into db\n\nSo the working solution should be like\nimport pandas as pd\n\n\ndef read_csv_file(file_name) -> pd.DataFrame:\n \"\"\"Read csv file and return a dataframe\"\"\"\n df = pd.read_csv(file_name)\n ... | [
1
] | [] | [] | [
"pandas",
"python",
"sqlite"
] | stackoverflow_0074343103_pandas_python_sqlite.txt |
Q:
Assign value based on index from another array numpy
I have a indices array like this:
idx = np.array([3,4,1], [0,0,0], [1,4,1], [2,0,2]]
And an array of zeros A with shape 4x5
I would like to make all the indices in idx of A to be 1
For the above example, the final array should be:
[[0,1,0,1,1], # values at ind... | Assign value based on index from another array numpy | I have a indices array like this:
idx = np.array([3,4,1], [0,0,0], [1,4,1], [2,0,2]]
And an array of zeros A with shape 4x5
I would like to make all the indices in idx of A to be 1
For the above example, the final array should be:
[[0,1,0,1,1], # values at index 3,4,1 are 1
[1,0,0,0,0], # value at index 0 is 1
[0,... | [
"Use fancy indexing:\nA = np.zeros((4, 5), dtype=int)\n\nA[np.arange(len(idx))[:,None], idx] = 1\n\nOr numpy.put_along_axis:\nA = np.zeros((4, 5), dtype=int)\n\nnp.put_along_axis(A, idx, 1, axis=1)\n\nupdated A:\narray([[0, 1, 0, 1, 1],\n [1, 0, 0, 0, 0],\n [0, 1, 0, 0, 1],\n [1, 0, 1, 0, 0]])\n\n... | [
2
] | [] | [] | [
"arrays",
"indexing",
"numpy",
"python"
] | stackoverflow_0074343202_arrays_indexing_numpy_python.txt |
Q:
Use regex and pymongo for extracts documents create in 2014
I'm begginner to pymongo and i'd like find the count of the documents who have create in 2014 in 'update_date' and i'd like use the REGEX.
My code is :
exp = re.compile("[2][0][1][4]-[0-9][0-9]-[0-9][0-9]")
pprint(list(col.find({"update_date": exp}, {"upd... | Use regex and pymongo for extracts documents create in 2014 | I'm begginner to pymongo and i'd like find the count of the documents who have create in 2014 in 'update_date' and i'd like use the REGEX.
My code is :
exp = re.compile("[2][0][1][4]-[0-9][0-9]-[0-9][0-9]")
pprint(list(col.find({"update_date": exp}, {"update_date": 1})))
the result find all documents in 2014 but i'd l... | [
"I found the solution : a loop.\nexp = re.compile(\"[2][0][1][4]-[0-9][0-9]-[0-9][0-9]\")\n\n\ntst = col.find({\"update_date\": exp}, {\"update_date\": 1})\nli=[]\nfor i in tst:\n li.append(i)\nprint(len(li))\n\n"
] | [
0
] | [] | [] | [
"mongodb",
"pymongo",
"python",
"python_re",
"regex"
] | stackoverflow_0074335012_mongodb_pymongo_python_python_re_regex.txt |
Q:
How to count the occurrences of single items in a list of lists in descending order?
x=[['apple', 'banana', 'carrot'],
['apple', 'banana'],
['banana', 'carrot']]
I want the result to look like this:
dict = {'banana': 3,'apple': 2, 'carrot': 2}
A:
You can "flatten" your x, and then just count, while iterating o... | How to count the occurrences of single items in a list of lists in descending order? | x=[['apple', 'banana', 'carrot'],
['apple', 'banana'],
['banana', 'carrot']]
I want the result to look like this:
dict = {'banana': 3,'apple': 2, 'carrot': 2}
| [
"You can \"flatten\" your x, and then just count, while iterating over unique elements of the (flat) x:\nx = [['apple', 'banana', 'carrot'],\n ['apple', 'banana'],\n ['banana', 'carrot']]\n\nflat_x = [a for b in x for a in b]\nres = {a: sum(b == a for b in flat_x) for a in set(flat_x)}\nprint(res)\n# {'carrot... | [
2
] | [] | [] | [
"count",
"list",
"python"
] | stackoverflow_0074343227_count_list_python.txt |
Q:
Adding +1 to a URL whilst scraping
If I have a url called youtube.com/user/1/ and I want the number to incrament to youtube.com/user/2/
whilst scraping the whole page, how would I do so? I've been trying to think of some ways to do this but I can't seem to find anything?
BeautifulSoup
It should work like this:
you... | Adding +1 to a URL whilst scraping | If I have a url called youtube.com/user/1/ and I want the number to incrament to youtube.com/user/2/
whilst scraping the whole page, how would I do so? I've been trying to think of some ways to do this but I can't seem to find anything?
BeautifulSoup
It should work like this:
youtube.com/user/1/
You scrape the page and... | [
"while scraping:\n for i in range(amount_of_scrapes):\n scrape(f\"youtube.com/user/{i+1}/\")\n scraping = False\n\nThis is just an example but correct implemented it should work\n",
"You could do something like\nlast_page_num = # set the last page number here\n\nscraped_data = []\nfor page_num in ran... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074343136_beautifulsoup_python_web_scraping.txt |
Q:
Need FTP the file without storing interpreter file save in local through Python
I am trying to do some image interpreter and trying to store them directly to FTP server.
But my steps like upload the image from local folder then it converts to mask image then it will have final output. But during my mask and final ... | Need FTP the file without storing interpreter file save in local through Python | I am trying to do some image interpreter and trying to store them directly to FTP server.
But my steps like upload the image from local folder then it converts to mask image then it will have final output. But during my mask and final output scenarios, temporary images are getting save it local which I don't want.
But ... | [
"I presume your question is really *\"How do I call ftplib.storbinary() without needing a disk file. The short answer is via io.BytesIO:\nHere we make a PIL Image\nfrom PIL import Image\nfrom io import BytesIO\n\n# Create dummy red PIL Image\noutput = Image.new('RGB', (320,240), 'red')\n\nand save it in aBytesIO:\n... | [
0,
0
] | [] | [] | [
"image_processing",
"matplotlib",
"python",
"python_3.x"
] | stackoverflow_0074292103_image_processing_matplotlib_python_python_3.x.txt |
Q:
AttributeError: module 'tensorflow' has no attribute 'reset_default_graph'
I have installed tensorflow version r0.11.
In my file name cartpole.py I have imported tensorflow:
import tensorflow as tf
and use it:
tf.reset_default_graph()
Trying to run my project in PyCharm I get this error:
in <module>
tf.rese... | AttributeError: module 'tensorflow' has no attribute 'reset_default_graph' | I have installed tensorflow version r0.11.
In my file name cartpole.py I have imported tensorflow:
import tensorflow as tf
and use it:
tf.reset_default_graph()
Trying to run my project in PyCharm I get this error:
in <module>
tf.reset_default_graph()
AttributeError: module 'tensorflow' has no attribute 'reset_de... | [
"This function is deprecated. \nUse tf.compat.v1.reset_default_graph() instead.\nUpdate\nThis is not the only function to be out of date. Check out this answer for release notes and a conversion script. \n",
"You normally import tensorflow by writing,\nimport tensorflow as tf\n\nIt's possible that you have named ... | [
82,
34,
9,
7,
5,
5,
2,
0,
0,
0,
0,
0
] | [] | [] | [
"pycharm",
"python",
"tensorflow"
] | stackoverflow_0040782271_pycharm_python_tensorflow.txt |
Q:
how to free up memory occupied by parallelized processes
as shown in the below code, the iterable self.__listOfKeyCellsCollector contains hundereds of thousands of objects of type KeyGridCellsInTreatmentFilterator. each object or item in self.__listOfKeyCellsCollector is to be processed separately on a different
p... | how to free up memory occupied by parallelized processes | as shown in the below code, the iterable self.__listOfKeyCellsCollector contains hundereds of thousands of objects of type KeyGridCellsInTreatmentFilterator. each object or item in self.__listOfKeyCellsCollector is to be processed separately on a different
process by invoking the run() respectively.
the problem i am fa... | [
"Well, one way to free up some memory could be to use the del statement to explicitly \"delete\" an object if it is not needed anymore.\nIn a nutshell, it decreases the reference count for an object and when the reference count reaches 0, it gets freed.\nIn some extreme cases you could also try calling gc.collect, ... | [
0
] | [] | [] | [
"memory_leaks",
"memory_management",
"multiprocessing",
"python",
"python_multiprocessing"
] | stackoverflow_0074343068_memory_leaks_memory_management_multiprocessing_python_python_multiprocessing.txt |
Q:
How to save files from Incoming email using imap_tools into AWS S3 bucket
I have an email server hosted on AWS EC2. I am using imap_tools for retrieving email content.
when I tried to get the file through the payload, I get this return;
att.payload # bytes: b'\xff\xd8\xff\xe0\'
Please how do I get the... | How to save files from Incoming email using imap_tools into AWS S3 bucket | I have an email server hosted on AWS EC2. I am using imap_tools for retrieving email content.
when I tried to get the file through the payload, I get this return;
att.payload # bytes: b'\xff\xd8\xff\xe0\'
Please how do I get the actual file path from the payload or bytes to be saved on AWS S3 and be able t... | [
"There is no \"actual file path from of payload\" in email.\nJust name, nesting level and some few attachment attrs.\n"
] | [
0
] | [] | [] | [
"django",
"email",
"imap",
"imap_tools",
"python"
] | stackoverflow_0074317027_django_email_imap_imap_tools_python.txt |
Q:
enable cors in a nginx with reverse proxy to strawberry-graphql python app with asgi using daphne
I have a website that has the following setup:
the client is an angular 14 project
the server is a python app with strawberry for graphql
using nginx as web server
using asgi python script to run the app using daphne... | enable cors in a nginx with reverse proxy to strawberry-graphql python app with asgi using daphne | I have a website that has the following setup:
the client is an angular 14 project
the server is a python app with strawberry for graphql
using nginx as web server
using asgi python script to run the app using daphne
I'm having cors related errors when I try to access graphql from the angular app
Access to XMLHttpReq... | [] | [] | [
"I checked the network tab of my browser and I noticed that what the OPTIONS request (for the CORS preflight request) fails with error 301, which is redirect. and then I noticed that the graphql url is mydomain.com/graphql and not www.mydomain.com/graphql and I do redirect to www in my nginx configuration.\ni disab... | [
-1
] | [
"asgi",
"cors",
"daphne",
"nginx",
"python"
] | stackoverflow_0074340424_asgi_cors_daphne_nginx_python.txt |
Q:
How to remove certain lines from text file in python?
I am trying to delete specific lines from text files, Which is basically a java code in txt format. I am trying to delete multi-comments from the text, which means script should read the files and delete multi-comments starting with "/" and end with / along wit... | How to remove certain lines from text file in python? | I am trying to delete specific lines from text files, Which is basically a java code in txt format. I am trying to delete multi-comments from the text, which means script should read the files and delete multi-comments starting with "/" and end with / along with "\\" , "package", and "import".
I am using this code, it ... | [
"you have the wrong regex in order to expect \".\" or \"*\" as a string, you need to put a \\ before it:\nimport re\nimport sys\nimport codecs\ntxt = \"hi.txt\"\nwith open(txt, 'r',encoding= 'utf-8', errors= 'ignore') as fil:\n file = fil.read()\n\nwtalc = re.sub(r\"//.*?\\n\", '', file)\nwtslc = re.sub(r\"/\\*.... | [
1,
0
] | [] | [] | [
"function",
"python",
"python_3.x",
"python_re"
] | stackoverflow_0074342888_function_python_python_3.x_python_re.txt |
Q:
What is the difference between "datetime.timedelta" and "dateutil.relativedelta.relativedelta" when working only with days?
What is the difference between datetime.timedelta (from Python's standard library) and dateutil.relativedelta.relativedelta when working only with days?
As far as I understand, timedelta only... | What is the difference between "datetime.timedelta" and "dateutil.relativedelta.relativedelta" when working only with days? | What is the difference between datetime.timedelta (from Python's standard library) and dateutil.relativedelta.relativedelta when working only with days?
As far as I understand, timedelta only supports days (and weeks), while relativedelta adds support for periods defined in terms of years, months, weeks or days, as wel... | [
"dateutil is an extension package to the python standard datetime module. As you say, it provides extra functionality, such as timedeltas that are expressed in units larger than a day.\nThis is useful if you have to ask questions such as how many months can I save before my girlfriend's birthday comes up, or what's... | [
104,
54,
25,
2
] | [] | [] | [
"datetime",
"python",
"timedelta"
] | stackoverflow_0012433233_datetime_python_timedelta.txt |
Q:
Price Scraping: Element not visible in html
I am trying to extract the price value of in the linked website using beautfulsoup in python. I am able to see the where the price is when I use 'Inspect Element', but I do not see it when using 'View Source'
import requests
from bs4 import BeautifulSoup
r = requests.... | Price Scraping: Element not visible in html | I am trying to extract the price value of in the linked website using beautfulsoup in python. I am able to see the where the price is when I use 'Inspect Element', but I do not see it when using 'View Source'
import requests
from bs4 import BeautifulSoup
r = requests.get('https://www.rolex.com/en-us/watches/air-king... | [
"The price data loads from a json file. You can see this by loading up Dev Tools and searching for the price (7,400 for me) and seeing what request loaded the price.\nThe code to get the price is simple :)\nresponse = requests.get(\"https://www.rolex.com/content/api/rolex/model-price.US.m126900-0001.en_us.json\").j... | [
0
] | [] | [] | [
"beautifulsoup",
"html",
"parsing",
"python",
"web_scraping"
] | stackoverflow_0074343194_beautifulsoup_html_parsing_python_web_scraping.txt |
Q:
how to iterate through column values of pyspark dataframe
I have a pyspark dataframe
I want to check each row for the address column and if it contains the substring "india"
then I need to add another column and say true
else false
and also i wanted to check the substring is present in the column value string if ... | how to iterate through column values of pyspark dataframe | I have a pyspark dataframe
I want to check each row for the address column and if it contains the substring "india"
then I need to add another column and say true
else false
and also i wanted to check the substring is present in the column value string if yes print yes else no.. this has to iterate for all the rows in... | [
"You can utilise contains or like for this\nData Preparation\ns = StringIO(\"\"\"\nuser,address\nrishi,XYZ Bangalore Karnataka\nkirthi,ABC Pune India\ntushar,ASD Orissa India\n\"\"\"\n)\n\ndf = pd.read_csv(s,delimiter=',')\n\nsparkDF = sql.createDataFrame(df)\n\nsparkDF.show()\n\n+------+-----------------------+\n|... | [
1
] | [] | [] | [
"pyspark",
"python",
"python_3.x"
] | stackoverflow_0074343350_pyspark_python_python_3.x.txt |
Q:
Can model.h5 file be accessed at the backend using load_model from Keras library?
I have saved my model after training and am currently loading it to use it for prediction at the backend. I have uploaded the model.h5 file to heroku via Github using auto-deploy feature with the flask app associated to it accessing ... | Can model.h5 file be accessed at the backend using load_model from Keras library? | I have saved my model after training and am currently loading it to use it for prediction at the backend. I have uploaded the model.h5 file to heroku via Github using auto-deploy feature with the flask app associated to it accessing it when the predict method is called. It works fine when testing it on localhost, but i... | [
"To everyone having this issue, Heroku doesn't support large file systems associated with Git-LFS(more than 300MB in Heroku). So accessing your .h5 file from your flask app won't help as .h5 files are usually huge. So, this application won't work on Heroku.\n"
] | [
1
] | [] | [] | [
"heroku",
"keras",
"python"
] | stackoverflow_0074335414_heroku_keras_python.txt |
Q:
Getting error: legacy-install-failure while installing OpenVino
I keep getting error: legacy-install-failure error while installing OpenVino using pip install openvino-dev[ONNX,tensorflow2]. I've tried to upgrade and reinstall wheel, setup tool and pip.
Below is the full error:
[end of output]
not... | Getting error: legacy-install-failure while installing OpenVino | I keep getting error: legacy-install-failure error while installing OpenVino using pip install openvino-dev[ONNX,tensorflow2]. I've tried to upgrade and reinstall wheel, setup tool and pip.
Below is the full error:
[end of output]
note: This error originates from a subprocess, and is likely not a probl... | [
"The error occurs due to unsupported Python version (Python 3.10 is not yet supported by OpenVINO™). OpenVINO™ Toolkit is supported only for Python versions 3.6-3.9 on Windows OS.\nRefer to the System Requirements for more information.\n"
] | [
1
] | [] | [] | [
"openvino",
"pip",
"python"
] | stackoverflow_0074326110_openvino_pip_python.txt |
Q:
How to get as tag as title and its child element as its description using Beautiful Soup Python
For an HTML input below:
example = """<strong>First Title</strong><p>Content of first title</p><p>Content of first title</p><strong>Second title</strong><p>Content of second title</p></strong>"""
the output should be:... | How to get as tag as title and its child element as its description using Beautiful Soup Python | For an HTML input below:
example = """<strong>First Title</strong><p>Content of first title</p><p>Content of first title</p><strong>Second title</strong><p>Content of second title</p></strong>"""
the output should be:
{'First Title': '<p>Content of first title</p> <p>Content of first title</p>', 'Second title': '<p>Co... | [
"You need to select <p> nodes with <strong> child\nfor header in soup.select('p strong'):\n title = header.get_text().strip()\n nextNode = header.parent\n content = []\n ...\n\nand in the inner loop check if the nextNode child is strong\n...\nelif isinstance(nextNode, Tag):\n if next(nextNode.childre... | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0074343142_beautifulsoup_html_python.txt |
Q:
How to add parameters to Matplotlib Class Circle?
The question is probably technically confusing, but I'm not sure how to actually ask this.
Here's the code:
import matplotlib.pyplot as plt
import matplotlib.patches as ptch
import numpy as np
import math
import random
class Particle(ptch.Circle):
def __init__... | How to add parameters to Matplotlib Class Circle? | The question is probably technically confusing, but I'm not sure how to actually ask this.
Here's the code:
import matplotlib.pyplot as plt
import matplotlib.patches as ptch
import numpy as np
import math
import random
class Particle(ptch.Circle):
def __init__(self, center = np.array([0.5,0.5]), radius = 1.0, colo... | [
"Calling the parent class's __init__ method with super seems to solve the problem.\nclass Particle(ptch.Circle):\n def __init__(self, center = np.array([0.5,0.5]), radius = 1.0, color = '#FFFFFF', mass = 1, velocity = np.array([1,1]), acceleration = np.array([0,0]), **kwargs):\n super().__init__(center, r... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074341172_matplotlib_python.txt |
Q:
reproduce numpy random numbers with numpy rng
I have a script using np.random.randint that was seeded withnp.random.seed(0). Now I'd like to find how I can get the same numbers by creating a separate rng object rng = np.random.default_rng(0). Naively I would have expected these two ways to be identical, but appare... | reproduce numpy random numbers with numpy rng | I have a script using np.random.randint that was seeded withnp.random.seed(0). Now I'd like to find how I can get the same numbers by creating a separate rng object rng = np.random.default_rng(0). Naively I would have expected these two ways to be identical, but apparently this is not the case. The reason is that I'm t... | [
"numpy.random.default_rng uses the new-style Generator API. This is mostly superior to the old functionality, and should be preferred in new code unless you have a specific reason not to use it, but it is not backward compatible with the old API.\nThe old API's way of creating a new RNG object is numpy.random.Rando... | [
1
] | [] | [] | [
"numpy",
"python",
"random"
] | stackoverflow_0074343474_numpy_python_random.txt |
Q:
No module named project name.settings
I tried running (python manage.py runserver. But it keeps giving me an error
*I tried changing the directory of my setting but i resulted the same way
*
A:
Make sure you have your project name with file tree here:
-- nameofyourproject\
|-- __init__.py
|-- manage.py
|-- se... | No module named project name.settings | I tried running (python manage.py runserver. But it keeps giving me an error
*I tried changing the directory of my setting but i resulted the same way
*
| [
"Make sure you have your project name with file tree here:\n-- nameofyourproject\\\n |-- __init__.py\n |-- manage.py\n |-- settings.py\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074343581_python.txt |
Q:
SHA256 hashing of a CSV file with email list
I'll try to keep it simple. So I need to upload client's database to ad platforms and compliance only will let me do so if I convert the information before. -
I've read a ton of other questions about this but I really can't understand them because im such an ignorant co... | SHA256 hashing of a CSV file with email list | I'll try to keep it simple. So I need to upload client's database to ad platforms and compliance only will let me do so if I convert the information before. -
I've read a ton of other questions about this but I really can't understand them because im such an ignorant code-wise.
If someone can point me please to the sim... | [
"Please try using the tool suggested here in Google Support. Drop file to Hashing Demo - .csv output section and you can SHA256 hash Email, First Name, Last Name columns.\nOr you can use the python script suggested here in Google Support.\n"
] | [
0
] | [] | [] | [
"excel",
"python",
"sha256"
] | stackoverflow_0072370511_excel_python_sha256.txt |
Q:
Extract text on mouse hover in python selenium
I would like to extract the text that appears on mouse hover on an element from the website https://idsc.cidadessustentaveis.org.br/rankings. A particular example of text of interest, is the text “Erradicacao da pobreza Pontuacao: 44,47” which appears on hovering the ... | Extract text on mouse hover in python selenium | I would like to extract the text that appears on mouse hover on an element from the website https://idsc.cidadessustentaveis.org.br/rankings. A particular example of text of interest, is the text “Erradicacao da pobreza Pontuacao: 44,47” which appears on hovering the first bar located in the column “Desempenho por ODS”... | [
"You was close to the solution.\nWhen hovering over those elements tooltips appearing.\nThese tooltips will present different texts according to element you hovered over.\nHere I used your code, just added the tooltips\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdr... | [
1
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"selenium_webdriver",
"webdriverwait"
] | stackoverflow_0074342917_css_selectors_python_selenium_selenium_webdriver_webdriverwait.txt |
Q:
Mock two get responses with different result
I'am trying to mock two same get requests but with different result. My goal is to test second exception (except requests.exceptions.RequestException) but I can't make it work so that first requests.get pass and second requests.get fail to "connect" and therefore to rea... | Mock two get responses with different result | I'am trying to mock two same get requests but with different result. My goal is to test second exception (except requests.exceptions.RequestException) but I can't make it work so that first requests.get pass and second requests.get fail to "connect" and therefore to reach second exception. Is that even possible? Thx!
t... | [
"You can make the Mock object return different values and/or raise different exceptions on different calls by specifying an iterable as the side_effect attribute.\nAn excerpt from the documentation:\n\nIf you pass in an iterable, it is used to retrieve an iterator which\nmust yield a value on every call. This value... | [
1
] | [] | [] | [
"python",
"python_unittest"
] | stackoverflow_0074343473_python_python_unittest.txt |
Q:
Django ModelForm with extra fields that are not in the model
I have done a ModelForm adding some extra fields that are not in the model. I use these fields for some calcualtions when saving the form.
The extra fields appear on the form and they are sent in the POST request when uploading the form. The problem is t... | Django ModelForm with extra fields that are not in the model | I have done a ModelForm adding some extra fields that are not in the model. I use these fields for some calcualtions when saving the form.
The extra fields appear on the form and they are sent in the POST request when uploading the form. The problem is they are not added to the cleaned_data dictionary when I validate t... | [
"EDIT 2020 (Django 2 or higher)\nIn Django 2+ you can add the extra fields like this:\nclass ProfileForm(forms.ModelForm):\n \n extra_field = forms.ImageField()\n\n class Meta:\n model = User\n fields = ['username', 'country', 'website', 'biography']\n\nOriginal answer (Django 1)\nIt's possib... | [
47,
17,
8,
5,
4,
3,
2,
0
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0002229039_django_forms_python.txt |
Q:
python manage.py runserver error : ModuleNotFoundError: No module named 'settings'
I am in the process on getting started with python and have run into a problem using django 2.1 and python 3.7 that many other people seem to have had as well.
Below is my process for getting here:
started a virtual environment
s... | python manage.py runserver error : ModuleNotFoundError: No module named 'settings' | I am in the process on getting started with python and have run into a problem using django 2.1 and python 3.7 that many other people seem to have had as well.
Below is my process for getting here:
started a virtual environment
started a django project
attempted to run:
python manage.py runserver
I consistently g... | [
"\nopen yr project folder.\n\nsearch for the wsgi.py file and add this line.\nfrom django.conf import settings.\n\n\nThen save.\n\nlocate yr manage.py file edit the\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')\n\nTo\nos.environ['DJANGO_SETTINGS_MODULE' ]='projectname.settings'\n\n\nsave ... | [
3,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"django",
"django_2.1",
"python"
] | stackoverflow_0053799484_django_django_2.1_python.txt |
Q:
I want to transpose after concat in pandas
I want to concatenate multiple columns in a DataFrame into a single column and transpose them into a single row, but when I call transpose it remains a single column.
import pandas as pd
df = pd.DataFrame(
{
0: [1, 2, 3],
1: [11, 12, 13]
}
)
print(... | I want to transpose after concat in pandas | I want to concatenate multiple columns in a DataFrame into a single column and transpose them into a single row, but when I call transpose it remains a single column.
import pandas as pd
df = pd.DataFrame(
{
0: [1, 2, 3],
1: [11, 12, 13]
}
)
print( df)
df = pd.concat( [df[0], df[1]])
df = df.T.c... | [
"Dump down into numpy and build a new dataframe:\nimport pandas as pd\nimport numpy as np\n\nout = df.to_numpy().ravel(order='F')\npd.DataFrame([out])\n 0 1 2 3 4 5\n0 1 2 3 11 12 13\n\n",
"example:\ndf = pd.DataFrame(\n {\n 0: [1, 2, 3],\n 1: [11, 12, 13]\n }\n)\n\nuse followi... | [
3,
1
] | [] | [] | [
"concatenation",
"pandas",
"python",
"transpose"
] | stackoverflow_0074343606_concatenation_pandas_python_transpose.txt |
Q:
Convert digital representation of a value into Arabic words
Convert the digital representation of a value to the equivalent words in the Arabic language.
An English language example would be:
input = 111
output = One hundred and eleven
In my requirement One hundred and eleven is the Arabic equivalent.
Is there a... | Convert digital representation of a value into Arabic words | Convert the digital representation of a value to the equivalent words in the Arabic language.
An English language example would be:
input = 111
output = One hundred and eleven
In my requirement One hundred and eleven is the Arabic equivalent.
Is there a python library for converting digital numbers to words in Arabic... | [
"num2words module in Python, which converts number (like 34) to words (like thirty-four). Also, this library has support for multiple languages. In this article, we will see how to convert number to words using num2words module.\nInstallation\nOne can easily install num2words using pip\npip install num2words\nConsi... | [
0
] | [] | [] | [
"arabic_support",
"python"
] | stackoverflow_0040051000_arabic_support_python.txt |
Q:
Is my model using dropout although it is not in the forward pass ? Printing the model shows only the attributes
I have the following nn model in pytorch, the forward method is not using dropout, but there is an instance of dropout in the class, and it gets printed when the class is instantiated. Is the model using... | Is my model using dropout although it is not in the forward pass ? Printing the model shows only the attributes | I have the following nn model in pytorch, the forward method is not using dropout, but there is an instance of dropout in the class, and it gets printed when the class is instantiated. Is the model using dropout or not?
Here is the code structure.
n_input_dim=train_ds[0][0].shape[0] #getting the input dimension of a sa... | [
"The dropout layer is registered as a submodule of the NN module, and as a result is printed when you print the model. However, it is not being called anywhere (in particular, including the forward pass), so in a conceptual sense your network does not have a dropout layer since it is not being used.\n"
] | [
0
] | [] | [] | [
"machine_learning",
"python",
"pytorch"
] | stackoverflow_0074342714_machine_learning_python_pytorch.txt |
Q:
Is there a way to create a dataframe in python from start date to end date
Is there way to create a dataframe(using pandas) from start date to End date with random values
For example, the required data frame:
date value
2015-06-25 12
2015-06-26 23
2015-06-27 3.4
2015-06-28 5.6
Is this da... | Is there a way to create a dataframe in python from start date to end date | Is there way to create a dataframe(using pandas) from start date to End date with random values
For example, the required data frame:
date value
2015-06-25 12
2015-06-26 23
2015-06-27 3.4
2015-06-28 5.6
Is this dataframe I need to set "from date" to "To date" so that there is no need to type ... | [
"You can use pandas.date_range and numpy.random.uniform:\nimport numpy as np\ndates = pd.date_range('2015-06-25', '2015-06-28', freq='D')\n\ndf = pd.DataFrame({'date': dates,\n 'value': np.random.uniform(0, 50, size=len(dates))})\n\noutput:\n date value\n0 2015-06-25 39.496971\n1 2015... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074343469_pandas_python.txt |
Q:
Merging lists/tuples stored inside a list in python
I have a list of lists each containing tuples with some co-ordinates which sort of look like this:
[[(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)], [(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)], [(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)]]
Considering orders, lets cal... | Merging lists/tuples stored inside a list in python | I have a list of lists each containing tuples with some co-ordinates which sort of look like this:
[[(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)], [(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)], [(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)]]
Considering orders, lets call the outer list - L0, and the inner list - L1
The number... | [
"A short and relatively fast way to do this would be to use list comprehensions:\nxmin = min([x for L1 in L0 for x, y in L1])\nymax = max([y for L1 in L0 for x, y in L1])\n\nBasically, you loop through the lists L1 in the list L2 and make a new list containing all the first (for x) or last (for y) elements of the t... | [
0,
0
] | [] | [] | [
"list",
"max",
"min",
"python",
"python_3.x"
] | stackoverflow_0074343705_list_max_min_python_python_3.x.txt |
Q:
Why does Tensorflow Classification Algorithm make same prediction all the time
import os
os.add_dll_directory("C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.2/bin")
import tensorflow as tf
from keras import models
from keras import Sequential
from keras import layers
from keras.layers import Conv2D, MaxP... | Why does Tensorflow Classification Algorithm make same prediction all the time |
import os
os.add_dll_directory("C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.2/bin")
import tensorflow as tf
from keras import models
from keras import Sequential
from keras import layers
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
import os
print(len(os.listdir('COVID-19_Radiography_Da... | [
"it is for medical instruments BinaryCrossEntrophy classification because it required the most accurate from 0 to 1. I skipped the model path and sample as there are no data examples but one answer repeating may occur for these reasons.\n\nModel training and learning rates, the model needs to learn in appropriate m... | [
0
] | [] | [] | [
"classification",
"python",
"tensorflow"
] | stackoverflow_0074341206_classification_python_tensorflow.txt |
Q:
Python/Django - Expected a string or bytes-like object
I've looked around, and I've seen a couple of solutions that I thought would work for my own code, but seemed to do nothing.
I am trying to pull data from a JSON file and add the information to arrays. The arrays will then be used to input data into several ob... | Python/Django - Expected a string or bytes-like object | I've looked around, and I've seen a couple of solutions that I thought would work for my own code, but seemed to do nothing.
I am trying to pull data from a JSON file and add the information to arrays. The arrays will then be used to input data into several objects that I add to the database (I know, this is terribly i... | [
"JUST IN CASE SOMEONE RUNS INTO THIS ERROR OF RECENT.\nSTEP 1: Go to the migrations folder \"migrations\".\nSTEP 2: Navigate to the migration file, the recent one, for example, \"0008_auto_20210821_0912.py\".\nSTEP 3: Change the default value that is there from whatever value to \"2021-01-05\" for DateField or \"20... | [
5,
4,
0
] | [
"You should Delete migration files and run migrations again\n"
] | [
-1
] | [
"django",
"python"
] | stackoverflow_0040234503_django_python.txt |
Q:
Questions about the text of telegram bots
How to put a large text on the output in a telegram bot, what are the distribution tools
I tried to insert the text as it is, writes that there is an error in the syntax
A:
Use triple quotes or triple double-quotes.
@bot.message_handler(commands=["start"])
def start(mess... | Questions about the text of telegram bots | How to put a large text on the output in a telegram bot, what are the distribution tools
I tried to insert the text as it is, writes that there is an error in the syntax
| [
"Use triple quotes or triple double-quotes.\n@bot.message_handler(commands=[\"start\"])\ndef start(message):\n bot.send_message(message.from_user.id, \"\"\"texttexttextext\n\ntexttexttextext\n\ntexttexttextext\n\ntexttexttextext\"\"\")\nbot.polling(none_stop=True, interval=0)\n\n"
] | [
0
] | [] | [] | [
"python",
"telegram_bot"
] | stackoverflow_0074341387_python_telegram_bot.txt |
Q:
ValueError: Invalid parameter for estimator Pipeline
I get an error when tuning the hyperparameters of a decision tree with GridSearchCV.
Code is given below:
pipe_tree = Pipeline([
('Scaler', MinMaxScaler()),
('Classifier', DecisionTreeClassifier(max_depth=8))
])
# Train
pipe_tree.fit(X_train, y_train)
... | ValueError: Invalid parameter for estimator Pipeline | I get an error when tuning the hyperparameters of a decision tree with GridSearchCV.
Code is given below:
pipe_tree = Pipeline([
('Scaler', MinMaxScaler()),
('Classifier', DecisionTreeClassifier(max_depth=8))
])
# Train
pipe_tree.fit(X_train, y_train)
# Predict
pred_tree = pipe_tree.predict(X_test)
# overall... | [
"First of all, I think some part of your code is missing. I assume you are doing RandomizedSearchCV or similiar, but we can't see it in your code.\nHowever, it seems that the error is in the creation of the param_dist dictionary. You should follow some rules to define key names. Let me recommend this link.\nBasical... | [
0
] | [] | [] | [
"decision_tree",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074338493_decision_tree_machine_learning_python_scikit_learn.txt |
Q:
Unable to locate element with relative XPATH or CSS selector, but absolute XPATH is located and clickable in python selenium
I'm struggling with locating an element to click. Here's what I am working with:
I'm trying to locate the element with the a href link. I've tried the following:
driver.find_element(By.CSS_... | Unable to locate element with relative XPATH or CSS selector, but absolute XPATH is located and clickable in python selenium | I'm struggling with locating an element to click. Here's what I am working with:
I'm trying to locate the element with the a href link. I've tried the following:
driver.find_element(By.CSS_SELECTOR,'a[href="/collections/e-coated-kettlebells/products/28kg-kettlebell"]').click()
driver.find_element(By.XPATH,'//div//a[@... | [
"These are unique locators for that element.\nXPath:\n\"//div/a[contains(@href,'28kg-kettlebell')]\"\n\nCSS Selector:\n\"div>a[href*='28kg-kettlebell']\"\n\nInside Selenium methods it can be as following:\nXPath:\ndriver.find_element(By.XPATH, \"//div/a[contains(@href,'28kg-kettlebell')]\").click()\n\nCSS Selector:... | [
1
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"selenium_webdriver",
"xpath"
] | stackoverflow_0074341989_css_selectors_python_selenium_selenium_webdriver_xpath.txt |
Q:
How to set Collation in MySQL database with Django 2.* mysqlclient?
I need to set default Collation for MySQL tables with Django 2.*, im using mysqlclient, my settings are:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
'PASSWORD': '... | How to set Collation in MySQL database with Django 2.* mysqlclient? | I need to set default Collation for MySQL tables with Django 2.*, im using mysqlclient, my settings are:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS'... | [
"'default': {\n 'ENGINE': 'django.db.backends.mysql', \n 'NAME': '',\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': 'localhost',\n 'PORT': '3306',\n 'OPTIONS': {\n 'init_command': 'ALTER DATABASE <YOUR_DB_NAME> CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci',\n },\n}\n\nThanks to https:/... | [
3,
0
] | [] | [] | [
"django",
"django_models",
"mysql",
"python",
"python_3.x"
] | stackoverflow_0049316327_django_django_models_mysql_python_python_3.x.txt |
Q:
How can i remove a word from a string using the index in python?
I have used .find() on my string to find the index of the word that the user wants to remove from the string, but now how do i use this index to them remove said word?
The function is as follows:
sentence = "The quick brown fox jumps over the lazy do... | How can i remove a word from a string using the index in python? | I have used .find() on my string to find the index of the word that the user wants to remove from the string, but now how do i use this index to them remove said word?
The function is as follows:
sentence = "The quick brown fox jumps over the lazy dog."
print("The sentence is: "+ sentence)
user_removal = input("Which ... | [
"You can use slicing.\nUsage\nsomestring[lowerborder:upperborder].\nExample\nsentence = \"The.quick.brown.fox.jumps.over.the.lazy.dog.\"\nprint(\"The sentence is: \"+ sentence)\n\nuser_removal = input(\"Which word would you like to remove? \")\n\nlowerborder = sentence.find(user_removal) -1\nupperborder = lowerbord... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074343509_python.txt |
Q:
module 'asyncio' has no attribute 'coroutine' on snakemake
I followed the following code to install snakemake on my linux machine :
conda activate base
mamba create -c conda-forge -c bioconda -n snakemake snakemake
conda activate snakemake
Everything was fine, but when I try to run the following code :
snakemake ... | module 'asyncio' has no attribute 'coroutine' on snakemake | I followed the following code to install snakemake on my linux machine :
conda activate base
mamba create -c conda-forge -c bioconda -n snakemake snakemake
conda activate snakemake
Everything was fine, but when I try to run the following code :
snakemake -s Snakemake_job -j n
I get this error :
Building DAG of jobs..... | [
"Quoth the docs for asyncio.coroutine, emphasis mine:\n\nDeprecated since version 3.8, will be removed in version 3.11: Use async def instead.\n\nThe ratelimiter dependency snakemake uses is evidently not compatible with Python 3.11.\nThat package has had an issue open about this for multiple years, and snakemake s... | [
1
] | [] | [] | [
"python",
"python_asyncio",
"snakemake"
] | stackoverflow_0074343982_python_python_asyncio_snakemake.txt |
Q:
cv2.error: OpenCV(4.5.2) C:\Users\ ... \modules\imgproc\src\resize.cpp:3929: error: (-215:Assertion failed) func != 0 in function 'cv::hal::resize'
I tried to run the following code:
a = np.array([[1,0],[0,0]])
a = cv2.resize(a , (400,400))
cv2.imshow('Image', a)
cv2.waitKey(0)
cv2.destroyAllWindows
and got this ... | cv2.error: OpenCV(4.5.2) C:\Users\ ... \modules\imgproc\src\resize.cpp:3929: error: (-215:Assertion failed) func != 0 in function 'cv::hal::resize' | I tried to run the following code:
a = np.array([[1,0],[0,0]])
a = cv2.resize(a , (400,400))
cv2.imshow('Image', a)
cv2.waitKey(0)
cv2.destroyAllWindows
and got this error:
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-_8k9tw8n\opencv\modules\imgproc\src\resize.cpp:3929: error: (-215:A... | [
"the error is from the resize function, it needs to be a dtype=uint8 type array.\nthere is a pretty solid answer here\nupdate me if it worked :)\n",
"Changing the type of you array a to float fix the issue.\n\na = cv2.resize(a.astype(float) , (400,400))\n\n\n"
] | [
2,
0
] | [] | [] | [
"image_resizing",
"numpy",
"opencv",
"python"
] | stackoverflow_0068429181_image_resizing_numpy_opencv_python.txt |
Q:
Why dateparser module fails to parse date strings in Spanish even setting parameters as languages or locales in Spanish?
I'm trying to parse a large set of files with records that include dates in Spanish with formats like this one 'Ago 01, 2022'. For this task, I'm using the function parse from dataparser module.... | Why dateparser module fails to parse date strings in Spanish even setting parameters as languages or locales in Spanish? | I'm trying to parse a large set of files with records that include dates in Spanish with formats like this one 'Ago 01, 2022'. For this task, I'm using the function parse from dataparser module. In the past, I could use successfully that function for a similar purpose, but now it fails with string in Spanish even if I ... | [
"This has been fixed in recent versions.\ndateparser 1.1.3\nCan you check that everything is working as expected now?\n>>> parse('Ago 01, 2021', date_formats=['%b %d, %Y'] )\ndatetime.datetime(2021, 8, 1, 0, 0)\n>>> parse('Ago 01, 2021', date_formats=['%b %d, %Y'], languages=['es'])\ndatetime.datetime(20... | [
0
] | [] | [] | [
"dateparser",
"datetime",
"python",
"python_3.x"
] | stackoverflow_0073793335_dateparser_datetime_python_python_3.x.txt |
Q:
How do I fix my python version showing up in terminal?
Even though I have installed Python 3.11 and it shows up on my Applications.
When I go to terminal to check python version it shows this:
Python 3.8.8 (default, Apr 13 2021, 12:59:45)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
How do I fix this?
I am on Lates... | How do I fix my python version showing up in terminal? | Even though I have installed Python 3.11 and it shows up on my Applications.
When I go to terminal to check python version it shows this:
Python 3.8.8 (default, Apr 13 2021, 12:59:45)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
How do I fix this?
I am on Latest macOS Ventura version.
I've already uninstalled Anaconda b... | [
"It is possible to have multiple versions of python installed. Your system probably points to python3.8 as the main python version.\nIn your terminal, type: python<tab><tab> (press <tab> key twice). It should list every python executable you have. In case it shows python3.11, all you need to do to use it is to run ... | [
0
] | [] | [] | [
"anaconda",
"macos",
"python",
"python_3.x"
] | stackoverflow_0074343871_anaconda_macos_python_python_3.x.txt |
Q:
Unable to set cloud spanner dialect for Alembic
I have installed the following packages -
SQLAlchemy==1.4.41
sqlalchemy-spanner==1.2.2
alembic==1.8.1
Then I created a file main.py where I am creating a SQLAlchemy engine for cloud spanner.
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarat... | Unable to set cloud spanner dialect for Alembic | I have installed the following packages -
SQLAlchemy==1.4.41
sqlalchemy-spanner==1.2.2
alembic==1.8.1
Then I created a file main.py where I am creating a SQLAlchemy engine for cloud spanner.
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine(
... | [
"You're using SQLAlchemy 1.4, which means it must be everywhere spanner+spanner. Just spanner will not work. As the problem appears only for Alembic, reinstall will also not help - the problem is in configurations somewhere.\nCan you show your env.py file? There must be written something like this:\nclass SpannerIm... | [
1
] | [] | [] | [
"alembic",
"google_cloud_spanner",
"python",
"sqlalchemy"
] | stackoverflow_0074177257_alembic_google_cloud_spanner_python_sqlalchemy.txt |
Q:
How to write output files with variable names with path join
I'm trying to save file name , my filename should be like this "doc00012dsadfile5.jpg"
filename = "doc00012dsad.pdf"
mypath = "/desktop/myfolder/"
_path = os.path.join(mypath,"images")
num = 5
#filename.split(".pdf",1)[0]
os.path.join(_path, file%d.jpg"... | How to write output files with variable names with path join | I'm trying to save file name , my filename should be like this "doc00012dsadfile5.jpg"
filename = "doc00012dsad.pdf"
mypath = "/desktop/myfolder/"
_path = os.path.join(mypath,"images")
num = 5
#filename.split(".pdf",1)[0]
os.path.join(_path, file%d.jpg" % num), xx)
| [
"filename = \"doc00012dsad.pdf\"\nmypath = \"/desktop/myfolder/\"\n_path = os.path.join(mypath,\"images\")\nnum = 5\n#filename.split(\".pdf\",1)[0] \nos.path.join(_path, \"file{}.jpg\".format(num), xx)\n\nI don't know what xx is, but I have just put it there because it was in your code\n",
"Just inject them befor... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074343961_python.txt |
Q:
How to add data from a csv to a new table in SQL?
I have a CSV like this:
no_orden codigo_producto cantidad_orden precio_cada nombre_producto linea_productos descr precio_compra fecha_orden no_cliente nombre_cliente tlf direccion ciudad estado codigo_postal pais
0 10100 S18_1749 30 136.00 ... | How to add data from a csv to a new table in SQL? | I have a CSV like this:
no_orden codigo_producto cantidad_orden precio_cada nombre_producto linea_productos descr precio_compra fecha_orden no_cliente nombre_cliente tlf direccion ciudad estado codigo_postal pais
0 10100 S18_1749 30 136.00 1917 Grand Touring Sedan Vintage Cars Our Vintage... | [
"pandas dataframes have the df.to_sql() method, which might be suitable for what you want to do.\nfrom sqlalchemy import create_engine\nengine = create_engine(YOUR_DB)\n\ncols = ['no_orden', 'codigo_producto', 'cantidad_orden', 'precio_cada', 'nombre_producto', 'linea_productos', 'descr', 'precio_compra', 'fecha_or... | [
0
] | [] | [] | [
"mysql",
"python",
"sql"
] | stackoverflow_0074339886_mysql_python_sql.txt |
Q:
products not showing in product view page django
i created a function to view products in products view page i tried so many times but cant find any one help me please
here is my code
views.py:
def product_view(request,cate_slug,prod_slug):
if (Category.objects.filter(slug=cate_slug, status=0)):
i... | products not showing in product view page django | i created a function to view products in products view page i tried so many times but cant find any one help me please
here is my code
views.py:
def product_view(request,cate_slug,prod_slug):
if (Category.objects.filter(slug=cate_slug, status=0)):
if (Products.objects.filter(slug=prod_slug, status=0)):... | [
"In views:\ndef product_view(request,cate_slug,prod_slug):\n if (Category.objects.filter(slug=cate_slug, status=0)):\n if (Products.objects.filter(slug=prod_slug, status=0)):\n product = Products.objects.filter(slug=prod_slug, status=0)\n \n else:\n messages.warning(r... | [
1,
0
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python",
"python_3.x"
] | stackoverflow_0074343571_django_django_templates_django_views_python_python_3.x.txt |
Q:
Python: How to convert unixtimestamp and timezone into datetime object?
I have a csv file with the datetime in unixtimestamp format with milliseconds and timezone information in milliseconds as well. I want to convert this into a more usable datetime format for further processing.
For example, the time is 1437323... | Python: How to convert unixtimestamp and timezone into datetime object? | I have a csv file with the datetime in unixtimestamp format with milliseconds and timezone information in milliseconds as well. I want to convert this into a more usable datetime format for further processing.
For example, the time is 1437323953822 and timezone is -14400000.
I can convert the timestamp into a datetime... | [
"fromtimestamp can also take another parameter for the timezone, a subclass of tzinfo:\n\nclassmethod datetime.fromtimestamp(timestamp[, tz])\nReturn the local date and time corresponding to the POSIX timestamp,\n such as is returned by time.time(). If optional argument tz is\n None or not specified, the timestam... | [
5,
3,
2,
0
] | [] | [] | [
"datetime",
"python",
"python_2.7",
"timezone",
"unix_timestamp"
] | stackoverflow_0032325209_datetime_python_python_2.7_timezone_unix_timestamp.txt |
Q:
How to make a year range column into separate columns?
I am using Python to analyze a data set that has a column with a year range (see below for example):
Name
Years Range
Andy
1985 - 1987
Bruce
2011 - 2018
I am trying to convert the "Years Range" column that has a string of start and end years into two separ... | How to make a year range column into separate columns? | I am using Python to analyze a data set that has a column with a year range (see below for example):
Name
Years Range
Andy
1985 - 1987
Bruce
2011 - 2018
I am trying to convert the "Years Range" column that has a string of start and end years into two separate columns within the data frame to: "Year Start"... | [
"You can use expand=True within split function\ndf[['Year Start','Year End']] = df['Years Range'].str.split('-',expand=True)\n\noutput #\n Nmae Years_Range Year Start Year End\n0 NAdy 1995-1987 1995 1987\n1 bruce 1890-8775 1890 8775\n\n",
"I think str.extract can do the job.\nHere i... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074343755_python.txt |
Q:
Import pytz into AWS lambda function
I'm writing a lambda function that works with datetimes and trying to import pytz so I can have timezone be accounted for when comparing.
import boto3
import pytz
from datetime import timedelta, date, datetime
from boto3.dynamodb.conditions import Key, Attr
causes this to disp... | Import pytz into AWS lambda function | I'm writing a lambda function that works with datetimes and trying to import pytz so I can have timezone be accounted for when comparing.
import boto3
import pytz
from datetime import timedelta, date, datetime
from boto3.dynamodb.conditions import Key, Attr
causes this to display
{errorMessage=Unable to import module ... | [
"If you don't have access to pytz in your environment, maybe you have access to python-dateutil. In that case you can do:\nimport datetime\nimport dateutil.tz\n\neastern = dateutil.tz.gettz('US/Eastern')\ndatetime.datetime.now(tz=eastern)\n\nREF. How to get current time in Pacific Timezone when import pytz fails?\n... | [
26,
14,
3,
1,
0,
0
] | [
"import datetime as dt\nimport dateutil.tz\n\naesttime = dateutil.tz.gettz('Australia/Brisbane')\nprint(dt.datetime.now(tz=aesttime).strftime(format=\"%Y-%m-%d %H:%M:%S\"))\n\n"
] | [
-1
] | [
"aws_lambda",
"python",
"python_3.x",
"pytz",
"timezone"
] | stackoverflow_0034906589_aws_lambda_python_python_3.x_pytz_timezone.txt |
Q:
PyTorch: Visualize image batch from DataLoader
I have a dataset containing a single image and I am simply applying the YOCO technique to visualize images generated by YOCO. I just get a single output sometimes the output is the same image as the input and sometimes flip+cut. I have no idea why it happens.
Code
imp... | PyTorch: Visualize image batch from DataLoader | I have a dataset containing a single image and I am simply applying the YOCO technique to visualize images generated by YOCO. I just get a single output sometimes the output is the same image as the input and sometimes flip+cut. I have no idea why it happens.
Code
import torch
from torchvision.utils import save_image
i... | [
"Your code is not very readable, if you reformat it properly you will see that it does something like:\nimages = aug(images) # random horizontal flip\nif torch.rand(1) > .5:\n images = horizontal_cutflip(images)\nelse:\n images = vertica_cutflip(images)\n\nIn other words, it applies a random flip operation (d... | [
0
] | [] | [] | [
"data_augmentation",
"machine_learning",
"python",
"pytorch"
] | stackoverflow_0074344045_data_augmentation_machine_learning_python_pytorch.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.