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 Pandas - "None of [' '] are in the columns"
I have this code which selects a column of the csv file, transposes it and appends to one big csv file:
def append_pandas(s,d):
import pandas as pd
df = pd.read_csv(d, sep=';')
df_add = pd.read_csv(s, sep=';')
def append_a_row(df, df_add):
... | Python Pandas - "None of [' '] are in the columns" | I have this code which selects a column of the csv file, transposes it and appends to one big csv file:
def append_pandas(s,d):
import pandas as pd
df = pd.read_csv(d, sep=';')
df_add = pd.read_csv(s, sep=';')
def append_a_row(df, df_add):
df_add = df_add.set_index('Well ID').T
df_add.in... | [
"Can you read the file outside the function and print out its columns:\nprint(df_add.columns)\n\nIt's possible that your column have some more extra spaces, like 'Well ID '\nChange the column name:\ndf_add.rename(columns = {'bad_acutal_name':'Well ID'}, inplace = True)\n\n"
] | [
0
] | [] | [] | [
"append",
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0072069114_append_csv_dataframe_pandas_python.txt |
Q:
Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""
Searching the net this seems to be a problem caused by spaces in the Python installation path.
How do I get pip to work without having to reinstall everything in a path w... | Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe"" | Searching the net this seems to be a problem caused by spaces in the Python installation path.
How do I get pip to work without having to reinstall everything in a path without spaces ?
| [
"it seems that\npython -m pip install XXX \n\nwill work anyway (worked for me)\n(see link by user474491)\n",
"On Windows at least, pip stores the execution path in the executable pip.exe when it is installed.\nEdit this file using a hex editor or WordPad (you have to save it as plain text then to retain binary da... | [
484,
81,
39,
20,
19,
6,
4,
3,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"Instead of calling ipython directly, it is loaded using Python such as \n$ python \"full path to ipython.exe\"\n"
] | [
-2
] | [
"pip",
"python"
] | stackoverflow_0024627525_pip_python.txt |
Q:
python -m django startproject vs django-admin startproject
hi everyone what is difference between python -m django startproject and
django-admin startproject
if it have any different so which one is better for use ?
A:
TL;DR
They are about the same, with manage.py doing the same as django-admin, but setting the... | python -m django startproject vs django-admin startproject | hi everyone what is difference between python -m django startproject and
django-admin startproject
if it have any different so which one is better for use ?
| [
"TL;DR\nThey are about the same, with manage.py doing the same as django-admin, but setting the DJANGO_SETTINGS_MODULE environment variable beforehand.\nAnswer\ndjango-admin is a script installed by setuptools when installing django (i.e: pip install django). The script generated executes something similar to (but ... | [
2
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074138313_django_django_rest_framework_python.txt |
Q:
How do i append at a json file at the end of the list with python
So i want to put some json strings like this
[{"username": "username", "key": "key"}, {"username": "username", "key": "key"}, ...]
i tried json.dump and json.dumps but it doesn't worked for me, please help me
this is the code that i written for now... | How do i append at a json file at the end of the list with python | So i want to put some json strings like this
[{"username": "username", "key": "key"}, {"username": "username", "key": "key"}, ...]
i tried json.dump and json.dumps but it doesn't worked for me, please help me
this is the code that i written for now:
import json
username = input('Username to put in the keys file: ')
k... | [
"Your keys.json file's content initially must be equal to [] that matchs an empty json array to append your objects at runtime, then you have to add your {\"username\": username, \"key\": key} json object to your data list with the append method like below:\n#keys.json is initialized with [] \n\nimport json\n\nuse... | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074132095_json_python.txt |
Q:
How to remove nan and the repeated character from a string list?
I have a string list with nan and some repeated characters, as follows:
classes = [nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan,
nan, nan, ' L-glutamate ', nan,
nan, nan, ... | How to remove nan and the repeated character from a string list? | I have a string list with nan and some repeated characters, as follows:
classes = [nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan,
nan, nan, ' L-glutamate ', nan,
nan, nan, nan, ' L-lysine ', nan,
nan, nan, nan, nan, nan, nan, ' dih... | [
"You could try this\ninstead of checking nan==nan False you can check nan in (nan, )True\nfrom math import nan\nclasses = [nan, nan, nan, nan, nan,\n nan, nan, nan, nan, nan,\n nan, nan, nan, nan, nan, nan,\n nan, nan, ' L-glutamate ', nan,\n nan, nan, nan, ' L-lysine ', nan,... | [
1,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074137471_list_python.txt |
Q:
Download the public key in .PEM format from Azure Key Vault
Is there a python sdk call to download the publickey in .pem format from the azure keyvault.
Yes, we can download the publickey using the Az CLI "az keyvault key download " and directly using the azure portal, but we are looking for the python sdk call
Be... | Download the public key in .PEM format from Azure Key Vault | Is there a python sdk call to download the publickey in .pem format from the azure keyvault.
Yes, we can download the publickey using the Az CLI "az keyvault key download " and directly using the azure portal, but we are looking for the python sdk call
Below code only gives the key name or version of key but not the ac... | [
"The only way to get public key of the certificate (assumption based on PEM format) in that format is to download secret portion which will include both public and private in that format.\nIn the code above you print key name of the key, so it shows just name:\nprint(key.name)\nTry print(key.n), for more informatio... | [
1,
1,
0,
0
] | [] | [] | [
"azure",
"azure_keyvault",
"private_key",
"public_key",
"python"
] | stackoverflow_0074015157_azure_azure_keyvault_private_key_public_key_python.txt |
Q:
How to automatically set an index to a Pandas DataFrame when reading a CSV with or without an index column
Say I have two CSV files. The first one, input_1.csv, has an index column, so when I run:
import pandas as pd
df_1 = pd.read_csv("input_1.csv")
df_1
I get a DataFrame with an index column, as well as a colum... | How to automatically set an index to a Pandas DataFrame when reading a CSV with or without an index column | Say I have two CSV files. The first one, input_1.csv, has an index column, so when I run:
import pandas as pd
df_1 = pd.read_csv("input_1.csv")
df_1
I get a DataFrame with an index column, as well as a column called Unnamed: 0, which is the same as the index column. I can prevent this duplication by adding the argumen... | [
"CSV has no built-in notion of an \"index\" column, so the answer I think is that this isn't possible in general.\nIt would be nice if you could say \"use 0 as index only if unnamed\", but Pandas does not give us that option.\nTherefore you will probably need to just check if an Unnamed: column appears, and set th... | [
0,
0
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074138109_csv_dataframe_pandas_python.txt |
Q:
quoted printable line continuation bug?
I'm writing code to generate a report and send it via email. In this case, I'm trying to embed the report as html the body, but outlook is not rendering parts of the report correctly. In particular it appears to be artifacts from the quoted printable encoding. I can't see an... | quoted printable line continuation bug? | I'm writing code to generate a report and send it via email. In this case, I'm trying to embed the report as html the body, but outlook is not rendering parts of the report correctly. In particular it appears to be artifacts from the quoted printable encoding. I can't see anything wrong with my encoded text.
I have nar... | [
"The problem turned out to be that the email content used LF for line feeds instead of CRLF which is required by RFC. Outlook apparently tries to work with the LF content but has some bugs.\nIf you're generating email from Python and experiencing this problem, remember you need to convert it's output from LF to CRL... | [
2,
0
] | [] | [] | [
"outlook",
"python",
"quoted_printable"
] | stackoverflow_0058666402_outlook_python_quoted_printable.txt |
Q:
if and else in Convolution function
I have a problem with use if and else statement in convolution function.
this code return error:
use any() or all()
import matplotlib.pyplot as plt
import numpy as np
def name(y):
if y<300 :
print("if")
fun2=y-6
return fun2
else:
fun2=6-y
pri... | if and else in Convolution function | I have a problem with use if and else statement in convolution function.
this code return error:
use any() or all()
import matplotlib.pyplot as plt
import numpy as np
def name(y):
if y<300 :
print("if")
fun2=y-6
return fun2
else:
fun2=6-y
print("else")
return fun2
y=np.arange... | [
"The name function is called with a numpy array as the parameter. \"Is the array less than 300?\" isn't meaningful. Are all the items less than 300, np.all? Are any of them less than 300, np.any?\nMy guess is that you want something like:\ndef name( y ):\n sign = 1 - 2*(y>300)\n return sign * (y-6)\n\ny = n... | [
0
] | [] | [] | [
"convolution",
"if_statement",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074135796_convolution_if_statement_matplotlib_numpy_python.txt |
Q:
Run python script from Dockerfile
I have problem with my Dockerfile.
I want to execute my python script during image building (this script creates a few files).
But this script is not execute during image building - there aren't file created by script in container.
It's my Dockerfile
FROM ubuntu:latest
RUN python ... | Run python script from Dockerfile | I have problem with my Dockerfile.
I want to execute my python script during image building (this script creates a few files).
But this script is not execute during image building - there aren't file created by script in container.
It's my Dockerfile
FROM ubuntu:latest
RUN python script1.py
| [
"If you need to interact with files during image building, you must add those files to the image first, otherwise how is Docker to know where those files are?\nFROM ubuntu:latest\nADD script1.py /tmp/script1.py\nRUN python /tmp/script1.py\n\nOf course, I'll leave the paths to you.\n",
"FROM ubuntu:latest \nADD sc... | [
1,
0
] | [] | [] | [
"docker",
"dockerfile",
"python"
] | stackoverflow_0062201160_docker_dockerfile_python.txt |
Q:
Scrape eBay Sold Items Using Selenium Returns []
I have almost no webscraping experience, and wasn't able to solve this using BeautifulSoup, so I'm trying selenium (installed it today). I'm trying to scrape sold items on eBay. I'm trying to scrape:
https://www.ebay.com/sch/i.html?_from=R40&_nkw=oakley+sunglasses&_... | Scrape eBay Sold Items Using Selenium Returns [] | I have almost no webscraping experience, and wasn't able to solve this using BeautifulSoup, so I'm trying selenium (installed it today). I'm trying to scrape sold items on eBay. I'm trying to scrape:
https://www.ebay.com/sch/i.html?_from=R40&_nkw=oakley+sunglasses&_sacat=0&Brand=Oakley&rt=nc&LH_Sold=1&LH_Complete=1&_ip... | [
"It is not necessary to use Selenium for eBay scraping, as the data is not rendered by JavaScript thus can be extracted from plain HTML. It is enough to use BeautifulSoup web scraping library.\nKeep in mind that problems with site parsing may arise when you try to request a site multiple times. eBay may consider th... | [
1,
0
] | [] | [] | [
"pandas",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0068810793_pandas_python_selenium_web_scraping.txt |
Q:
Read rtmp live streaming video using python
I am streaming a session using rtmp server(NGINX). I got the stream url as
rtmp://ip:port/live/stream_name.
How can I read the live stream in my python code(or any other) to do live transcription?
A:
You have to use one of libraries that allow such process, one of the ... | Read rtmp live streaming video using python | I am streaming a session using rtmp server(NGINX). I got the stream url as
rtmp://ip:port/live/stream_name.
How can I read the live stream in my python code(or any other) to do live transcription?
| [
"You have to use one of libraries that allow such process, one of the most commonly used is OpenCV.\nInstall through pip:\npython3 -m pip install opencv-python\n\nCode sample\nimport cv2 # Import OpenCV lib\n\ncap = cv2.VideoCapture('<your RTMP url>') # Open video source as object\nwhile cap.isOpened(): # Untill ... | [
1
] | [] | [] | [
"audio_analysis",
"ffmpeg",
"live_streaming",
"python",
"rtmp"
] | stackoverflow_0073329977_audio_analysis_ffmpeg_live_streaming_python_rtmp.txt |
Q:
IndexError: index 1000 is out of bounds for axis 0 with size 1000, while trying to reproduce the code from a paper
I am working on reproducing the result from a paper.
While running the seq_transformation.py I found this error.
How can I solve this problem?
Here is the code in seq_transformation.py
# Licensed und... | IndexError: index 1000 is out of bounds for axis 0 with size 1000, while trying to reproduce the code from a paper | I am working on reproducing the result from a paper.
While running the seq_transformation.py I found this error.
How can I solve this problem?
Here is the code in seq_transformation.py
# Licensed under the MIT License.
import sys
sys.path.append(['../..'])
import os
import os.path as osp
import numpy as np
import pick... | [
"The error is telling you that you have an axis of 1000 and you try reaching the 1000th element. This is perfectly logical, since Python is 0-indexed, that is, its indexes start from 0 and therefore the 1000th element has an index of 999.\nThe solution is to look at the stack trace, which tells you that in seq_tran... | [
1
] | [] | [] | [
"machine_learning",
"python",
"python_3.x",
"scikit_learn"
] | stackoverflow_0074138368_machine_learning_python_python_3.x_scikit_learn.txt |
Q:
Check if it's possible to divide sequence into k non-intersecting subsections with odd sums
*Subtractor is a set of consecutive elements.
I created this algorithm, but it doesn't work for 4 test. I don't know where is a mistake
n, k = map(int, input().split())
num = [int(i) % 2 for i in input().split()]
if (k - su... | Check if it's possible to divide sequence into k non-intersecting subsections with odd sums | *Subtractor is a set of consecutive elements.
I created this algorithm, but it doesn't work for 4 test. I don't know where is a mistake
n, k = map(int, input().split())
num = [int(i) % 2 for i in input().split()]
if (k - sum(num)) % 2 == 0:
print('YES')
else:
print('NO')
| [
"You can split a sequence into k subsequences each with odd sums if and only if the number of odd numbers is k plus a non-negative even number. Your code tests whether the number of odd numbers is k plus any (positive, zero or negative) even number.\nTry this:\nn, k = map(int, input().split())\nodds = sum(int(i) % ... | [
0
] | [] | [] | [
"algorithm",
"python",
"sequence"
] | stackoverflow_0074138525_algorithm_python_sequence.txt |
Q:
Can we really do parallel computing using numba python library in python?
I am new to CUDA and was going through Running Python script on GPU. Performance with GPU is better than that without GPU (without GPU: 3.525673059999974, with GPU: 0.07701390800002628) for the following code executed in a colab notebook:
fr... | Can we really do parallel computing using numba python library in python? | I am new to CUDA and was going through Running Python script on GPU. Performance with GPU is better than that without GPU (without GPU: 3.525673059999974, with GPU: 0.07701390800002628) for the following code executed in a colab notebook:
from numba import jit, cuda
import numpy as np
# to measure exec time
from timei... | [
"You are confusing some basic concepts of computing here. The GIL makes the CPU code effectively-single threaded, but not the GPU one. In some way, the way you rung GPU code is you \"launch it\" or \"schedule\" it in this almost separate machine that is the GPU. So your code is a single threaded CPU that request co... | [
4
] | [] | [] | [
"cuda",
"gpu",
"numba",
"python"
] | stackoverflow_0074138637_cuda_gpu_numba_python.txt |
Q:
Transforming a string list into a list of int in pandas
my data look like this:
{569328: '[ 596005 4321416 5802640 6031690 6043910 8600475 8642629 9203255 9345445 10177065 10455451 13428248 22139349 22591458 24627241 24750476 26261826 26405611 27079105 27096884]',
574660: '[ 5956195 11260528 22181831 224... | Transforming a string list into a list of int in pandas | my data look like this:
{569328: '[ 596005 4321416 5802640 6031690 6043910 8600475 8642629 9203255 9345445 10177065 10455451 13428248 22139349 22591458 24627241 24750476 26261826 26405611 27079105 27096884]',
574660: '[ 5956195 11260528 22181831 22437920 22642946 23278096 23407037 23458128 24244657 24355363 2... | [
"Use dict comprehension with strip and split, last convert lists to integers, because empty list add if-else statement:\nd = {569328: '[ 596005 4321416 5802640 ]',\n 574660: '[ 5956195 ]',\n 1187498: []}\n \nd = {k: list(map(int, v.strip('[]').split())) if bool(v) else [] for k, v in d.items()}\nprint (d)... | [
1,
1,
0
] | [] | [] | [
"list",
"pandas",
"python"
] | stackoverflow_0074138176_list_pandas_python.txt |
Q:
Pands groupby stacked bar show same size for each class
I want to plot stacked bar graph using pandas. But i notice that length of each section in bar graph is same.
Here is the dataframe
sensor class mean
0 mq135 0.0 40
1 mq135 1.0 216
2 mq135 2.0 390
3 mq2 0.0 17
4 ... | Pands groupby stacked bar show same size for each class | I want to plot stacked bar graph using pandas. But i notice that length of each section in bar graph is same.
Here is the dataframe
sensor class mean
0 mq135 0.0 40
1 mq135 1.0 216
2 mq135 2.0 390
3 mq2 0.0 17
4 mq2 1.0 153
5 mq2 2.0 349
6 mq3 0.0 ... | [
"IIUC, you want to plot the mean column value in the bar\n(df.groupby(['sensor', 'class'])['mean'].sum()\n .unstack()\n .plot(kind='bar', stacked=True))\n\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074138490_matplotlib_pandas_python.txt |
Q:
Create dynamic updated graph with Python
I need your help to write a script in Python that will take dynamically changed data, the source of data is not matter here, and display graph on the screen.
I know how to use matplotlib, but the problem with matplotlib, that I can display graph only once, at the end of th... | Create dynamic updated graph with Python | I need your help to write a script in Python that will take dynamically changed data, the source of data is not matter here, and display graph on the screen.
I know how to use matplotlib, but the problem with matplotlib, that I can display graph only once, at the end of the script. I need to be able not only to displa... | [
"As an alternative to matplotlib, the Chaco library provides nice graphing capabilities and is in some ways better-suited for live plotting.\nSee some screenshots here, and in particular, see these examples:\n\ndata_stream.py\nspectrum.py\n\nChaco has backends for qt and wx, so it handles the underlying details for... | [
2,
2,
0,
0,
0,
0
] | [] | [] | [
"dynamic",
"graph",
"python"
] | stackoverflow_0005618620_dynamic_graph_python.txt |
Q:
Converting Excel to PDF with pywin32 [Error]
I try to export one of my xlsx files as PDF with pywin32:
# Import Module
from win32com import client
# Open Microsoft Excel
excel = client.Dispatch("Excel.Application")
# Read Excel File
sheets = excel.Workbooks.Open('C:/Users/xxx/MyExcel.xlsx')
work_sheets = she... | Converting Excel to PDF with pywin32 [Error] | I try to export one of my xlsx files as PDF with pywin32:
# Import Module
from win32com import client
# Open Microsoft Excel
excel = client.Dispatch("Excel.Application")
# Read Excel File
sheets = excel.Workbooks.Open('C:/Users/xxx/MyExcel.xlsx')
work_sheets = sheets.Worksheets[4]
# Convert into PDF File
work_... | [
"When using Python paths on Windows, you need to use \\\\ not /. So convert all your paths to use the double backslash instead of the forward slash:\nsheets = excel.Workbooks.Open('C:\\\\Users\\\\xxx\\\\MyExcel.xlsx')\n...\nwork_sheets.ExportAsFixedFormat(0,'C:\\\\Users\\\\xxx\\\\MyPDF.pdf')\n\nYour ExportAsFixedFo... | [
0
] | [] | [] | [
"excel",
"pdf",
"python",
"pywin32",
"win32com"
] | stackoverflow_0074138458_excel_pdf_python_pywin32_win32com.txt |
Q:
How to read from stdin Linux and set it as input in python
This is a sample code:
var1 = float(input('Enter time interval: '))
print(f'OK, time interval is {var1}')
# doing something with above variable
I want to run this python file like this without changing the code if possible:
python file.py 0<'15'
But I ge... | How to read from stdin Linux and set it as input in python | This is a sample code:
var1 = float(input('Enter time interval: '))
print(f'OK, time interval is {var1}')
# doing something with above variable
I want to run this python file like this without changing the code if possible:
python file.py 0<'15'
But I get this error:
-bash: 15: No such file or directory
| [
"You can provide the input through a pipe:\necho 15 | python file.py\n\nOr, with lesser known syntax, using process substitution, which I'm mentioning because it seems like this is what you were trying to do:\npython file.py < <(echo 15)\n\nIn both cases, be aware of the shell's quoting rules and add quotes accordi... | [
1,
1
] | [] | [] | [
"bash",
"linux",
"python"
] | stackoverflow_0074138741_bash_linux_python.txt |
Q:
Python glob where file names look like regexes
I have an interesting issue that I can't resolve, maybe someone has seen it before.
The simplified example is as follows: we have a directory called "a[2-1]" that we list the files in using glob.glob(f"{path}/*"). Glob reads the argument as a regex and crashes because... | Python glob where file names look like regexes | I have an interesting issue that I can't resolve, maybe someone has seen it before.
The simplified example is as follows: we have a directory called "a[2-1]" that we list the files in using glob.glob(f"{path}/*"). Glob reads the argument as a regex and crashes because 2-1 is not a valid interval. It looks like the [] a... | [
"The glob-doc says that the match is done with fnmatch. It tells you:\n\nFor a literal match, wrap the meta-characters in brackets. For example, '[?]' matches the character '?'.\n\nSo you should use:\nglob.glob('a[[]2-1[]]*')\n\n"
] | [
1
] | [] | [] | [
"glob",
"python"
] | stackoverflow_0074138647_glob_python.txt |
Q:
Excluding rightmost edge in numpy.histogram
I have a list of numbers a and a list of bins which I shall use to bin the numbers in a using numpy.histogram. the bins are calculated from the mean and standard deviation (std) of a. So the number of bins is B, and the minimum value of the first bin is mean - std, the m... | Excluding rightmost edge in numpy.histogram | I have a list of numbers a and a list of bins which I shall use to bin the numbers in a using numpy.histogram. the bins are calculated from the mean and standard deviation (std) of a. So the number of bins is B, and the minimum value of the first bin is mean - std, the maximum of the last bin being mean + std. (The tex... | [
"Here's one (kind of crude?) way to turn the make the last bin half-open instead of closed. What I'm doing is subtracting the smallest possible value from the right side of the right-most bin:\na = np.array([1, 1, 3, 2, 2, 6])\nB = 3 # (in this example) \nbins = np.linspace(a.mean() - a.std(), a.mean() + a.std(), B... | [
2,
1
] | [] | [] | [
"binning",
"histogram",
"numpy",
"python"
] | stackoverflow_0062726096_binning_histogram_numpy_python.txt |
Q:
How to transform pandas dataframe into specific dictionary?
I have a pandas dataframe:
id val label
"a1" "ab" "first"
"a1" "aa" "second"
"a1" "ca" "third"
"b1" "cc" "first"
"b1" "kf" "second"
"b1" "ff" "third"
"c1" "wer" "first"
"c1" "iid" "... | How to transform pandas dataframe into specific dictionary? | I have a pandas dataframe:
id val label
"a1" "ab" "first"
"a1" "aa" "second"
"a1" "ca" "third"
"b1" "cc" "first"
"b1" "kf" "second"
"b1" "ff" "third"
"c1" "wer" "first"
"c1" "iid" "second"
"c1" "ff" "third"
I want to transform it into di... | [
"You can groupby on id with a lambda function to convert the label/val pairs into a dict, then to_dict on the result to get your desired output:\ndf.groupby('id').apply(lambda x:dict(zip(x['label'], x['val']))).to_dict()\n\nOutput for your sample data:\n{\n 'a1': {'first': 'ab', 'second': 'aa', 'third': 'ca'},\n 'b... | [
1,
1
] | [] | [] | [
"dataframe",
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0074138678_dataframe_dictionary_python_python_3.x.txt |
Q:
(Pymongo) Print/show what I just delete
I want to print what I just deleted by pymongo
the main function
def del_data(del_values_json ,one_or_many_bool ):
if one_or_many_bool:
x = mycol.delete_many(del_values_json)
else:
x = mycol.delete_one(del_values_json)
retrun x
number_of_delete_data... | (Pymongo) Print/show what I just delete | I want to print what I just deleted by pymongo
the main function
def del_data(del_values_json ,one_or_many_bool ):
if one_or_many_bool:
x = mycol.delete_many(del_values_json)
else:
x = mycol.delete_one(del_values_json)
retrun x
number_of_delete_data = int(x.deleted_count)
modified_data_list... | [
"The DeleteResult object only returns the number of items deleted. Once an item is deleted it will no longer occur in the collection so this fragment of code:\nmodified_data_list = []\nfor modified_data in mycol.find().sort(\"_id\", -1).limit(number_of_delete_data):\n print(modified_data)\n modified_d... | [
1
] | [] | [] | [
"mongodb",
"pymongo",
"pymongo_3.x",
"python"
] | stackoverflow_0074134967_mongodb_pymongo_pymongo_3.x_python.txt |
Q:
How can I 'clean up' a virtualenv?
If I want to keep my venv as clean as possible how can I clean up the stuff I don't need? Let me lay out an example...
Say I try a bunch of new modules...
pip install foo
pip install bar
pip install foobar
pip install foobarfoo
and these modules have some requirements of their o... | How can I 'clean up' a virtualenv? | If I want to keep my venv as clean as possible how can I clean up the stuff I don't need? Let me lay out an example...
Say I try a bunch of new modules...
pip install foo
pip install bar
pip install foobar
pip install foobarfoo
and these modules have some requirements of their own, etc. later I decide on which one I w... | [
"To uninstall every package (including dependencies) you can freeze the requirements and then pass them to pip uninstall:\npip freeze > to-uninstall.txt\npip uninstall -r to-uninstall.txt\n\n",
"The following works for me (can be executed from any Python 3.6 virtualenv):\nvirtualenv --clear your-env-name\n\nWhere... | [
37,
16,
10,
6,
5,
5,
1,
1,
0
] | [
"pip uninstall followed by one or more package names will remove the packages from the virtual environment.\nPython Documentation\n"
] | [
-1
] | [
"pip",
"python",
"virtualenv"
] | stackoverflow_0035075812_pip_python_virtualenv.txt |
Q:
Forwarding stdout and stderr to logger in Prefect 2 flows
I have a couple of old ETL jobs that need to be adopted to Prefect flows. All of them are utilizing print statements for logging. Jobs should be backward-compatible and keep printing existing messaged to stdout and stderr. The issue is that stout and stderr... | Forwarding stdout and stderr to logger in Prefect 2 flows | I have a couple of old ETL jobs that need to be adopted to Prefect flows. All of them are utilizing print statements for logging. Jobs should be backward-compatible and keep printing existing messaged to stdout and stderr. The issue is that stout and stderr messages are ignored by Orion UI for viewing logs.
Long story ... | [
"For now I've made a workaround that works fine, but seems pretty heavy comparing to how it was in v1.\nclass Logger:\n def __init__(self, level):\n self.level = level\n\n def write(self, message):\n if message != '\\n':\n self.level(message)\n\n def flush(self):\n self.leve... | [
2,
1
] | [] | [] | [
"logging",
"prefect",
"python",
"stdout"
] | stackoverflow_0074138833_logging_prefect_python_stdout.txt |
Q:
How can I save the coordinates of bounding boxes of Tensorflow object detection in a csv file?
I am currently working with the full course on Tensorflow object detection on youtube. Find the video here.
I am currently applying the code for "detection from the Webcam" to a video and now I am trying to sum up the de... | How can I save the coordinates of bounding boxes of Tensorflow object detection in a csv file? | I am currently working with the full course on Tensorflow object detection on youtube. Find the video here.
I am currently applying the code for "detection from the Webcam" to a video and now I am trying to sum up the detections in an excel or csv file. In detail, I need to have a file with every detection, its positio... | [
"tf.image.draw_bounding_boxes( ) input is tf.constant( ) you can direct save to target file.\nSample: On the working function you remark the image display and save it with panda. Love concatenate, accumulate data create summaries.\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"... | [
0
] | [] | [] | [
"artificial_intelligence",
"object_detection",
"python",
"tensorflow"
] | stackoverflow_0074137408_artificial_intelligence_object_detection_python_tensorflow.txt |
Q:
How to extract a string that has certain specific pattern with mix of dynamic and static characters in Python using regex
I have a string as below
33f04e43cc6","from":"/ABC001/data/ZZZ000_logger_v1_20221010053935242_1.zip","to":"/ABC001/data/ZZZ000_logger_v1_20221010053935242_1.zip","remove":true,"objectId":"229b... | How to extract a string that has certain specific pattern with mix of dynamic and static characters in Python using regex | I have a string as below
33f04e43cc6","from":"/ABC001/data/ZZZ000_logger_v1_20221010053935242_1.zip","to":"/ABC001/data/ZZZ000_logger_v1_20221010053935242_1.zip","remove":true,"objectId":"229bea5a-c9b0-4ad0-aecc-84a63bc7dc6f"}2022-10-10
05:39:35,247 Platform.Interface: Published message to topic:
{"id":"a32e6cbe-94d4... | [
"Try this,\nIn [1]: re.match(r'.*data/([^\"]+).*', s).group(1)\nOut[1]: 'ZZZ000_logger_v1_20221010053935242_1.zip'\n\nRegex diagram. Demo\n\n",
"As suggested by Rahul I used it in a similar pattern with slight changes.\nregex = re.compile(\".{0,}data/([^\\\"]{1,}).{0,}\")\ntestString = '*****'\nmatchArray = regex... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074126774_python_regex.txt |
Q:
Can I use an existing Python sqlite connection with a QSqlDatabase?
This project is in Python and will have an sqlite3 database.
I would like to open the sqlite3 database using Python's sqlite3 module. But I also want to have functionality from the PySide6.QtSql module.
PySide's documentation shows an example of t... | Can I use an existing Python sqlite connection with a QSqlDatabase? | This project is in Python and will have an sqlite3 database.
I would like to open the sqlite3 database using Python's sqlite3 module. But I also want to have functionality from the PySide6.QtSql module.
PySide's documentation shows an example of this happening with Postgres.
con = PQconnectdb("host=server user=bart pas... | [
"Those driver classes are only available in C++. There's no way for PySide or PyQt to wrap them because the drivers are implemented as plugins. There's also no way to directly register any kind of extension, adapter, aggregator etc using the Qt classes via Python. It can only be done via C++.\nPython's SQLite imple... | [
2
] | [] | [] | [
"pyqt",
"pyside",
"python",
"qtsql",
"sqlite"
] | stackoverflow_0074117804_pyqt_pyside_python_qtsql_sqlite.txt |
Q:
Python 2.7.11 pip not installed
I have Python 2.7.11 installed on my machine which to my understanding should come with pip, however when I check the C:\Python27\Tools\Scripts\ directory there is no pip.exe present.
I have tried completely removing and reinstalling Python 2.7.11 without success. Running the insta... | Python 2.7.11 pip not installed | I have Python 2.7.11 installed on my machine which to my understanding should come with pip, however when I check the C:\Python27\Tools\Scripts\ directory there is no pip.exe present.
I have tried completely removing and reinstalling Python 2.7.11 without success. Running the installer pip is set to be installed, but ... | [
"I encountered the same problem - pip not installed - with python-2.7.16, Win10, installing for 'all users'. It was resolved when I allowed the MSI installer to target the default location (C:\\Python27) rather than changing it to under Program Files (x86). I've no clue why this changed anything. \n",
"python2.7.... | [
5,
3,
3,
2,
0,
0,
0,
0,
0
] | [
"It happens on windows as you should have admin rights to install anything on disk C.\nI have the same issue Scripts folder was not installed. I would sugest to instal it on disk D.\n"
] | [
-1
] | [
"pip",
"python",
"python_2.7",
"windows"
] | stackoverflow_0039155669_pip_python_python_2.7_windows.txt |
Q:
Why does nn.Conv1d work on 2d feature [b, c, h, w]?
I am wondering why conv1d works on 2d feature(batch, channel, height, width).
An nn.Conv1d(channel, channel, kernel_size=(1,1)) works when I put 2d feature, but gives different result from nn.Conv2d(channel, channel, kernel_size=1).
I want to know why conv1d work... | Why does nn.Conv1d work on 2d feature [b, c, h, w]? | I am wondering why conv1d works on 2d feature(batch, channel, height, width).
An nn.Conv1d(channel, channel, kernel_size=(1,1)) works when I put 2d feature, but gives different result from nn.Conv2d(channel, channel, kernel_size=1).
I want to know why conv1d works and what it mean by 2d kernel size in 1d convolution.
| [
"\"I want to know why conv1d works and what it mean by 2d kernel size in 1d convolution\"\nIt doesn't have any reason not to work. Under the hood all this \"convolution\" means is \"Dot Product\", now it could be between matrix and vector, matrix and matrix, vector and vector, etc. Simply put, the real distinction ... | [
1,
1
] | [] | [] | [
"convolution",
"neural_network",
"python",
"pytorch"
] | stackoverflow_0065790139_convolution_neural_network_python_pytorch.txt |
Q:
How to add column name in single string?
I have a code where I'm flattening the jsonb columns so I have written a code something like this
{% set survey_methods_query %}
SELECT DISTINCT(jsonb_object_keys(_airbyte_data)) as column_name
from {{source('survey-cto', 'raw_surveycto')}}
{% endset %}
{% set results = ... | How to add column name in single string? | I have a code where I'm flattening the jsonb columns so I have written a code something like this
{% set survey_methods_query %}
SELECT DISTINCT(jsonb_object_keys(_airbyte_data)) as column_name
from {{source('survey-cto', 'raw_surveycto')}}
{% endset %}
{% set results = run_query(survey_methods_query) %}
{% if exec... | [
"JSON field names need to be wrapped in single quotes to be selected in postgresql so you can change your Jinja to have single quotes around the column name.\n_airbyte_data->>'{{ column_name }}' as {{ column_name }}\nOr update your query to include the single quotes in the initial SELECT\nSELECT concat('''', DISTIN... | [
1
] | [] | [] | [
"dbt",
"postgresql",
"python"
] | stackoverflow_0074136932_dbt_postgresql_python.txt |
Q:
Converting int to float with known precision
I've exported my location data from Google but one thing they have in the resulting json is that both latitudes and longitudes are stored as integers. For example:
-37785037 # latitude
144939405 # longitude
Since I know where I roughly was at that time it's clear th... | Converting int to float with known precision | I've exported my location data from Google but one thing they have in the resulting json is that both latitudes and longitudes are stored as integers. For example:
-37785037 # latitude
144939405 # longitude
Since I know where I roughly was at that time it's clear that the actual coords are -37.785.. and 144.939...,... | [
"If precision is fixed, simply dividing your value by 1e6 will give you the correct answer:\n-37785037/1e6=-37.785037\n"
] | [
1
] | [] | [] | [
"python",
"type_conversion"
] | stackoverflow_0074139037_python_type_conversion.txt |
Q:
Database connection in a running Microservice process
I run into some issues with open database connections in a flask process.
Setup
flask app running
import psycopg2, json
from flask_cors import CORS
from flask import Flask, Response, request
app = Flask(__name__)
CORS(app)
db_connection = psycopg2.connect(host... | Database connection in a running Microservice process | I run into some issues with open database connections in a flask process.
Setup
flask app running
import psycopg2, json
from flask_cors import CORS
from flask import Flask, Response, request
app = Flask(__name__)
CORS(app)
db_connection = psycopg2.connect(host="some_host_address", port="some_port", database="some_db_n... | [
"Without seeing exactly what you're setup is/network topology it's hard to answer why you're seeing connections fail after a period of 12 hours.\nYou could write your own connection pool system that would keep long running connections alive, handle when they disconnect and avoid the start up time hit on every reque... | [
1
] | [] | [] | [
"flask",
"microservices",
"networking",
"postgresql",
"python"
] | stackoverflow_0074138388_flask_microservices_networking_postgresql_python.txt |
Q:
How to drop rows if text in column if fully latin?
i have a dataframe with column sent:
sent
"error was found"
"я ищу новый error"
"загрузка завершена"
"new file is uploaded"
as you see some rows are fully latin strings, some are mixed and some are fully non-latin. i'd like to drop rows with fully latin string ro... | How to drop rows if text in column if fully latin? | i have a dataframe with column sent:
sent
"error was found"
"я ищу новый error"
"загрузка завершена"
"new file is uploaded"
as you see some rows are fully latin strings, some are mixed and some are fully non-latin. i'd like to drop rows with fully latin string rows. so desired output is:
sent
"я ищу новый error"
"загр... | [
"You can remove lines that has no Cyrillic letters.\nimport pandas as pd\n\nsent = [\"error was found\",\n\"я ищу новый error\",\n\"загрузка завершена\",\n\"new file is uploaded\"]\n\ndf = pd.DataFrame(sent, columns=['sent'])\ndf = df[df['sent'].str.contains('[а-яА-Я]')] # filter dataframe\n\nprint(df)\n\nOutput\n ... | [
-1
] | [] | [] | [
"dataframe",
"filter",
"python",
"python_3.x"
] | stackoverflow_0074139026_dataframe_filter_python_python_3.x.txt |
Q:
How to properly reuse a session while multiprocessing
I have some python code that is listening to a socket connection and processes tasks that it receives via that socket. The python code has a multiprocessing pool in it that takes care of these tasks. (A task is assigned to some process in the pool)
These tasks ... | How to properly reuse a session while multiprocessing | I have some python code that is listening to a socket connection and processes tasks that it receives via that socket. The python code has a multiprocessing pool in it that takes care of these tasks. (A task is assigned to some process in the pool)
These tasks involve an API request and I noticed that each time it is d... | [
"What is taking place there is that Multiprocessing Pool actually delays the creation of workers until they are needed, or there is some \"idle\" time.\nBy simply adding more information to the prints, that is clearly visible - what is taking place is that the single line tasks finish so fast they are actually all ... | [
2,
1
] | [] | [] | [
"multiprocessing",
"python",
"python_requests"
] | stackoverflow_0074129088_multiprocessing_python_python_requests.txt |
Q:
How do I nest multiprocessing in multiprocessing, with common variables (python)?
I have a function which is running twice in two parallel processes. Lets call it - parentFunction().
Each process ends with a dictionary which is added to a common list which gives a list of two dictionaries. This I solved by using p... | How do I nest multiprocessing in multiprocessing, with common variables (python)? | I have a function which is running twice in two parallel processes. Lets call it - parentFunction().
Each process ends with a dictionary which is added to a common list which gives a list of two dictionaries. This I solved by using preset list using manager.
Now, inside parentFunction() L would like to run two parallel... | [
"The source you posted does not seem to match your stack trace. You would only get a FileNotFoundException when the main process tries to enumerate any objects within list L with a statement such as print(list(L)), which I see in the stack trace but not in your code. It helps when you post the actual code causing t... | [
1
] | [] | [] | [
"dataframe",
"multiprocessing",
"pandas",
"python",
"python_multiprocessing"
] | stackoverflow_0074138410_dataframe_multiprocessing_pandas_python_python_multiprocessing.txt |
Q:
Pandas update a date column
I wish to update dates in date column based on a condition. But i'm unable to get it working:
d_ = {
'id': [1,2,3],
'dt1': ['28-10-2016', '18-11-2016', '21-12-2016'],
}
df = pd.DataFrame(d_)
df['dt1'] = pd.to_datetime(df['dt1'])
df
id dt1
1 2016-10-28
2 2016-11-18
3 2016... | Pandas update a date column | I wish to update dates in date column based on a condition. But i'm unable to get it working:
d_ = {
'id': [1,2,3],
'dt1': ['28-10-2016', '18-11-2016', '21-12-2016'],
}
df = pd.DataFrame(d_)
df['dt1'] = pd.to_datetime(df['dt1'])
df
id dt1
1 2016-10-28
2 2016-11-18
3 2016-12-21
df['dt1'] = np.where(df['... | [
"Use loc to avoid conversion to numpy array:\ndf.loc[df['id']==1, 'dt1'] = pd.to_datetime('2018-01-01')\n\nOr mask:\ndf['dt1'] = df['dt1'].mask(df['id']==1, pd.to_datetime('2018-01-01'))\n\noutput:\n id dt1\n0 1 2018-01-01\n1 2 2016-11-18\n2 3 2016-12-21\n\n",
"You can use df.apply() to prevent con... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074138323_dataframe_pandas_python.txt |
Q:
How to run my code on files from different folders?
a=np.array(h5py.File('/Users/D/Desktop/Files500/1/FIELD-3D.h5', 'r')['Zone']['TOp']['data'])
#iterations
a=a.flatten(order='C')
iter_num = 10; i=iter_num
while i < x:
a = np.insert(a, i, (a[i]+a[i-1])/2)
i += iter_num
np.savetxt('merged.csv',a.flatten(... | How to run my code on files from different folders? | a=np.array(h5py.File('/Users/D/Desktop/Files500/1/FIELD-3D.h5', 'r')['Zone']['TOp']['data'])
#iterations
a=a.flatten(order='C')
iter_num = 10; i=iter_num
while i < x:
a = np.insert(a, i, (a[i]+a[i-1])/2)
i += iter_num
np.savetxt('merged.csv',a.flatten(order='C'),delimiter=',')
I have 500 folders and have a ... | [
"Iterate number 1..500 and replace the folder number in the path for both .h5 and .csv files\nfor i in range(1, 501):\n a=np.array(h5py.File(f'/Users/D/Desktop/Files500/{i}/FIELD-3D.h5', 'r')['Zone']['TOp']['data'])\n #iterations\n a=a.flatten(order='C')\n iter_num = 10; i=iter_num\n while i < x:\n ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074139165_python.txt |
Q:
use_cuda is set True even though it was specified as False T5
I am trying to train a T5 model using simpletransformers. Here is my code:
from simpletransformers.t5 import T5Model
model_args = {
"max_seq_length": MAX_LEN,
"train_batch_size": 8,
"eval_batch_size": 8,
"num_train_epochs": 1,
"evalu... | use_cuda is set True even though it was specified as False T5 | I am trying to train a T5 model using simpletransformers. Here is my code:
from simpletransformers.t5 import T5Model
model_args = {
"max_seq_length": MAX_LEN,
"train_batch_size": 8,
"eval_batch_size": 8,
"num_train_epochs": 1,
"evaluate_during_training": True,
"evaluate_during_training_steps": 1... | [
"You need to pass in the arg use_cuda to the call to the T5Model constructor, not in your model_args dict.\nfrom simpletransformers.t5 import T5Model\n\nmodel_args = {...}\n\nmodel = T5Model('t5', 't5-base', args=model_args, use_cuda=False)\n\n"
] | [
2
] | [] | [] | [
"huggingface_transformers",
"nlp",
"python",
"simpletransformers"
] | stackoverflow_0074138756_huggingface_transformers_nlp_python_simpletransformers.txt |
Q:
Draw path on heatmap Python
I have a vector x with length N=n**2=625 which I simply plot with imshow by reshaping into a matrix, which is essentially a 2D topographical map.
plt.imshow(x.reshape((n,n)),cmap="magma",origin="lower")
I also have a given connected path with the some indices of the vector x, e.g
path ... | Draw path on heatmap Python | I have a vector x with length N=n**2=625 which I simply plot with imshow by reshaping into a matrix, which is essentially a 2D topographical map.
plt.imshow(x.reshape((n,n)),cmap="magma",origin="lower")
I also have a given connected path with the some indices of the vector x, e.g
path = np.array([1, 2, 27, 28, 54,55,5... | [
"IIUC, you can use numpy.unravel_index to convert your coordinates:\nimport matplotlib.pyplot as plt\nn=25\nx = np.arange(n**2)\nax = plt.imshow(x.reshape((n,n)),cmap=\"magma\",origin=\"lower\", alpha=0.2)\nX, Y = np.unravel_index(np.array([1, 2, 27, 28, 54,55,56,81,106,131]), (n, n))\nplt.plot(Y, X)\n\nExample:\n\... | [
1
] | [] | [] | [
"line_plot",
"matplotlib",
"numpy",
"plot",
"python"
] | stackoverflow_0074138927_line_plot_matplotlib_numpy_plot_python.txt |
Q:
How to remove directory and show only file name in tkinter?
im trying to make only the file name show up using filedialog
here's the example :
import tkinter as tk
import pygame
from tkinter import filedialog
root = tk.Tk()
controls_frame = tk.Frame(root)
controls_frame.pack()
def add_name():
name = filedia... | How to remove directory and show only file name in tkinter? | im trying to make only the file name show up using filedialog
here's the example :
import tkinter as tk
import pygame
from tkinter import filedialog
root = tk.Tk()
controls_frame = tk.Frame(root)
controls_frame.pack()
def add_name():
name = filedialog.askopenfile()
names.insert(filedialog.END,name)
names = ... | [
"The module os can help with this:\nimport os\n\n def add_name():\n name = os.path.basename(str(filedialog.askopenfile()))\n name = name.replace(\"' mode='r' encoding='UTF-8'>\", \"\")\n names.insert(filedialog.END,name)\n\n",
"You can do it like this.\nI found this solution on another pos... | [
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0064917839_python_tkinter.txt |
Q:
Why doesn't my PyQt USB serial connection work until after I've connected with another serial monitor?
I have a Raspberry Pi Pico connected via USB to a Windows 10 PC running a Python script using PyQt.
I've found that the serial comms (over USB) between my Pico and the Python script on the PC doesn't work. If I o... | Why doesn't my PyQt USB serial connection work until after I've connected with another serial monitor? | I have a Raspberry Pi Pico connected via USB to a Windows 10 PC running a Python script using PyQt.
I've found that the serial comms (over USB) between my Pico and the Python script on the PC doesn't work. If I open a connection using Arduino's Serial Monitor, or using pyserial, it does work. You'd think this would be ... | [
"I could solve the issue with the information of Windows COM access to PICO via USB trouble.\nAfter you opened the port, call this\nQSerialPort::setDataTerminalReady(true)\n\n"
] | [
0
] | [] | [] | [
"pyqt",
"python",
"qtserialport",
"raspberry_pi_pico"
] | stackoverflow_0071392985_pyqt_python_qtserialport_raspberry_pi_pico.txt |
Q:
ImportError: cannot import name 'Profile' from partially initialized module 'profiles.models' (most likely due to a circular import)
I am importing Profile from profiles.models into meta.models, but showing the subject error. Can't find cutom solution, even though there are similar problems with different solution... | ImportError: cannot import name 'Profile' from partially initialized module 'profiles.models' (most likely due to a circular import) | I am importing Profile from profiles.models into meta.models, but showing the subject error. Can't find cutom solution, even though there are similar problems with different solutions out there but not working in my case.
Here is my profiles.models
from django.db import models
from django.contrib.auth.models import Use... | [
"To summarize the issues:\n1/ To avoid cicular imports, you can use strings to declare foreign key target model, syntax: \"app.Model\".\nclass PlaceOfPosting(models.Model):\n UserProfile = models.OneToOneField(\"profiles.Profile\", on_delete=models.CASCADE)\n\n2/ On_delete is not available on ManyToManyField s... | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074139160_django_django_models_python.txt |
Q:
Creating a subplot of images with plotly
I wanted to display the first 10 images from the mnist dataset with plotly. This is turning out to be more complicated than I thought. This does not work:
import numpy as np
np.random.seed(123)
import plotly.express as px
from keras.datasets import mnist
(X_train, y_train... | Creating a subplot of images with plotly | I wanted to display the first 10 images from the mnist dataset with plotly. This is turning out to be more complicated than I thought. This does not work:
import numpy as np
np.random.seed(123)
import plotly.express as px
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
fig ... | [
"this worked - I hope this is not the final answer:\nfig = subplots.make_subplots(rows=2, cols=5)\n\nfor n, image in enumerate(X_train[:10]):\n fig.add_trace(px.imshow(255-image).data[0], row=int(n/5)+1, col=n%5+1)\n\n# the layout gets lost, so we have to carry it over - but we cannot simply do\n# fig.layout = lay... | [
6,
1
] | [] | [] | [
"jupyter_notebook",
"plotly",
"python"
] | stackoverflow_0064268081_jupyter_notebook_plotly_python.txt |
Q:
How to create a binary file with python?
I want to create a binary file in python so that will be according to following pattern:
4 bytes - zeros
16 bytes - this number 1010101010101010
How can I do it in python?
I tried to do it in the following way, but i don't sure that it's correct:
f = open('file', 'w+b')
r... | How to create a binary file with python? | I want to create a binary file in python so that will be according to following pattern:
4 bytes - zeros
16 bytes - this number 1010101010101010
How can I do it in python?
I tried to do it in the following way, but i don't sure that it's correct:
f = open('file', 'w+b')
res = struct.pack(">l", 0000)
f.write(res)
I t... | [] | [] | [
"If you not sure, use\nprint(open(\"file\", \"rb\").read())\n\nto check\n"
] | [
-1
] | [
"binary",
"binaryfiles",
"python",
"python_3.x"
] | stackoverflow_0074139170_binary_binaryfiles_python_python_3.x.txt |
Q:
Why I can't parse timestamp in pyarrow?
I have a JSON file with that variable:
"BirthDate":"2022-09-05T08:08:46.000+00:00"
And I want to create parquet based on that file. I prepared fixed schema for pyarrow where BirthDate is a pa.timestamp('s'). And when I trying to convert that file I got error:
ERROR:root:Fai... | Why I can't parse timestamp in pyarrow? | I have a JSON file with that variable:
"BirthDate":"2022-09-05T08:08:46.000+00:00"
And I want to create parquet based on that file. I prepared fixed schema for pyarrow where BirthDate is a pa.timestamp('s'). And when I trying to convert that file I got error:
ERROR:root:Failed of conversion of JSON to timestamp[s], co... | [
"It works for me using pa.field(\"BirthDate\", pa.timestamp('ms')).\nI think it's because your timestamps have got millisecond precision (even though they have their milliseconds set to zero)\n\nimport pyarrow.json as pyarrow_json\nimport pyarrow as pa\n\nprepared_schema = pa.schema([pa.field(\"BirthDate\", pa.time... | [
1
] | [] | [] | [
"json",
"parquet",
"pyarrow",
"python"
] | stackoverflow_0074138746_json_parquet_pyarrow_python.txt |
Q:
Azure Storage Account: How to rename/move a Blob within a Container
I am using Microsoft Azure SDK for Python and I want to move or rename a Blob within the same container.
For example, how to move this blob
https://demostorage.blob.core.windows.net/container-a/folder1/file1.jpg
into this?
https://demostorage.bl... | Azure Storage Account: How to rename/move a Blob within a Container | I am using Microsoft Azure SDK for Python and I want to move or rename a Blob within the same container.
For example, how to move this blob
https://demostorage.blob.core.windows.net/container-a/folder1/file1.jpg
into this?
https://demostorage.blob.core.windows.net/container-a/folder2/file2.jpg
| [
"After reproducing from my end I could able to achieve this using copy_blob of azure-storage versioned 0.20.0.\nfrom azure.storage.blob import BlobService\n\naccountName = \"<YourAccountName>\"\naccountKey = \"<YourAccountKey>\"\n\nblob_service = BlobService(accountName ,accountKey )\nsourceFileName = 'file1.png'\n... | [
0
] | [] | [] | [
"azure_blob_storage",
"azure_sdk_python",
"python"
] | stackoverflow_0073941246_azure_blob_storage_azure_sdk_python_python.txt |
Q:
How does dot operator relate to Namespaces?
As i was going through python basics and introduction one thing that really confuses me is namespaces. I cant seem to understand how they work.
For instance in Cs50 course they brush over the concept but i wanted to get clearer understanding of it if possible because it ... | How does dot operator relate to Namespaces? | As i was going through python basics and introduction one thing that really confuses me is namespaces. I cant seem to understand how they work.
For instance in Cs50 course they brush over the concept but i wanted to get clearer understanding of it if possible because it seems very important to grasp. For example this c... | [
"You import cs50, so you have a name \"cs50\", you can use\ncs50.get_int()\n\nbut namespaces has no name get_int.\nYou can use from cs50 import get_int to import name \"get_int\"\n",
"To answer this question, let's talk about modules.\nIn Python, \"module\" is used to refer to two things. First, a piece of code, ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074139052_python.txt |
Q:
Packages that work with networkx that can handle clickable nodes
I'm looking to try and visualize data using networkx as a network graph. My data looks great, but i'm wanting to add on hover and on click events to display additional information.
For example, there might be a node called "New York", when clicked wi... | Packages that work with networkx that can handle clickable nodes | I'm looking to try and visualize data using networkx as a network graph. My data looks great, but i'm wanting to add on hover and on click events to display additional information.
For example, there might be a node called "New York", when clicked will display a small table to the side of the canvas that gives informat... | [
"I maintain a python library for network visualisations called netgraph, which works nicely with networkx or igraph Graph objects. I thought this was a neat idea for a feature, so I just implemented a bare bones version on the dev branch.\n\nInstallation via pip:\npip install https://github.com/paulbrodersen/netgra... | [
5,
1,
0
] | [] | [] | [
"click",
"events",
"networkx",
"python",
"pyvis"
] | stackoverflow_0070281628_click_events_networkx_python_pyvis.txt |
Q:
How to calculate mean relative error on test datasets
def create_model():
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(40002, 12)))
model.add(LSTM(50, return_sequences= True))
model.add(LSTM(50, return_sequences= True))
model.add(tf.keras.layers.LSTM(30))
mode... | How to calculate mean relative error on test datasets | def create_model():
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(40002, 12)))
model.add(LSTM(50, return_sequences= True))
model.add(LSTM(50, return_sequences= True))
model.add(tf.keras.layers.LSTM(30))
model.add(Dense(2, activation='linear'))
def rmse(Y_test, ... | [
"Would have added like this:\nfrom tensorflow.math import reduce_mean, abs, reduce_sum\n\nrelative_error = reduce_mean(reduce_sum(abs(prediction-Y_test)/prediction, axis=1))\n# [0.9, 0.54285717]\n\nmean_relative_error = reduce_mean(relative_error)\n# 0.7214286\n\nI couldn't use tf.keras.losses.MeanAbsoluteError(red... | [
1
] | [] | [] | [
"keras",
"lstm",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0074138837_keras_lstm_neural_network_python_tensorflow.txt |
Q:
In Pytest, cannot find global variable defined in fixture
I have following file called functions.py:
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
@pytest.fixture(scope='function', autouse=True)
def create_driver():
global driver
driver = webdriver.Chrome()
d... | In Pytest, cannot find global variable defined in fixture | I have following file called functions.py:
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
@pytest.fixture(scope='function', autouse=True)
def create_driver():
global driver
driver = webdriver.Chrome()
driver.get("https://www.google.com/")
yield
driver.quit(... | [
"This looks like abuse of the pytest fixtures functionality. There should be no need for global variables.\nI didn't test it, but something along these lines is how fixtures are supposed to be used:\nmy_fixtures.py\nfrom selenium import webdriver\nimport pytest\n\n@pytest.fixture # No need for autouse, and scope='... | [
1
] | [] | [] | [
"pytest",
"python",
"selenium"
] | stackoverflow_0074139249_pytest_python_selenium.txt |
Q:
sqlalchemy.exc.InvalidRequestError: Can't attach instance another instance with key is already present in this session
Here I have a mistake that I can't find the solution. Please excuse me for the quality of the code, I didn't start classes until 6 months ago. I've tried to detach category objects with expunge bu... | sqlalchemy.exc.InvalidRequestError: Can't attach instance another instance with key is already present in this session | Here I have a mistake that I can't find the solution. Please excuse me for the quality of the code, I didn't start classes until 6 months ago. I've tried to detach category objects with expunge but once it's added it doesn't work.I was thinking when detaching the object with expunge it will work. and I can't find a sol... | [
"This error happens when you try to add an object to a session but it is already loaded.\nThe only line that I see you use .add function is at the end where you run:\nconnection.connect.add(article)\nSo my guess is that this Model is already loaded in the session and you don't need to add it again. You can add a tr... | [
1,
1,
0
] | [] | [] | [
"python",
"python_3.x",
"sqlalchemy"
] | stackoverflow_0048601123_python_python_3.x_sqlalchemy.txt |
Q:
Python: populate list in dictionary from data in excel sheet using openpyxl
I am trying to take the below data from excel sheet and create a dictionary with a list of mac address values in this format siteinv_dict = {1741 : [XX:XX:XX:XX:XX:XX, YY:YY:YY:YY:YY:YY]}
The list of mac addresses vary from col to col.
Wh... | Python: populate list in dictionary from data in excel sheet using openpyxl | I am trying to take the below data from excel sheet and create a dictionary with a list of mac address values in this format siteinv_dict = {1741 : [XX:XX:XX:XX:XX:XX, YY:YY:YY:YY:YY:YY]}
The list of mac addresses vary from col to col.
When trying to do it for just one number to try get it working i was trying somethi... | [
"You can construct a deque by column of the workbook, then left pop everything off the deque using non-strings as keys and strings as a values list into a new dict.\nimport openpyxl\nfrom collections import deque\n\nwb = openpyxl.load_workbook('C:\\Site_Details.xlsx', data_only=True)\nsh = wb.active\n\nsiteinv_queu... | [
0
] | [] | [] | [
"excel",
"openpyxl",
"python"
] | stackoverflow_0074138844_excel_openpyxl_python.txt |
Q:
Python: When joining between python daframes, is it possible to match the included key value instead of the same key value?
When joining between python daframes, is it possible to match the included key value instead of the same key value?
For example
A
B
C
D
E
ABC
1
2
3
4
DEF
5
6
7
8
GHI
9
10
11
12
df_1 like... | Python: When joining between python daframes, is it possible to match the included key value instead of the same key value? | When joining between python daframes, is it possible to match the included key value instead of the same key value?
For example
A
B
C
D
E
ABC
1
2
3
4
DEF
5
6
7
8
GHI
9
10
11
12
df_1 like this. And
F
G
H
I
J
AB
13
14
15
16
DE
17
18
19
20
GH
21
22
23
24
df_2 like this.
A
B
C
D
E
G
H
I
... | [
"One solution - although a very slow one - would be to iterate through both dataframes, comparing substrings that exist in both dataframes. Here's how the code would look like:\nimport pandas as pd\n\n\ndef string_match(\n df1: pd.DataFrame, df2: pd.DataFrame, left_on: str, right_on: str\n):\n final = []\n ... | [
0,
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074134713_dataframe_python.txt |
Q:
How can we have SortedList as a parameter in SortedDict in Python?
I am trying to use SortedList from sortedcontainers library as a parameter for SortedDict. Even though the Initialization maps = SortedDict(SortedList()) worked. I am Unable to insert any data into the SortedDict maps
from sortedcontainers import... | How can we have SortedList as a parameter in SortedDict in Python? | I am trying to use SortedList from sortedcontainers library as a parameter for SortedDict. Even though the Initialization maps = SortedDict(SortedList()) worked. I am Unable to insert any data into the SortedDict maps
from sortedcontainers import SortedDict, SortedList
maps = SortedDict(SortedList)
maps[1] = [1,2]
... | [
"You are passing the class SortedList to the constructor of the SortedDict. What do you expect that to do?\nThe documentation explains what it actually does:\n\nOptional key-function argument defines a callable that, like the key argument to the built-in sorted function, extracts a comparison key from each dictiona... | [
2
] | [] | [] | [
"python",
"python_3.x",
"sortedcontainers",
"sorteddictionary",
"sortedlist"
] | stackoverflow_0074139331_python_python_3.x_sortedcontainers_sorteddictionary_sortedlist.txt |
Q:
Python Beginner question - Or function not working when writing a basic if statement?
age = float(input('enter age '))
if age != 10 or age != '11':
print('you are not 10 or 11. ')
else:
print('you are 10 or 11')
When i run this code it always prints ('you are not 10 or 11') regardless of age ?
A:
There... | Python Beginner question - Or function not working when writing a basic if statement? | age = float(input('enter age '))
if age != 10 or age != '11':
print('you are not 10 or 11. ')
else:
print('you are 10 or 11')
When i run this code it always prints ('you are not 10 or 11') regardless of age ?
| [
"There are several things not working here:\nage = float(input('enter age '))\n\nIf age is an integer, you should keep is an integer and not convert it to a float. Since you're a beginner, I won't go into detail, just mention that this can lead to unexpected problems. If you want to know more, read this:\nIs floati... | [
1,
0,
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0074139398_if_statement_python.txt |
Q:
pd.to_csv adding sep info as metadata to csv file
I have a basic code for saving a dataframe as .csv file with a semicolon separator, following:
df.to_csv(path, sep=';', encoding='utf-8', index=False)
And it saves, like:
df.csv
col1;col2;col3;col4
val1;val2;val3;val4
However, when I try to open df.csv wi... | pd.to_csv adding sep info as metadata to csv file | I have a basic code for saving a dataframe as .csv file with a semicolon separator, following:
df.to_csv(path, sep=';', encoding='utf-8', index=False)
And it saves, like:
df.csv
col1;col2;col3;col4
val1;val2;val3;val4
However, when I try to open df.csv with the Excel program, it automatically separates the co... | [
"I think the most pythonic might be to just read the first line, then read again the file:\nwith open('df.csv') as f:\n sep = f.readline().strip().split('=')[-1]\n print(f'separator: {sep}')\ndf = pd.read_csv('df.csv', skiprows=1, sep=sep)\nprint(df)\n\nIf you really want to open the file only once you can us... | [
0
] | [] | [] | [
"csv",
"excel",
"file",
"pandas",
"python"
] | stackoverflow_0074139512_csv_excel_file_pandas_python.txt |
Q:
Solving an optimisation problem with a 1D array, 1 constraint, and 1 optimisation criterion
What would be the best approach (method/function) to solve the following problem?
I have a (8760,1) array "Power", which is a time series of the machine operating power during a year with a 1 hour resolution. Each value flu... | Solving an optimisation problem with a 1D array, 1 constraint, and 1 optimisation criterion | What would be the best approach (method/function) to solve the following problem?
I have a (8760,1) array "Power", which is a time series of the machine operating power during a year with a 1 hour resolution. Each value fluctuates within a certain predefined range of 1:500 (maximum machine power).
Using values from thi... | [
"You're trying to solve an optimization problem. There are many Python packages that can help define your problem and solve it using an Open-source or Paid solver. I recommend using Pulp, if you're trying to solve a linear optimization problem (meaning you don't have any variable multiplication in your formulation)... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074138446_python.txt |
Q:
Rebasing a project when the file structure has changed
I'm working on a project hosted in Gitlab and I'm using Pycharm
I have my branch which I was working on, while the master branch has changed the file structure, how can I rebase against the new file structure and update my branch with it?
A:
By running git r... | Rebasing a project when the file structure has changed | I'm working on a project hosted in Gitlab and I'm using Pycharm
I have my branch which I was working on, while the master branch has changed the file structure, how can I rebase against the new file structure and update my branch with it?
| [
"By running git rebase. Either Git is clever enough to detect the structural changes and you are done. Or the structure has changed too much and you must resolve the conflicts manually at each commit that is being rebased.\nYou can try to play around with the find-renames strategy option:\ngit rebase -X find-rename... | [
0
] | [] | [] | [
"git",
"gitlab",
"python",
"rebase"
] | stackoverflow_0073406794_git_gitlab_python_rebase.txt |
Q:
Why doesn't 0.1+0.2-0.3 equal 0.0?
Why doesn't 0.1+0.2-0.3 equal 0.0 ? according to normal equation the result should be 0 but why isn't it?
Could someone please explain me the reason?
| Why doesn't 0.1+0.2-0.3 equal 0.0? | Why doesn't 0.1+0.2-0.3 equal 0.0 ? according to normal equation the result should be 0 but why isn't it?
Could someone please explain me the reason?
| [] | [] | [
"All programming languages including Python use 32-bit floating point representation for numbers. With decimal fractions, this floating-point number system causes some rounding errors which results in 0.1 + 0.2 == 0.3 as false.\nThe Actual Answer\nFor Example:\n1.2 is exactly equal to 1.1999999999999999555910790149... | [
-1
] | [
"add",
"floating_point",
"numbers",
"python"
] | stackoverflow_0074139295_add_floating_point_numbers_python.txt |
Q:
read multiple .dat file and extract specific information
I have multiple .dat files and all of them start with similar information at the beginning about the observation time, lat, long, and... .
After this text information, there are 16 columns of observed data. which looks like this:
#Occultation start (UTC): 20... | read multiple .dat file and extract specific information | I have multiple .dat files and all of them start with similar information at the beginning about the observation time, lat, long, and... .
After this text information, there are 16 columns of observed data. which looks like this:
#Occultation start (UTC): 2022-01-01 00:10:00
#Occultation stop (UTC): 2022-01-01 00:12:0... | [
"You forgot the brackets to call the method. You can specify the splitting criterium by passing a value to the sep-argument (default is whitespace), see doc for details.\na = data.split()\n\nthen slices a[14:15] will make sense hence TypeError: 'builtin_function_or_method' object is not subscriptable should be fi... | [
1,
0
] | [] | [] | [
"for_loop",
"python",
"sqlite"
] | stackoverflow_0074139310_for_loop_python_sqlite.txt |
Q:
Onnx Runtime Adding Multiple Initializers in Python
When trying to prepare the session options for onnx runtime I receive a onnxruntime.capi.onnxruntime_pybind11_state.RuntimeException when trying to add more than one initializer at a time.
See code
import onnxruntime
import numpy as np
params = {"fc1.weight": [... | Onnx Runtime Adding Multiple Initializers in Python | When trying to prepare the session options for onnx runtime I receive a onnxruntime.capi.onnxruntime_pybind11_state.RuntimeException when trying to add more than one initializer at a time.
See code
import onnxruntime
import numpy as np
params = {"fc1.weight": [3, 4], "fc1.bias": [3]}
options = onnxruntime.SessionOpti... | [
"Thanks to Pranav Sharma for this solution.\nIn the code above the second initializer overwrites the first one as you're using the same variable; the first one gets garbage collected and hence the pointer is not valid by the time session is constructed. For this API to work you need to keep the initializers around ... | [
3
] | [] | [] | [
"onnxruntime",
"python"
] | stackoverflow_0074139718_onnxruntime_python.txt |
Q:
How to convert csv file to dictionary so that top row is keys, and columns (in list form) are values (without numpy.loadtxt and panda)?
(To preface, I know/believe you could use numpy.loadtxt and pandas but I want to know how to achieve the same result without them.)
I would have a csv file like this, after openin... | How to convert csv file to dictionary so that top row is keys, and columns (in list form) are values (without numpy.loadtxt and panda)? | (To preface, I know/believe you could use numpy.loadtxt and pandas but I want to know how to achieve the same result without them.)
I would have a csv file like this, after opening it and assigning it to file while also using splitlines():
file =
'Top1','Top2','Top3','Top4','Top5'
'1','a','3','b','5'
'a','2','b','3','... | [
"You can do this with zip,\ntext = \"\"\"'Top1','Top2','Top3','Top4','Top5'\n'1','a','3','b','5'\n'a','2','b','3','c'\n'1','a','3','b','5'\"\"\" \nlines = text.split('\\n') # This equals to the file_pointer.readlines()\n\nkeys = keys = list(map(lambda x:x.replace(\"'\", '').lower(), lines[0].split(',')))\nvalues = ... | [
2,
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074139043_dictionary_list_python.txt |
Q:
Looping through a dictionary that has multiple None value
I have a dataframe that has a multivalued column. This column has a dictionary inside a list. It may be that in some line it comes as None or the dictionary inside the list. The idea is to go through this column and bring only what is not null, in this case... | Looping through a dictionary that has multiple None value | I have a dataframe that has a multivalued column. This column has a dictionary inside a list. It may be that in some line it comes as None or the dictionary inside the list. The idea is to go through this column and bring only what is not null, in this case what is in the 'optionText' key.
For this, I transformed this ... | [
"This will return a new dict b if for every key in the dict a there is a value associated with the key:\nb = {k: a.get(k) for k in a if a.get(k) is not None}\n\nModifying this for your example, you can add an additional lookup to check whether a certain element associated with this key fulfills a certain condition.... | [
1
] | [] | [] | [
"dictionary",
"nonetype",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074139532_dictionary_nonetype_pandas_python_python_3.x.txt |
Q:
How to find the amount of minutes between the current time and a future time of the same day in python
I'm trying to make a program that tells me how long there is (in minutes) until a certain time of day in the future. I've been trying to write working code all night, but I just can't wrap my head around strftime... | How to find the amount of minutes between the current time and a future time of the same day in python | I'm trying to make a program that tells me how long there is (in minutes) until a certain time of day in the future. I've been trying to write working code all night, but I just can't wrap my head around strftime, timedelta and datetime. I'm quite new to python, and being able to do this would be quite useful to my day... | [
"from datetime import datetime\n\ndef minutes_until(hour, minute):\n #get the current time\n now = datetime.now()\n #get the current hour\n current_hour = now.hour\n #get the current minute\n current_minute = now.minute\n #get the current second\n current_second = now.second\n #get the cu... | [
0
] | [
"You can try:\nfrom datetime import datetime\n\ntarget = '2023-01-01 00:00:00'\n\nt = datetime.strptime(target, '%Y-%m-%d %H:%M:%S')\nnow = datetime.now()\nprint(f'{(t-now).total_seconds()/60:.0f} minutes')\n\noutput: 104445 minutes\n"
] | [
-1
] | [
"datetime",
"python",
"strftime"
] | stackoverflow_0074139653_datetime_python_strftime.txt |
Q:
Removing Traceback Warning
my code is running fine but everytime iam running it i always get this error
Traceback (most recent call last):
File "pixiv2.py", line 20, in <module>
print(url["url"])
KeyError: 'url
here my code
import requests
import json
head = {"cookie":"first_visit_datetime_pc=2022-10-18+23... | Removing Traceback Warning | my code is running fine but everytime iam running it i always get this error
Traceback (most recent call last):
File "pixiv2.py", line 20, in <module>
print(url["url"])
KeyError: 'url
here my code
import requests
import json
head = {"cookie":"first_visit_datetime_pc=2022-10-18+23%3A14%3A39;p_ab_id=6; p_ab_id_2=... | [
"How to ignore exceptions in python: Python: How to ignore an exception and proceed?\nimplemented in your code, but I would also look at @matszwecja's answer to understand why this error is occurring.\nfor url in r[\"body\"][\"illusts\"]:\n try:\n print(url[\"url\"])\n except KeyError:\n pass \n... | [
0,
0
] | [] | [] | [
"json",
"python",
"python_requests",
"traceback",
"web_scraping"
] | stackoverflow_0074139535_json_python_python_requests_traceback_web_scraping.txt |
Q:
decode utf8 in javascript client websocket from python websocket server
I'm trying to send integers through websocket asyncio in python as server to JS websocket client. I have encoded with utf8 from python side. but I don't know how to decode the value from js side. Any suggestions will be really helpful.
it's s... | decode utf8 in javascript client websocket from python websocket server | I'm trying to send integers through websocket asyncio in python as server to JS websocket client. I have encoded with utf8 from python side. but I don't know how to decode the value from js side. Any suggestions will be really helpful.
it's showing like this in my webbrowser console:
Message from server Blobsize: 2ty... | [
"First things first, encoding normal string to utf-8 is unnecessary you just need to\nawait client.send(str(current_coordinates))\nNext thing is that if the message.data is a blob then you just need to convert it to a string\n socket.addEventListener('message',async function (event) {\n var data = event.data;\n... | [
0
] | [] | [] | [
"javascript",
"python",
"python_asyncio",
"websocket"
] | stackoverflow_0074139299_javascript_python_python_asyncio_websocket.txt |
Q:
Removing suffixes from list Python
I have 2 lists
where
name = ['Annie A3', 'apple.com', 'John PLG', 'Piggy Alpha CLa']
suffixes = ['A3','.Com','pLG','Cla']
I am trying to remove the suffixes from the name list.
What is the best approach in this scenario?
Do i convert both list string into upper/lower case let... | Removing suffixes from list Python | I have 2 lists
where
name = ['Annie A3', 'apple.com', 'John PLG', 'Piggy Alpha CLa']
suffixes = ['A3','.Com','pLG','Cla']
I am trying to remove the suffixes from the name list.
What is the best approach in this scenario?
Do i convert both list string into upper/lower case letter and iterate through a for loop to su... | [
"in my opinion, two loops.\nnames = ['Annie A3', 'apple.com', 'John PLG', 'Piggy Alpha CLa']\nsuffixes = ['A3','.Com','pLG','Cla']\nnew_names = []\nfor name in names:\n for suffix in suffixes:\n if name.lower().endswith(suffix.lower()):\n name = # Do what you want with the suffix\n new_names.append(name)\... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0060933735_python.txt |
Q:
Is it possible to call a variable within an argument from a class?
I'm trying to return the dictionary d that is within the argument bar from the class foo but the return I get is <function bar at 0x00000262763B2EE0>. Is this the best way to do this? I wrote an example code that I've written to represent what I'm... | Is it possible to call a variable within an argument from a class? | I'm trying to return the dictionary d that is within the argument bar from the class foo but the return I get is <function bar at 0x00000262763B2EE0>. Is this the best way to do this? I wrote an example code that I've written to represent what I'm working on which includes a much larger code. It seems to me like I may... | [
"Try:\ndef bar():\n d = {'a':1, 'b':2}\n return d\nclass foo:\n def __init__(self, _bar):\n self._bar = _bar\n def p_dict(self):\n print(self._bar())\n\ntest_1 = foo(bar)\n\ntest_1.p_dict()\n\n"
] | [
0
] | [] | [] | [
"class",
"object",
"printing",
"python"
] | stackoverflow_0074139620_class_object_printing_python.txt |
Q:
How to read the filenames from an input directory that starts with the prefixes in a list in python
I am using the current function to read file from a local directory when the filename starts with certain prefix.
Now I have second use case where multiple prefixes are in a list like['prefix1', 'prefix2'] . How can... | How to read the filenames from an input directory that starts with the prefixes in a list in python | I am using the current function to read file from a local directory when the filename starts with certain prefix.
Now I have second use case where multiple prefixes are in a list like['prefix1', 'prefix2'] . How can I modify the code below for finding multiple filenames from the local directory where filename start wit... | [
"The issue is about this line:\nif prefix in filename\nThe logic will be inversed like this:\nif (some part of the filename) in prefix , where prefix is a list like['prefix1', 'prefix2',..]\nYou can solve this using startswith method and a tuple of the prefixes list.\nFor example:\nprefix_list=['prefix1', 'prefix2... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074138958_python_python_3.x.txt |
Q:
How to log nested function names while logging
I am logging the function name in my application logs using %(funcName), but this only captures the function name which executes the code.
let's say that func_C is called form func_B and func_B is being called from func_A, then i would also like this information in lo... | How to log nested function names while logging | I am logging the function name in my application logs using %(funcName), but this only captures the function name which executes the code.
let's say that func_C is called form func_B and func_B is being called from func_A, then i would also like this information in log. How can i fetch this info in my log message?
| [
"What I would do is pass the outer function's name to the inner function with an argument and then you can log that in the inner function from the passed variable. So func name A gets passed to func B, then func name A and func name B get passed to func C where you log all three.\n",
"You can just use the stack_i... | [
0,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0074120880_logging_python.txt |
Q:
Timout while connecting to Azure VM via Python
I am trying to connect Azure VM which is created via Administrator Password (Not SSH) but have allowed SSH, HTTPS, and HTTP in Networking. But It's giving Timeout Error.
Tried to connect via paramiko library. Below is my code
import paramiko
results = []
def ssh_co... | Timout while connecting to Azure VM via Python | I am trying to connect Azure VM which is created via Administrator Password (Not SSH) but have allowed SSH, HTTPS, and HTTP in Networking. But It's giving Timeout Error.
Tried to connect via paramiko library. Below is my code
import paramiko
results = []
def ssh_conn():
try:
client = paramiko.SSHClient()... | [
"We have tested this in my local environment, we are able to execute and ssh into the VM using your shared python code using Visual studio code.\nWhile testing your code we found that there is an false attribute apend in the code so use append instead of that attribute.\nBecause of this, code execution got failed... | [
0
] | [] | [] | [
"azure",
"python",
"rdp",
"virtual_machine"
] | stackoverflow_0074137048_azure_python_rdp_virtual_machine.txt |
Q:
Django how can i find_all book by сategory = None
How can i take all books when i pass None, cuz in Ruby if i write something like that
Book.where(category = None) => Give all Books
I try this
Book.objects.filter(category = None) => empty QuerySet
In general, there is some method in django that covers this logic... | Django how can i find_all book by сategory = None | How can i take all books when i pass None, cuz in Ruby if i write something like that
Book.where(category = None) => Give all Books
I try this
Book.objects.filter(category = None) => empty QuerySet
In general, there is some method in django that covers this logic
| [
"For Books with None category:\nBook.objects.filter(category = None)\n\nAll the books:\nBook.objects.all()\n\nFor Books with NOT NONE category:\nBook.objects.all().exclude(category=None)\n\nThis is the way for Python/Django if you want to filter with whatever your requirement.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074138748_django_python.txt |
Q:
Easy way to fix wrong year (y2k bug) using pandas
I have a database with a column named ['birth_date'], already converted string -> date using:
dataCopy.loc[:,'birth_date'] = dataCopy['birth_date'].astype('datetime64[ns]')
I also converted other columns my db has.
So, as some of you know there is an issue with 2 d... | Easy way to fix wrong year (y2k bug) using pandas | I have a database with a column named ['birth_date'], already converted string -> date using:
dataCopy.loc[:,'birth_date'] = dataCopy['birth_date'].astype('datetime64[ns]')
I also converted other columns my db has.
So, as some of you know there is an issue with 2 digits year dates (mm/dd/yy or whatever) that when pytho... | [
"You need to create a custom function and map it to the birth_date column.\nYou can decide a cutoff year (say 40) above which will be classified to 19th century and below which will be classified to 20th century. For example, 62 will be converted to year 1962, 32 will be converted to 2032.\nThe below code create th... | [
1,
1
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python",
"y2k"
] | stackoverflow_0071168678_dataframe_jupyter_notebook_pandas_python_y2k.txt |
Q:
pandas: list comprehension for creating column in existing dataframe
I have one column, and another is datetime which is in index position I done some coding on this. I try to use for loop for below condition but need optimization or list comprehension.
date_today = datetime.now()
days = pd.date_range(date_today, ... | pandas: list comprehension for creating column in existing dataframe | I have one column, and another is datetime which is in index position I done some coding on this. I try to use for loop for below condition but need optimization or list comprehension.
date_today = datetime.now()
days = pd.date_range(date_today, date_today + timedelta(254), freq='D')
dd = pd.DataFrame()
cc = sorted(np.... | [
"IIUC, you can try\ncount1 = sum([(i >= 2) and (j >= 32) for i, j in rle])\n# or with pandas\ncount1 = len(pd.DataFrame(rle).loc[lambda df: df[0].ge(2) & df[1].ge(32), :])\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"itertools_groupby",
"pandas",
"python"
] | stackoverflow_0074138336_dataframe_itertools_groupby_pandas_python.txt |
Q:
Get tweets from topics section with Twitter API
I want to get tweets from a specific topic from the topics section. But I couldn't find this on the twitter api page or the tweepy website. how can I get this tweet with tweepy or twitter api? Below picture shows the topics I followed. I need to select one topic fro... | Get tweets from topics section with Twitter API | I want to get tweets from a specific topic from the topics section. But I couldn't find this on the twitter api page or the tweepy website. how can I get this tweet with tweepy or twitter api? Below picture shows the topics I followed. I need to select one topic from here and save these tweets for the project.
Twitter... | [
"In order to build something like this, you would use Tweet annotations, which are a part of Twitter API v2 (link to the official documentation). These annotations are used inside Twitter to power the Topics features, but they may not always be a direct mapping.\nNote that not all annotations are available via the ... | [
1
] | [] | [] | [
"python",
"tweepy",
"twitter",
"twitter_api_v1",
"twitterapi_python"
] | stackoverflow_0074131392_python_tweepy_twitter_twitter_api_v1_twitterapi_python.txt |
Q:
how can I open new tab in plotly dash?
I have the following code:
app.layout = html.Div([html.Button("Press", id = "newpage")])
@callback(Input("newpage", n_click))
def newPage(n: int):
#Do something, open a new page and show "Hello" in that new page.
Thanks
A:
I think I partially find the solution, throu... | how can I open new tab in plotly dash? | I have the following code:
app.layout = html.Div([html.Button("Press", id = "newpage")])
@callback(Input("newpage", n_click))
def newPage(n: int):
#Do something, open a new page and show "Hello" in that new page.
Thanks
| [
"I think I partially find the solution, through flask/DispatcherMiddleware.\nfrom dash import Dash\nfrom werkzeug.wsgi import DispatcherMiddleware\nimport flask\nfrom werkzeug.serving import run_simple\nimport dash_html_components as html\n\nserver = flask.Flask(name)\ndash_app1 = Dash(name, server = server, url_ba... | [
1
] | [] | [] | [
"plotly_dash",
"python"
] | stackoverflow_0074131281_plotly_dash_python.txt |
Q:
Flask api server not working across local network
I have a Flask api server running, worked absolutely fine on 127.0.0.1 right up until I started tinkering with trying to get it working across the LAN. I can see the connections from other devices on the LAN in the debug log, and it is receiving the connections fin... | Flask api server not working across local network | I have a Flask api server running, worked absolutely fine on 127.0.0.1 right up until I started tinkering with trying to get it working across the LAN. I can see the connections from other devices on the LAN in the debug log, and it is receiving the connections fine, but not serving any pages, only 404, but not even my... | [
"Fixed it after some more research/Googling while I waited for answers\nMoved the host declaration to underneath the if name call\nimport os\n\nif __name__ == '__main__':\n port = int(os.environ.get(\"PORT\", 5155))\n api.run(host='0.0.0.0', port=port)\n\n",
"The problem comes from run.api() at the start. ... | [
2,
1
] | [] | [] | [
"flask",
"python",
"windows"
] | stackoverflow_0074139696_flask_python_windows.txt |
Q:
When applying `Series.clip` to ordered categorical data, I get the wrong result
Let's say we have a series of ordered categorical data:
s = pd.Series(['zero','one','two','three','four','five','six'], dtype='category')
s = s.cat.reorder_categories(['zero','one','two','three','four','five','six'], ordered=True)
prin... | When applying `Series.clip` to ordered categorical data, I get the wrong result | Let's say we have a series of ordered categorical data:
s = pd.Series(['zero','one','two','three','four','five','six'], dtype='category')
s = s.cat.reorder_categories(['zero','one','two','three','four','five','six'], ordered=True)
print(s)
Here's an output of the code above:
0 zero
1 one
2 two
3 three... | [
"This looks like a bug. In the source there is a check that the upper/lower bounds are in the correct order. However I think this is mistakenly using the string values of the categories ('four' < 'two'):\n 8095 # GH 2747 (arguments were reversed)\n 8096 if (\n 8097 lower is not Non... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074139763_pandas_python.txt |
Q:
os.walk() is not printing anything when providing the current directory path as a string
The following code is not generating any output when I provide the current directory path as a string to os.walk() method but when I provide os.getcwd() as an argument to the os.walk() method, it prints the desired output.
imp... | os.walk() is not printing anything when providing the current directory path as a string | The following code is not generating any output when I provide the current directory path as a string to os.walk() method but when I provide os.getcwd() as an argument to the os.walk() method, it prints the desired output.
import os
dir='/Users/shiva/AppData/Local/Programs/Python/Python39'
for dirpath,dirnames,filename... | [] | [] | [
"Use Raw String for Path\nimport os\npath = r'C:\\Users\\USER_NAME\\AppData\\Local\\Programs\\Python\\Python310'\nfor dirpath, dirnames, filenames in os.walk(path):\n print(f'dirpath={dirpath}\\ndirnames={dirnames}\\nfilenames={filenames}')\n\n"
] | [
-2
] | [
"python",
"python_3.x"
] | stackoverflow_0074139523_python_python_3.x.txt |
Q:
Web Scraping with BeautifulSoup - how to set delay for Scraping when accessing site?
I am trying to scrape the entries from Immobilienscout24, which is a german real estate listing platform.
Whenever i want to scrape a site, it only scrapes "Ich bin kein Roboter" (in german "i am not a robot") as header. I found o... | Web Scraping with BeautifulSoup - how to set delay for Scraping when accessing site? | I am trying to scrape the entries from Immobilienscout24, which is a german real estate listing platform.
Whenever i want to scrape a site, it only scrapes "Ich bin kein Roboter" (in german "i am not a robot") as header. I found out that sometimes, when you enter the site, for half a second you get a screen that says s... | [
"This solution might not work for your problem, but solved for me.\nBefore using this you should download the appropriate driver for your browser, and uncomment only one time the lines bellow\nimport os\nfrom selenium import webdriver\n\nif os.environ['PATH'].find(';C:\\\\SeleniumDrivers') > 0:\n pass\nelse:\n ... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074139888_beautifulsoup_python_web_scraping.txt |
Q:
Python Selenium How to Run Continuously?
I want to my program start again when driver2.find_element("xpath", f'//*[text()="{entry1.get()}"]').click() gives error how can i do it pls help me
class a(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
bot()
... | Python Selenium How to Run Continuously? | I want to my program start again when driver2.find_element("xpath", f'//*[text()="{entry1.get()}"]').click() gives error how can i do it pls help me
class a(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
bot()
while True:
bot()
def... | [
"You can put the code block you want to repeat until it succeed inside try-except block inside while loop. As following:\nurl = 'https://www.google.com'\nagain = True\nwhile again:\n try:\n driver2.get(url)\n driver2.find_element(\"name\", \"q\")\n time.sleep(1)\n driver2.find_element... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"try_catch",
"while_loop"
] | stackoverflow_0074139877_python_selenium_selenium_chromedriver_try_catch_while_loop.txt |
Q:
Pandas group by with list applied to multiple columns
I have a table:
ID
Component
Revenue
1
4
10
1
5
20
2
4
15
3
6
30
and I'd like to group by ID, creating a column with a dictionary or list as such:
ID
Grouped
1
[[4, 10], [5,20]]
2
[4, 15]
3
[6, 30]
I know using
df.groupby(['ID']).Component.apply(list... | Pandas group by with list applied to multiple columns | I have a table:
ID
Component
Revenue
1
4
10
1
5
20
2
4
15
3
6
30
and I'd like to group by ID, creating a column with a dictionary or list as such:
ID
Grouped
1
[[4, 10], [5,20]]
2
[4, 15]
3
[6, 30]
I know using
df.groupby(['ID']).Component.apply(list).reset_index()
will do so for one ... | [
"You can use:\n(df.groupby(['ID'])[['Component', 'Revenue']]\n .apply(lambda d: d.to_numpy().tolist())\n .reset_index(name='Grouped')\n)\n\noutput:\n ID Grouped\n0 1 [[4, 10], [5, 20]]\n1 2 [[4, 15]]\n2 3 [[6, 30]]\n\n"
] | [
0
] | [] | [] | [
"data_science",
"group_by",
"pandas",
"python"
] | stackoverflow_0074140028_data_science_group_by_pandas_python.txt |
Q:
Moviepy concatenated videoclip exports way slower than clips themselves
I have a list of 4 moviepy ImageClips that I want to concatenate and then export. I notice that when I export the concatenated videoclip, it starts exporting at ~60 it/s but it quickly drops to ~6 after a couple seconds. I suspect that the dro... | Moviepy concatenated videoclip exports way slower than clips themselves | I have a list of 4 moviepy ImageClips that I want to concatenate and then export. I notice that when I export the concatenated videoclip, it starts exporting at ~60 it/s but it quickly drops to ~6 after a couple seconds. I suspect that the drop is when it reaches the third clip, which is significantly longer than the o... | [
"Okay, so I tested various things, and it indeed was the RAM holding me back, I think. I exported the clips separately and saw numbers like 250 it/s with the h264_nvenc codec. If you don't have a GPU(or your CPU is at least faster) I suggest you use that. Either way, make sure your RAM isn't being completely oblite... | [
0
] | [] | [] | [
"export",
"moviepy",
"python",
"video_editing"
] | stackoverflow_0074117365_export_moviepy_python_video_editing.txt |
Q:
How to implement last visited functionality for articles in django rest framework
I have this model of Article where users can post articles, add comments, etc. I want to add a filter where it can filter Articles according to user which has visited the last Article or commented on the last Article.
Please guide me... | How to implement last visited functionality for articles in django rest framework | I have this model of Article where users can post articles, add comments, etc. I want to add a filter where it can filter Articles according to user which has visited the last Article or commented on the last Article.
Please guide me on how can I achieve this functionality in Django/DRF.
This is my models:
class Articl... | [
"Please see my answer here from a previous question, which is almost identical.\nYou could create an extra table.\nclass ArticleSeenRecord(models.Model):\n user = models.ForeignKey(\"django.contrib.auth.models.User\", on_delete=models.CASCADE)\n article = models.ForeignKey(Article, on_delete=models.CASCADE)\n... | [
2
] | [] | [] | [
"django",
"django_filter",
"django_filters",
"django_rest_framework",
"python"
] | stackoverflow_0074140015_django_django_filter_django_filters_django_rest_framework_python.txt |
Q:
Traverse using numpy.where with 2 indices
I am having this kind of array: v = [1, 2, -1, 2, 3, -1, 3, -10, -10, -10].
My assignment is to create another array with the indices of the elements, where a change of sign has been made. For the example above, the new array should be v2 = [1, 2, 4, 5, 6]. I have been giv... | Traverse using numpy.where with 2 indices | I am having this kind of array: v = [1, 2, -1, 2, 3, -1, 3, -10, -10, -10].
My assignment is to create another array with the indices of the elements, where a change of sign has been made. For the example above, the new array should be v2 = [1, 2, 4, 5, 6]. I have been given the indication to use numpy.where, but I can... | [
"You can use:\nout = np.nonzero(np.diff(np.sign(v)))[0]\n\n# or with np.where\n# out = np.where(np.diff(np.sign(v))!=0)[0]\n\noutput: array([1, 2, 4, 5, 6])\nIntermediates:\nnp.sign(v)\n# array([ 1, 1, -1, 1, 1, -1, 1, -1, -1, -1])\n\nnp.diff(np.sign(v))\n# array([ 0, -2, 2, 0, -2, 2, -2, 0, 0])\n\nnp.nonz... | [
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074140086_arrays_numpy_python.txt |
Q:
Sendgrid resulting in an error 401 Unauthorized
My code runs scripts that sends email every 1 hour.
The script was running fine, until the Sendgrid resulted in error HTTP 401 Unauthorized.
I checked up online and found that this could be due to wrong API key or not properly importing the API in the python code. Bu... | Sendgrid resulting in an error 401 Unauthorized | My code runs scripts that sends email every 1 hour.
The script was running fine, until the Sendgrid resulted in error HTTP 401 Unauthorized.
I checked up online and found that this could be due to wrong API key or not properly importing the API in the python code. But my code ran fine, up till now.
sg = sendgrid.SendGr... | [
"I think that this isn't a SendGrid API problem. This may happen because you are not importing the SENDGRID_API_KEY properly.\nFor test only, try using a key hardcoded, p.e. SENDGRID_API_KEY=\"xpto123, instead of the method os.environ.get().\n"
] | [
0
] | [] | [] | [
"python",
"sendgrid"
] | stackoverflow_0073890873_python_sendgrid.txt |
Q:
Printing number of elements in a string but with some exception
so I wanted to count the number of elements in a string. However, there are some exceptions on how to solve this such as the use of len, count, max, min, string function, etc.
Say I have a string of 'hello' means that I wanted to make a program that g... | Printing number of elements in a string but with some exception | so I wanted to count the number of elements in a string. However, there are some exceptions on how to solve this such as the use of len, count, max, min, string function, etc.
Say I have a string of 'hello' means that I wanted to make a program that gives the output which states the number of elements of the 'hello' st... | [
"So you just want to loop over the characters in a string to determine the length of the string without using len()? One possible way to do that would be:\nstrg = \"hello\"\ncount = 0\nwhile True:\n try:\n strg[count]\n except IndexError:\n break\n else:\n count += 1\nprint(count)\n\n"... | [
1
] | [] | [] | [
"arrays",
"element",
"python",
"string"
] | stackoverflow_0074139985_arrays_element_python_string.txt |
Q:
Using Playwright with CSS that contains nth element
I'm trying to find an element with a specific nth index as a CSS expression.
How can I fix my code without changing the CSS expression?
try:
expect(self.page.locator('div[class="some-class"]:nth(3)')).\
to_be_visible(timeout=20000)
retu... | Using Playwright with CSS that contains nth element | I'm trying to find an element with a specific nth index as a CSS expression.
How can I fix my code without changing the CSS expression?
try:
expect(self.page.locator('div[class="some-class"]:nth(3)')).\
to_be_visible(timeout=20000)
return True
except AssertionError:
return False
The erro... | [
"Your locator should look like this. Replace \":\" with \">>\"\ndiv[class=\"some-class\"]>>nth=3\n\n",
"You can also do something like this:\nself.page.locator('div.some-class').nth(3)\n//or\nself.page.locator('div.some-class').nth(4)\n\n"
] | [
1,
1
] | [] | [] | [
"playwright",
"playwright_python",
"python"
] | stackoverflow_0074125356_playwright_playwright_python_python.txt |
Q:
Generate a set of random numbers where the absolute value of the difference between every two numbers is greater than a given threshold
I want to generate a set of random numbers in a given interval, where the absolute value of the difference between every two numbers is greater than a given threshold.
I have trie... | Generate a set of random numbers where the absolute value of the difference between every two numbers is greater than a given threshold | I want to generate a set of random numbers in a given interval, where the absolute value of the difference between every two numbers is greater than a given threshold.
I have tried random.sample(range(1, 5), 3), but I want to get a set of float numbers.
E.g. The given threshold is 1.0.
Thus, [1.2, -0.9, 2.5] is right a... | [
"This should work for your example:\nimport random\nimport numpy as np\n\nthreshold = 1\ninterval = [1, 5]\nnumbers_to_generate = 3\ngenerate_random_number = lambda interval=interval: interval[1] - np.random.random() * abs(interval[1] - interval[0])\nresults = [generate_random_number()]\n\nfor _ in range(numbers_to... | [
0
] | [] | [] | [
"list",
"numpy",
"python"
] | stackoverflow_0074139753_list_numpy_python.txt |
Q:
TimeDistributed(GlobalAveragePooling2D()) vs TimeDistributed(Flatten())
For the image classification task, I first built a CNN model that gave a higher accuracy when I used GlobalAveragePooling2D() than Flatten().
Now i want to add LSTM layers to my model, TimeDistributed(Flatten()) before the LSTM layers works fi... | TimeDistributed(GlobalAveragePooling2D()) vs TimeDistributed(Flatten()) | For the image classification task, I first built a CNN model that gave a higher accuracy when I used GlobalAveragePooling2D() than Flatten().
Now i want to add LSTM layers to my model, TimeDistributed(Flatten()) before the LSTM layers works fine but when i replace it with TimeDistributed(GlobalAveragePooling2D()) i go... | [
"GlobalAveragePooling2D() accepts 4D tensor with the shape (batch_size, rows, cols, channels) or with the shape (batch_size, channels, rows, cols) according to Keras document.\nHere, the input shape is (None, 7, 1280). So the input dimension (ndim) is 3.\nBut the expected shape is like input_shape = (2, 4, 5, 3) - ... | [
0
] | [] | [] | [
"conv_neural_network",
"flatten",
"keras",
"lstm",
"python"
] | stackoverflow_0071392108_conv_neural_network_flatten_keras_lstm_python.txt |
Q:
Command 'ping' is not found using cogs. discord.py
discord.ext.commands.bot: Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found.
How to fix it?
Main class:
import discord
from discord.ext import commands
from discord import Intents
import os
intents = Inten... | Command 'ping' is not found using cogs. discord.py | discord.ext.commands.bot: Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found.
How to fix it?
Main class:
import discord
from discord.ext import commands
from discord import Intents
import os
intents = Intents.all()
intents.members = True
bot = commands.Bot(comm... | [
"I think its because your class isn't inheriting commands.Cog\nChanging class MainCog: to class MainCog(commands.Cog): should fix that problem for you.\n",
"Firstly, as the other comment mentioned, your Cog class is not inheriting from commands.Cog.\nSecond, you're loading extensions the old way. Extension loadin... | [
0,
-1
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074137776_discord.py_python.txt |
Q:
Slack event appends to list within the decorator function but it doesn't append to list outside the decorator function
message_text = []
@slack_event_adapter.on("message")
def message(payload):
event = payload.get("event", {})
channel_id = event.get("channel")
user_id = event.get("user")
# each u... | Slack event appends to list within the decorator function but it doesn't append to list outside the decorator function | message_text = []
@slack_event_adapter.on("message")
def message(payload):
event = payload.get("event", {})
channel_id = event.get("channel")
user_id = event.get("user")
# each user has an ID, loop through every user's id, find their name in user_in_channel return their name.
if user_id:
... | [
"The \"second print\" in this code as is, is actually executed as soon as the program starts, and before it can receive any events.\nPython programs are resolved line by line - but upon finding a function (or class) definition, Python \"learns\"that function and whatever code is inside will just be executed when th... | [
0
] | [] | [] | [
"python",
"slack_api"
] | stackoverflow_0074139530_python_slack_api.txt |
Q:
How to add comments in XML using python
XML i am parsing:
<List>
<Item>
<Price>
<Amount>100</Amount>
<Next_Item>
<Name>Apple</Name>
</Next_Item>
<Next_Item>
<Name>Orange</Name>
</Next_Item>
</Price>
... | How to add comments in XML using python | XML i am parsing:
<List>
<Item>
<Price>
<Amount>100</Amount>
<Next_Item>
<Name>Apple</Name>
</Next_Item>
<Next_Item>
<Name>Orange</Name>
</Next_Item>
</Price>
<Price>
<Amount>200</Amount>... | [
"I think this is a good use case for an XSLT transformation and lxml supports XSLT 1.0:\n<xsl:stylesheet\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n version=\"1.0\">\n \n <xsl:output indent=\"yes\"/>\n\n <xsl:template match=\"@* | node()\" name=\"identity\">\n <xsl:copy>\n <xsl:apply-tem... | [
1,
1
] | [] | [] | [
"lxml",
"python",
"xml",
"xml_comments"
] | stackoverflow_0074135197_lxml_python_xml_xml_comments.txt |
Q:
sendgrid - set contact id while Add or Update
I'm trying to use Add or Update a contact endpoint (https://docs.sendgrid.com/api-reference/contacts/add-or-update-a-contact) and I can see list_ids that can be used to set IDs for the contact, but I can't uses it and I don't see it in curl, when I added it to the requ... | sendgrid - set contact id while Add or Update | I'm trying to use Add or Update a contact endpoint (https://docs.sendgrid.com/api-reference/contacts/add-or-update-a-contact) and I can see list_ids that can be used to set IDs for the contact, but I can't uses it and I don't see it in curl, when I added it to the request I got error 400 bad request, any idea about how... | [
"As said in the docs that you share, the user ID of the SendGrid Marketing Contacts is the user email.\n\nIf the contact already exists in the system, any entries submitted via\nthis endpoint will update the existing contact. The contact to update\nwill be determined only by the email field and any fields omitted f... | [
0
] | [] | [] | [
"python",
"sendgrid"
] | stackoverflow_0073010545_python_sendgrid.txt |
Q:
Unprotect an Excel file programmatically
We're getting an Excel file from a client that has open protection and Write Reserve protection turned on. I want to remove the protection so I can open the Excel file with the python xlrd module. I've installed the pywin32 package to access the Excel file through COM, an... | Unprotect an Excel file programmatically | We're getting an Excel file from a client that has open protection and Write Reserve protection turned on. I want to remove the protection so I can open the Excel file with the python xlrd module. I've installed the pywin32 package to access the Excel file through COM, and I can open it with my program supplying the ... | [
"This function works for me\ndef Remove_password_xlsx(filename, pw_str):\n xcl = win32com.client.Dispatch(\"Excel.Application\")\n wb = xcl.Workbooks.Open(filename, False, False, None, pw_str)\n xcl.DisplayAlerts = False\n wb.SaveAs(filename, None, '', '')\n xcl.Quit()\n\n",
"This post helped me a ... | [
17,
6,
5,
2,
1,
0
] | [] | [] | [
"com",
"excel",
"python",
"pywin32"
] | stackoverflow_0027556751_com_excel_python_pywin32.txt |
Q:
Anaconda prompt fail to launch: UnicodeEncodeError: 'utf-8' codec can't encode character '\udd8e': surrogates not allowed
I have Windows 10 x64 en-US and Anaconda3 2021.05. My anaconda prompt was working. Today it failed to launch and shows an error:
# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<
... | Anaconda prompt fail to launch: UnicodeEncodeError: 'utf-8' codec can't encode character '\udd8e': surrogates not allowed | I have Windows 10 x64 en-US and Anaconda3 2021.05. My anaconda prompt was working. Today it failed to launch and shows an error:
# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\conda\cli\main.py", line 140, in ma... | [
"The issue is a non-unicode letter in you PATH environment, which has to be deleted.\nGo to your PATH environment file (control panel > system > advanced settings > environment variables) and delete paths under your local user account with non-unicode letters in it.\n",
"I had a similar error where setting the PY... | [
1,
0
] | [] | [] | [
"anaconda",
"powershell",
"python",
"unicode",
"utf_8"
] | stackoverflow_0069130762_anaconda_powershell_python_unicode_utf_8.txt |
Q:
Request info from each product by using requests
Whenever I try to get a request from each product url (product_info)
And I try to show the status code of my request it shows 414 which means there are too many requests.
I have tried to split the product info variable by the split function but it doesn't display in... | Request info from each product by using requests | Whenever I try to get a request from each product url (product_info)
And I try to show the status code of my request it shows 414 which means there are too many requests.
I have tried to split the product info variable by the split function but it doesn't display information as it supposed to.
import requests as r
from... | [
"You were not getting the urls right. There are 2 url addresses per product one is within loc tag and another within image:loc tag. If you get them right you can get what you need. Here is the code that gets both urls and tests for response. I exit the loop after 4 passes:\nimport requests as r\nfrom bs4 import Be... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"python_requests",
"web_scraping",
"xml_parsing"
] | stackoverflow_0074127269_beautifulsoup_python_python_requests_web_scraping_xml_parsing.txt |
Q:
Find complex roots for every e^(i phi) with 0 <= phi < 4pi
I want to find the complex roots for z1 = -0.9 and z2 = 0.3 but for every phi between 0 and 4pi.
phi = np.linspace(0, 4*np.pi, 400, endpoint=False)
e = np.exp(1j*phi)
z1 = [-0.9, -0.25, -0.99, -0.9405, -0.76, -1.019898, -1.00]
z2 = [0.3, 0.25, 0.11, 0.049... | Find complex roots for every e^(i phi) with 0 <= phi < 4pi | I want to find the complex roots for z1 = -0.9 and z2 = 0.3 but for every phi between 0 and 4pi.
phi = np.linspace(0, 4*np.pi, 400, endpoint=False)
e = np.exp(1j*phi)
z1 = [-0.9, -0.25, -0.99, -0.9405, -0.76, -1.019898, -1.00]
z2 = [0.3, 0.25, 0.11, 0.0495, 0.04, 0.000102, 1.00]
#Coefficients
P = [e, -e*(2*z1[0] + ... | [
"import numpy as np\n\nphi = np.linspace(0, 4*np.pi, 400, endpoint=False)\n\ne = np.exp(1j*phi)\nz1 = [-0.9, -0.25, -0.99, -0.9405, -0.76, -1.019898, -1.00]\nz2 = [0.3, 0.25, 0.11, 0.0495, 0.04, 0.000102, 1.00]\n\n#Coefficients \n\nP = [e,\n -e*(2*z1[0] + 2*z2[0]),\n e*(z1[0]**2 + z2[0]**2 + 4*z1[0]*z2[0] -... | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074132645_numpy_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.