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: pyinstaller add-binary prepends arg with current directory Win 10, Pyinstaller 3.6, python 3.9.7 (conda) With the command line C:\Users\David\Code\Python\Unitization>pyinstaller --add-binary 'C:\ProgramData\Anaconda3\Library\bin\mkl_intel_thread.1.dll;.' unitTracker.py I get this error Unable to find "C:\Users\Da...
pyinstaller add-binary prepends arg with current directory
Win 10, Pyinstaller 3.6, python 3.9.7 (conda) With the command line C:\Users\David\Code\Python\Unitization>pyinstaller --add-binary 'C:\ProgramData\Anaconda3\Library\bin\mkl_intel_thread.1.dll;.' unitTracker.py I get this error Unable to find "C:\Users\David\Code\Python\Unitization\'C:\ProgramData\Anaconda3\Library\bi...
[ "In spite of the fact that the manual shows single quotes, that's the one thing that doesn't work. No quotes, as suggested by @Alexander above works. Double quotes also work.\n" ]
[ 0 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0074296230_pyinstaller_python.txt
Q: Matplotlib, there are two seperate sets of numbers on each axes I am plotting 2 data series (obtained from a csv via pandas) using matplotlib, however I have noticed that the resulting plot has the expected numbering on the axes however overlayed onto both axes is additional numbering (from 0 to 1.0) which appears...
Matplotlib, there are two seperate sets of numbers on each axes
I am plotting 2 data series (obtained from a csv via pandas) using matplotlib, however I have noticed that the resulting plot has the expected numbering on the axes however overlayed onto both axes is additional numbering (from 0 to 1.0) which appears to come from nowhere (see attached image). My pandas DataFrame does ...
[ "Thanks to @StonedTensor I figured out the issue, i was generating two axes by calling plt.subplot() and then also calling figure.add_subplot in the create_plot() function.\nTherefore to fix this issue I just changed the call to plt.subplot to plt.figure() which does not generate an axis, and I defer creation of an...
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "python", "windows_subsystem_for_linux" ]
stackoverflow_0074305625_matplotlib_pandas_python_windows_subsystem_for_linux.txt
Q: Printed Date Programming Assigment The task wants you to have the user enter a month, day and two-digit number for a year in sperate prompts and if the month times the day equals the year to print "this date is magic" but I'm getting an unknown error What to be expected is: Sample Run (user input shown in bold) En...
Printed Date Programming Assigment
The task wants you to have the user enter a month, day and two-digit number for a year in sperate prompts and if the month times the day equals the year to print "this date is magic" but I'm getting an unknown error What to be expected is: Sample Run (user input shown in bold) Enter month (numeric):12↵ Enter day:8↵ Ent...
[ "You need to cast your inputs into ints.\nAlso you need to use the comparison operator == instead of the assignation operator = inside your if.\nprint('Enter a month:')\nmonth = int(input('Select a month from the year'))\nprint('Enter day:')\nday = int(input('Select a day:'))\nprint('Enter a two digit year:')\nyear...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074305797_python.txt
Q: Pandas Read CSV Error When Reading Multiple Files I have multiple csv files, named as 2C-BEB-29-2009-01-18.csv,2C-BEB-29-2010-02-18.csv,2C-BEB-29-2010-03-28.csv, 2C-ISI-12-2010-01-01.csv, and so on. 2C- Part is default in all csv files. BEB means name of the recording device 29 stands for the user ID 2009-01-1...
Pandas Read CSV Error When Reading Multiple Files
I have multiple csv files, named as 2C-BEB-29-2009-01-18.csv,2C-BEB-29-2010-02-18.csv,2C-BEB-29-2010-03-28.csv, 2C-ISI-12-2010-01-01.csv, and so on. 2C- Part is default in all csv files. BEB means name of the recording device 29 stands for the user ID 2009-01-18 stands for the date of the recording. I have around...
[ "Firstly,\nimport chardet\n\nThen, replace your code snippet of\na = pd.read_csv(f,sep='\\s+|;|,', engine='python')\n\nwith this one\nwith open(f, 'rb') as file: \n encodings = chardet.detect(file.read())[\"encoding\"] \n a = pd.read_csv(f,sep='\\s+|;|,', engine='python', encoding=encodings)\n\n" ]
[ 2 ]
[]
[]
[ "csv", "glob", "pandas", "python" ]
stackoverflow_0073647074_csv_glob_pandas_python.txt
Q: pyenv install: 3.x BUILD FAILED (Ubuntu 20.04 using python-build 20180424) Trying to install a new Python - version with pyenv on Ubuntu 20.04 WSL for Windows 10 fails with the following output: username@hd1pcms0347:~$ pyenv install 3.9.4 Downloading Python-3.9.4.tar.xz... -> https://www.python.org/ftp/python/3.9....
pyenv install: 3.x BUILD FAILED (Ubuntu 20.04 using python-build 20180424)
Trying to install a new Python - version with pyenv on Ubuntu 20.04 WSL for Windows 10 fails with the following output: username@hd1pcms0347:~$ pyenv install 3.9.4 Downloading Python-3.9.4.tar.xz... -> https://www.python.org/ftp/python/3.9.4/Python-3.9.4.tar.xz Installing Python-3.9.4... python-build: use readline from...
[ "These are the relevant parts of your log:\n[...]\nIn file included from /tmp/python-build.20210602162502.2268/Python-3.9.4/Modules/_cursesmodule.c:113:\n./Include/py_curses.h:36:10: fatal error: curses.h: No such file or directory\n 36 | #include <curses.h>\n | ^~~~~~~~~~\ncompilation terminated.\n...
[ 27, 0 ]
[]
[]
[ "homebrew", "pyenv", "python", "ubuntu", "windows_subsystem_for_linux" ]
stackoverflow_0067807596_homebrew_pyenv_python_ubuntu_windows_subsystem_for_linux.txt
Q: How to read from Registers with pymodbus how can I read from Register with pymodbus? I'm trying this piece of code: import pymodbus from pymodbus.pdu import ModbusRequest from pymodbus.client.sync import ModbusSerialClient as ModbusClient #initialize a serial RTU client instance from pymodbus.transaction import ...
How to read from Registers with pymodbus
how can I read from Register with pymodbus? I'm trying this piece of code: import pymodbus from pymodbus.pdu import ModbusRequest from pymodbus.client.sync import ModbusSerialClient as ModbusClient #initialize a serial RTU client instance from pymodbus.transaction import ModbusRtuFramer #count= the number of registe...
[ "from pymodbus.client.sync import ModbusSerialClient as ModbusClient\n\nclient = ModbusClient(method='rtu', port='COM4', baudrate=2400, timeout=1)\n\nclient.connect()\nread=client.read_holding_registers(address = 222 ,count =10,unit=1) \n//Address is register address e.g 30222, \n//and count is number of registers ...
[ 4, 1, 0 ]
[]
[]
[ "modbus", "python" ]
stackoverflow_0051056141_modbus_python.txt
Q: python convert list of lists into dictionary I have a structure that consists of a list of lists. I would like to convert it to a dictionary where the array of size one are the keys and the subsequent items in the array where array are size 2 are the key - value of the key. Every item in the array of size 1 will b...
python convert list of lists into dictionary
I have a structure that consists of a list of lists. I would like to convert it to a dictionary where the array of size one are the keys and the subsequent items in the array where array are size 2 are the key - value of the key. Every item in the array of size 1 will be a new key. For example: list of lists: [ [ ...
[ "So the first thing you want is a nice way to turn this list into a list of pairs.\nThere's a canonical solution, given in this answer\n(That's a little obscure and hard to read if you're not used to that notation - I'm not going to go into it here, but it's worth digging into why it works!)\nSo you can define a f...
[ 1, 1 ]
[]
[]
[ "data_structures", "dictionary", "json", "list", "python" ]
stackoverflow_0074305437_data_structures_dictionary_json_list_python.txt
Q: Pandas dataframe : working with Latitude and longitude features I have total 32 variables in dataframe, X1 to X16 - Latitude values and Y1 to Y16 - Longitude values for 16 different positions. I want to perform following steps on these values using python, calculate distance between each position (X1,Y1) with e...
Pandas dataframe : working with Latitude and longitude features
I have total 32 variables in dataframe, X1 to X16 - Latitude values and Y1 to Y16 - Longitude values for 16 different positions. I want to perform following steps on these values using python, calculate distance between each position (X1,Y1) with every other position. Do it for all the positions and then average the...
[ "The below should help you to find the distance between two coordinates:\n# Python 3 program to calculate Distance Between Two Points on Earth\nfrom math import radians, cos, sin, asin, sqrt\ndef distance(lat1, lat2, lon1, lon2):\n \n # The math module contains a function named\n # radians which converts ...
[ 0 ]
[]
[]
[ "dataframe", "geospatial", "latitude_longitude", "pandas", "python" ]
stackoverflow_0074305818_dataframe_geospatial_latitude_longitude_pandas_python.txt
Q: Data Compression list of dictionaries that all have the same keys My task is: Assume you have a list of dictionaries that all have the same keys. For example: ** [ {"a": 1, "b": 2, "c": 3}, {"a": 9, "c": 7, "b": 8}, # dictionary keys don't have any order ... ]** Write a function compress that takes...
Data Compression list of dictionaries that all have the same keys
My task is: Assume you have a list of dictionaries that all have the same keys. For example: ** [ {"a": 1, "b": 2, "c": 3}, {"a": 9, "c": 7, "b": 8}, # dictionary keys don't have any order ... ]** Write a function compress that takes such a list of dictionaries as a parameter data. The function should p...
[ "This is clearly a homework question, so it's likely better for you to think about how to solve the problem than someone on stack overflow giving you a direct answer. However, a few hints that may help you:\n\nYour compress function is far too complex, you don't need to use len and range to solve this problem effic...
[ 0 ]
[]
[]
[ "dictionary", "key", "list", "python", "tuples" ]
stackoverflow_0074305557_dictionary_key_list_python_tuples.txt
Q: How to select rows values starting by specific letters by group in a python dataframe? I have the following dataframe "data" composed of ID and associated cluster number : ID cluster FP_101 1 FP_102 1 SP_209 3 SP_300 3 SP_209 1 FP_45 90 SP_50 90 FP_398 100 ... I would like to print ...
How to select rows values starting by specific letters by group in a python dataframe?
I have the following dataframe "data" composed of ID and associated cluster number : ID cluster FP_101 1 FP_102 1 SP_209 3 SP_300 3 SP_209 1 FP_45 90 SP_50 90 FP_398 100 ... I would like to print clusters which contain more than one ID starting by SP and/or FP. I think that I have the tw...
[ "This is my understanding of your question; let me know if it helps:\n\nSeparating SP & FP\n\n\ndf['Prefix'] = df['ID'].apply(lambda x: x.split('_')[0])\n\n\nGrouping by clusters\n\n\ndf2 = df.groupby(['cluster', 'Prefix'], as_index = False).agg({'ID':['nunique','unique']})\n\n\nFiltering\n\n\ndf2.columns = df2.col...
[ 1 ]
[]
[]
[ "dataframe", "filter", "python" ]
stackoverflow_0074304842_dataframe_filter_python.txt
Q: How do I enter the msys2 /usr/bin directory in Python on Windows? I am trying to write a file in the/usr/bin path so that my program can be ran from anywhere. This is the code os.chdir("/usr/bin") writetofile("slang", "cd " + pdir + " && python3 slang.py $1 $2 $3") And pdir is set with os.getcwd() However, it giv...
How do I enter the msys2 /usr/bin directory in Python on Windows?
I am trying to write a file in the/usr/bin path so that my program can be ran from anywhere. This is the code os.chdir("/usr/bin") writetofile("slang", "cd " + pdir + " && python3 slang.py $1 $2 $3") And pdir is set with os.getcwd() However, it gives me an error. FileNotFoundError: [WinError 3] The system cannot find ...
[ "The only solution I've found is creating a separate shell script file (with the code to write into /usr/bin), and then running that script in a subprocess.\n" ]
[ 0 ]
[]
[]
[ "msys2", "python" ]
stackoverflow_0074296339_msys2_python.txt
Q: How to get select field text from html form in django? I have created a form with select field in template ehrinfo.html <form action="{% url 'ehrs:compcreate' %}" method="GET"> <select> <option value="Vital Signs">Vital Signs</option> <option value="Cancer Signs">Cancer Signs</option> </sel...
How to get select field text from html form in django?
I have created a form with select field in template ehrinfo.html <form action="{% url 'ehrs:compcreate' %}" method="GET"> <select> <option value="Vital Signs">Vital Signs</option> <option value="Cancer Signs">Cancer Signs</option> </select><br><br> <input type="submit" value="Select Template...
[ "The proper way to render your form would be to pass it in to your template via the context object and change your template. For example:\n<form action=\"{% url 'ehrs:compcreate' %}\" method=\"GET\">\n {{ form.as_p }}<br><br>\n <input type=\"submit\" value=\"Select Template\" class=\"addehr\">\n</form>\n\nIf ...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0049958939_django_python.txt
Q: How can i troubleshoot my code? It works fine for a few minutes and then crashes i keep getting this after the code runs for a minute or so... Traceback (most recent call last): File "rapid7_helper.py", line 233, in _request() File "rapid7_helper.py", line 31, in _request resp = requests.post(url=url1, heade...
How can i troubleshoot my code? It works fine for a few minutes and then crashes
i keep getting this after the code runs for a minute or so... Traceback (most recent call last): File "rapid7_helper.py", line 233, in _request() File "rapid7_helper.py", line 31, in _request resp = requests.post(url=url1, headers=headers, json=third_party_patching_filer, verify=False).json() File "/usr/local/l...
[ "That error means that your code expected JSON data but got something else. I would suggest adding print(resp.text) and print(resp2.text) underneath both of your requests so that you can see exactly what data you are getting back.\n", "In my experience, a JSON decode error means a status code !== 2xx. Check this ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074305921_python.txt
Q: Setting up Stable Diffusion in Google colab Trying to setup Stable Diffusion on a notebook in Google Colab. I keep getting errors when running it: make sure you're logged in with huggingface-cli login pipe = StableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4', revision='fp16', ...
Setting up Stable Diffusion in Google colab
Trying to setup Stable Diffusion on a notebook in Google Colab. I keep getting errors when running it: make sure you're logged in with huggingface-cli login pipe = StableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4', revision='fp16', torch_dtype=torch.float16, use_auth_token=True) ...
[ "Here is the solution. https://huggingface.co/spaces/stabilityai/stable-diffusion/discussions/12\nIt says you probably did not visit https://huggingface.co/CompVis/stable-diffusion-v1-4, read, accepted and acknowledged the LICENSE. If you do so, it should work!\n" ]
[ 0 ]
[]
[]
[ "artificial_intelligence", "google_colaboratory", "python" ]
stackoverflow_0073983863_artificial_intelligence_google_colaboratory_python.txt
Q: Why is selenium webdriver in python not returning all image links? I am using selenium WebDriver to collect the URL's to images from a website that is loaded with JavaScript. It appears as though my following code returns only 160 out of the about 240 links. Why might this be - because of the JavaScript rendering?...
Why is selenium webdriver in python not returning all image links?
I am using selenium WebDriver to collect the URL's to images from a website that is loaded with JavaScript. It appears as though my following code returns only 160 out of the about 240 links. Why might this be - because of the JavaScript rendering? Is there a way to adjust my code to get around this? driver = webdriver...
[ "You need to wait for all those elements to be loaded.\nThe recommended approach is to use WebDriverWait expected_conditions explicit waits.\nThis code is giving me 760-880 elements in the img_url2 list:\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom sele...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074305657_python_selenium_selenium_chromedriver_selenium_webdriver_webdriverwait.txt
Q: "Desired structure doesn't exist" for PDB retrieve_pdb_file method Trying to download some protein data from PDB using Biopython's Bio.PDB.PDBList Here is a min. reproducible example: from Bio.PDB import PDBList pdbl=PDBList() pdbl.retrieve_pdb_file('1GAV', file_format="pdb") This returns: Downloading PDB structu...
"Desired structure doesn't exist" for PDB retrieve_pdb_file method
Trying to download some protein data from PDB using Biopython's Bio.PDB.PDBList Here is a min. reproducible example: from Bio.PDB import PDBList pdbl=PDBList() pdbl.retrieve_pdb_file('1GAV', file_format="pdb") This returns: Downloading PDB structure '1GAV'... Desired structure doesn't exists Desired behavior is downl...
[ "We think the problem has to do with our corporate VPN because it works when the VPN is off (although proxy still on).\nSo as sammam said, no problems in the code.\nDon't know the specifics of why this occurs with our VPN, will update if I find out.\n", "I'm getting the same error message, which I looked at the s...
[ 0, 0 ]
[]
[]
[ "bioinformatics", "biopython", "python" ]
stackoverflow_0062819121_bioinformatics_biopython_python.txt
Q: How do I split a single column dataframe into multiple columns by index I've browsed a few answers but haven't found the exact thing i'm looking for yet. I have a pandas dataframe with a single column structured as follows (example) 0 alex 1 7 2 female 3 nora 4 3 5 female ... 999 fred 1000 15 1001 male i wan...
How do I split a single column dataframe into multiple columns by index
I've browsed a few answers but haven't found the exact thing i'm looking for yet. I have a pandas dataframe with a single column structured as follows (example) 0 alex 1 7 2 female 3 nora 4 3 5 female ... 999 fred 1000 15 1001 male i want to split that single column into 3 columns holding name, age, and gender. t...
[ "Not the most efficient solution perhaps, but you can use pd.concat() and put them all next to each other, if they're always in order:\ndf = pd.DataFrame({'Value':['alex',7,'female','nora',3,'female','fred',15,'male']})\ndf2 = pd.concat([df[(df.index + x) % 3 == 0].reset_index(drop=True) for x in range(3)],axis=1)\...
[ 3, 2, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074305718_dataframe_pandas_python.txt
Q: Distributed Processing - AWS Sagemaker I have a few raw .csv files in my S3 bucket. How can I process them in parallel to reduce run time? See comments on where I require a little help. I am using SKLearnProcessor and s3_data_distribution_type='ShardedByS3Key' %%writefile preprocessing/preprocessing_sklearn.py ...
Distributed Processing - AWS Sagemaker
I have a few raw .csv files in my S3 bucket. How can I process them in parallel to reduce run time? See comments on where I require a little help. I am using SKLearnProcessor and s3_data_distribution_type='ShardedByS3Key' %%writefile preprocessing/preprocessing_sklearn.py import pandas as pd import argparse from ...
[ "AWS documentation is not clear how they manage the horizontal scaling and aggregate the outputs from multiple instances into S3. I believe we can only assume the SageMaker looks after the parallel processing automatically with the s3_data_distribution_type='ShardedByS3Key', splits the input data into shards, assig...
[ 1, 0 ]
[]
[]
[ "amazon_s3", "amazon_sagemaker", "amazon_web_services", "python" ]
stackoverflow_0068624368_amazon_s3_amazon_sagemaker_amazon_web_services_python.txt
Q: How i can login in Gmail with Python? The idea of ​​my code is to send a message to the mail ( x ) from the mail that I go to using the Login in the code. 17 line causes an error. #main.py import config as cfg import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart msg =...
How i can login in Gmail with Python?
The idea of ​​my code is to send a message to the mail ( x ) from the mail that I go to using the Login in the code. 17 line causes an error. #main.py import config as cfg import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart msg = MIMEMultipart() to_email = 'dasdladalffhal...
[ "You will have to enable less secure apps in GMail for this to work. https://myaccount.google.com/lesssecureapps\nSometimes you may also have to complete a captcha while logged into GMail - https://accounts.google.com/DisplayUnlockCaptcha\nMore info: https://support.google.com/accounts/answer/6010255?hl=en\n" ]
[ 0 ]
[]
[]
[ "authentication", "python" ]
stackoverflow_0074305713_authentication_python.txt
Q: Is there a way to view my data frame in pandas without reading in the file every time? Here is my code: import pandas as pd df = pd.read_parquet("file.parqet", engine='pyarrow') df_set_index = df.set_index('column1') row_count = df.shape[0] column_count = df.shape[1] print(df_set_index) print(row_count) pri...
Is there a way to view my data frame in pandas without reading in the file every time?
Here is my code: import pandas as pd df = pd.read_parquet("file.parqet", engine='pyarrow') df_set_index = df.set_index('column1') row_count = df.shape[0] column_count = df.shape[1] print(df_set_index) print(row_count) print(column_count) Can I run this without reading in the parquet file each time I want to do...
[ "pd.read_parquet reads files that are stored on the disc and stores it in cache which is naturally slow with a lot of data. So, you could engineer a solution like:\n1.) column_count\n pd.read_parquet(\"file.parqet\", engine='pyarrow', nrows=1).shape[1] \n\n-> This would give you the number of columns while only re...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "parquet", "python" ]
stackoverflow_0074305898_dataframe_pandas_parquet_python.txt
Q: Insert content as the first line a big file in python I am reading a big file(10M - 30M records) line by line, performs some data manipulation to each line and writes to another file. I have a scenario where first line manipulation depends on some of the data on other lines and hence I can write the first line to ...
Insert content as the first line a big file in python
I am reading a big file(10M - 30M records) line by line, performs some data manipulation to each line and writes to another file. I have a scenario where first line manipulation depends on some of the data on other lines and hence I can write the first line to the output file only after traversing through all other lin...
[ "If you are on ubuntu then you can use sed command in a subprocess as that is much faster.\nsubprocess.run(f\"sed -i 's/Header/{transformed_header_line}/g' {temp_file_name}\", shell=True)\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074299144_python_python_3.x.txt
Q: Hacker Rank Sparse Arrays There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example:- strings = ['ab',' ab','abc'] queries = ['ab', ' abc','bc'] There are 2 instances of '...
Hacker Rank Sparse Arrays
There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example:- strings = ['ab',' ab','abc'] queries = ['ab', ' abc','bc'] There are 2 instances of 'ab', 1 of 'abc',0 of 'bc'. For ...
[ "Try this:\nfrom collections import Counter\n\n\ndef matchingStrings(strings, queries):\n count = Counter(strings)\n return [count[query] for query in queries]\n\nExample:\n>>> matchingStrings(['ab', 'ab', 'abc'], ['ab', 'abc', 'bc'])\n[2, 1, 0]\n\nIf you can't use collections.Counter you can implement your v...
[ 0 ]
[]
[]
[ "python", "sparse_matrix" ]
stackoverflow_0074306034_python_sparse_matrix.txt
Q: How do I get the text value of a selected option in django views.py For example: if first option Regular is selected then how can i get the value "1" and its text value "Regular" in views.py <form method = "post" action = "{% url 'index' %}"> {% csrf_token %} <select name = "drop1" > <option value="1">Regular<...
How do I get the text value of a selected option in django views.py
For example: if first option Regular is selected then how can i get the value "1" and its text value "Regular" in views.py <form method = "post" action = "{% url 'index' %}"> {% csrf_token %} <select name = "drop1" > <option value="1">Regular</option> <option value="2">Medium</option> <option value="3">Larg...
[ "The value 1 should be in request.POST under the key drop1.\nThis should help you see the selected value in your view:\nprint(request.POST['drop1'])\n\nThe text content of the <option> tag is not submitted to your view, only the text inside the value attribute. This is a HTML and web browser design; Python or Djang...
[ 9, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0055268259_django_python.txt
Q: Python regex stop matching after string I am currently trying to match the following cases, which works most of the time, but I'll explain the exception in a second: someword.something.lis something.lis However, matches are also made for the case: something.lis.some.bad.values.here.after.the.string My current r...
Python regex stop matching after string
I am currently trying to match the following cases, which works most of the time, but I'll explain the exception in a second: someword.something.lis something.lis However, matches are also made for the case: something.lis.some.bad.values.here.after.the.string My current regex is: f".+{user_input_string}|{user_input_...
[ "I think you want a positive lookahead assuming you don't wish to capture the stop symbol:\nf\".+{user_input_string}(?=!)|{user_input_string}(?=!)\"\n\nTangentially, .+ makes no sense. You could simplify it to:\nf\".*{user_input_string}(?=!)\"\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "regex" ]
stackoverflow_0074305398_python_python_3.x_regex.txt
Q: how to skip the NEXT for iteration? When trying to scrape a website that has promotional price and regular price both of these elements are found by selenium webdriver. i want to: if the promotional price is found, skip the next iteration, which would be the regular price. "price price-final" being the promotional...
how to skip the NEXT for iteration?
When trying to scrape a website that has promotional price and regular price both of these elements are found by selenium webdriver. i want to: if the promotional price is found, skip the next iteration, which would be the regular price. "price price-final" being the promotional price and "price price-from" being the r...
[ "I'd use an inner for loop here:\nremedios= driver.find_elements(By.CLASS_NAME, \"price-number\")\n\nfor element in remedios:\n for name in ('price price-final', 'price price-from'):\n try:\n driver.find_elements(By.CLASS_NAME, name)\n except:\n # element not found\n ...
[ 0 ]
[]
[]
[ "for_loop", "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074306010_for_loop_python_selenium_selenium_webdriver_web_scraping.txt
Q: Python multiprocessing module freeze_support() line can be omitted error Windows I'm trying to experiment with multiprocessing in python. I have initially written this test code on a Ubuntu system and it exectued fine. When I try to run the same thing in windows, I get the following error: Traceback (most recent c...
Python multiprocessing module freeze_support() line can be omitted error Windows
I'm trying to experiment with multiprocessing in python. I have initially written this test code on a Ubuntu system and it exectued fine. When I try to run the same thing in windows, I get the following error: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Peri\AppData\Local\...
[ "You most likely want to call one of the processes and then the other and don't do the\np1.join() p2.join() because that will just make the main program halt until the subprocesses finish.\nThis will work:\nfrom multiprocessing import Process\n\n\ndef process1(text):\n return print(text)\n\ndef process2(text):\n...
[ 0, 0, 0 ]
[]
[]
[ "multiprocessing", "python", "python_3.x", "python_multiprocessing", "windows" ]
stackoverflow_0061452513_multiprocessing_python_python_3.x_python_multiprocessing_windows.txt
Q: How to populate conandata.yml? Is there any way to write anything to conandata.yml file? I want calculate execution time of code and populate my conandata.yml with it. A: There is the update_conandata() that you can use in your export() method: import os from conan import ConanFile from conan.tools.files import ...
How to populate conandata.yml?
Is there any way to write anything to conandata.yml file? I want calculate execution time of code and populate my conandata.yml with it.
[ "There is the update_conandata() that you can use in your export() method:\nimport os\nfrom conan import ConanFile\nfrom conan.tools.files import update_conandata\n\n\nclass Pkg(ConanFile):\n name = \"pkg\"\n version = \"0.1\"\n\n def export(self):\n update_conandata(self, {\"mydata\": {...}})\n\nHo...
[ 1, 0 ]
[]
[]
[ "conan", "python", "yaml" ]
stackoverflow_0074305047_conan_python_yaml.txt
Q: How Do I Add a '_' In The Middle of All Data in the Column of a DataFrame eg . I have data like 2008Q1 , 2008Q2 , 2009Q1 in a single column. I want to give output as 2008_Q1 ,2008_Q2 df['quarter'] = df[:4] + '_' + df[2:] I have tried this but it did not work. A: We can try using str.replace here. Assuming dat...
How Do I Add a '_' In The Middle of All Data in the Column of a DataFrame
eg . I have data like 2008Q1 , 2008Q2 , 2009Q1 in a single column. I want to give output as 2008_Q1 ,2008_Q2 df['quarter'] = df[:4] + '_' + df[2:] I have tried this but it did not work.
[ "We can try using str.replace here. Assuming data in the column would always have the format 2022Q1:\ndf[\"quarter\"] = df[\"quarter\"].str.replace(r'(?=Q\\d$)', '_', regex=True)\n\n", "You can try this :\ndf['quarter'] = df.quarter.apply(lambda x: x[:4] + '_' + x[-2:])\n\n" ]
[ 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074306104_pandas_python.txt
Q: Fitting negative binomial in python In scipy there is no support for fitting a negative binomial distribution using data (maybe due to the fact that the negative binomial in scipy is only discrete). For a normal distribution I would just do: from scipy.stats import norm param = norm.fit(samp) Is there something s...
Fitting negative binomial in python
In scipy there is no support for fitting a negative binomial distribution using data (maybe due to the fact that the negative binomial in scipy is only discrete). For a normal distribution I would just do: from scipy.stats import norm param = norm.fit(samp) Is there something similar 'ready to use' function in any oth...
[ "Statsmodels has discrete.discrete_model.NegativeBinomial.fit(), see here:\nhttps://www.statsmodels.org/dev/generated/statsmodels.discrete.discrete_model.NegativeBinomial.fit.html#statsmodels.discrete.discrete_model.NegativeBinomial.fit\n", "Not only because it is discrete, also because maximum likelihood fit to ...
[ 8, 7, 3, 0 ]
[]
[]
[ "distribution", "python", "scipy", "statistics", "statsmodels" ]
stackoverflow_0023816522_distribution_python_scipy_statistics_statsmodels.txt
Q: Custom eval metric using early stopping in LGBM (Sklearn API) and Optuna Questions: First question is probably extremely stupid but I will ask anyway: Is the pruning and the early stopping the same in this example below? Or is it two separate separate options controlling two separate processes? I got an imbalance...
Custom eval metric using early stopping in LGBM (Sklearn API) and Optuna
Questions: First question is probably extremely stupid but I will ask anyway: Is the pruning and the early stopping the same in this example below? Or is it two separate separate options controlling two separate processes? I got an imbalanced target, so how can I use a custom evaluation metric here instead of 'binary_...
[ "So after a day of experimenting I can answer my own questions:\n\nThe LGBM pruning defined by LightGBMPruningCallback(trial, \"your_metric\") is NOT the referring to the early stopping procedure. The LGBM pruning essentially skips evaluating all cv-folds within a given trial (i.e. for a given set of hyper paramete...
[ 0 ]
[]
[]
[ "lightgbm", "optuna", "python" ]
stackoverflow_0074303961_lightgbm_optuna_python.txt
Q: Program blinking exit dots I'm trying to make a message that appears when exiting the program. What I want it to look like is like this: 1. print the word "Quitting" 2. repeat 3 times: - halt for 0.5 seconds - print a dot in the same line with the word "Quitti...
Program blinking exit dots
I'm trying to make a message that appears when exiting the program. What I want it to look like is like this: 1. print the word "Quitting" 2. repeat 3 times: - halt for 0.5 seconds - print a dot in the same line with the word "Quitting" 3. show the p...
[ "Answer:\nimport time\n\nprint(\"Quitting\", end='', flush=True)\nfor i in range(3):\n print('.', end='', flush=True)\n time.sleep(0.5)\nprint('\\n')\n\n", "This appears to be a duplicate, but code works if you do it like this:\nimport time\n\nprint(\"Quitting\", end='')\nfor i in range(3):\n print('.', ...
[ 1, 0 ]
[]
[]
[ "loops", "newline", "printing", "python", "time" ]
stackoverflow_0074301844_loops_newline_printing_python_time.txt
Q: How does one find all attributes that are lambda/anonymous functions in pytorch without recursion bugs? I have lambda function that is screwing up the pickling of an object. What makes it hard to debug is that it doesn't tell me the name of field causing this issue. I created a recursive function that tries to fin...
How does one find all attributes that are lambda/anonymous functions in pytorch without recursion bugs?
I have lambda function that is screwing up the pickling of an object. What makes it hard to debug is that it doesn't tell me the name of field causing this issue. I created a recursive function that tries to find such fields but it fails on the code I need it to work on (but succeeds in toy self contained cases). It wo...
[ "Looking closer to your dataset\nprint()\nimport learn2learn\nfrom torch.utils.data import DataLoader\n\nomni = learn2learn.vision.benchmarks.get_tasksets('omniglot', root='~/data/l2l_data')\n\nprint(omni)\n\nBenchmarkTasksets(\n train=<learn2learn.data.task_dataset.TaskDataset object at 0x7f07cd9f8830>,\n valida...
[ 0, 0 ]
[]
[]
[ "anonymous_function", "lambda", "pickle", "python", "pytorch" ]
stackoverflow_0074249550_anonymous_function_lambda_pickle_python_pytorch.txt
Q: decompressing string from database in python I know this question will looks a bit unclear but I reached a level of frustration that drives me to ask this here.. I'm working with data from a POSTGRESQL database, and I get something like this: 2022-06-01 02:21:52.770293 2022-06-01 02:21:52.78704 \\x0a78daa5534d6...
decompressing string from database in python
I know this question will looks a bit unclear but I reached a level of frustration that drives me to ask this here.. I'm working with data from a POSTGRESQL database, and I get something like this: 2022-06-01 02:21:52.770293 2022-06-01 02:21:52.78704 \\x0a78daa5534d6fe32014fc2fdca90063b0c9a91f52d... 2022-06-01 02:21...
[ "The hexadecimal representations starting with 78da... are the starts of valid zlib streams. You need to discard the \\\\x0a and convert the remainder from hexadecimal to binary. The result of that would be given to zlib.decompress(). Look at a2b_hex in binascii.\n" ]
[ 2 ]
[]
[]
[ "bytea", "encoding", "python", "zlib" ]
stackoverflow_0074305894_bytea_encoding_python_zlib.txt
Q: Finding all possible iterations of a nested JSON structure I have a config file that I've been working out of, Ex: "Preprocessing": { "BOW":{"ngram_range":[1,2], "max_features":[100, 200]}, "RemoveStopWords": {"Parameter1": ["..."]} } The idea is to take this data and run every iteration between the two preproces...
Finding all possible iterations of a nested JSON structure
I have a config file that I've been working out of, Ex: "Preprocessing": { "BOW":{"ngram_range":[1,2], "max_features":[100, 200]}, "RemoveStopWords": {"Parameter1": ["..."]} } The idea is to take this data and run every iteration between the two preprocessing steps and pass it into a Preprocessing object. The output I...
[ "This should work for you - assuming you always want that same RemoveStopWords section. It generates the product of all feature keys and values:\nfrom itertools import product\n# pprint just to make output clearer\nfrom pprint import pprint\n\nconfig = {\n \"Preprocessing\": {\n \"BOW\": {\"ngram_range\":[1...
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074306166_json_python.txt
Q: Replace NaN with the average of the last 5 values - Pandas I want to know how can I replace the NaN in my dataset with the last average of 5 last values. Column A Column B 1 2 2 5 3 5 4 2 5 2 NaN 2 NaN 2 1 2 1 2 1 2 1 NaN 1 2 1 2 For example, in this case the first NaN will be the average of (1,2,3,...
Replace NaN with the average of the last 5 values - Pandas
I want to know how can I replace the NaN in my dataset with the last average of 5 last values. Column A Column B 1 2 2 5 3 5 4 2 5 2 NaN 2 NaN 2 1 2 1 2 1 2 1 NaN 1 2 1 2 For example, in this case the first NaN will be the average of (1,2,3,4,5) and second NaN will be the average of ...
[ "As mentioned, it has been answered here, but the updated version for the latest pandas version is as follow:\n\ndata={'col1':[1,2,3,4,5,np.nan,np.nan,1,1,1,1,1,1],\n 'col2':[2,5,5,2,2,2,2,2,2,2,np.nan,2,2]}\ndf=pd.DataFrame(data)\n\nwindow_size = 5\ndf=df.fillna(df.rolling(window_size+1, min_periods=1).mean()...
[ 0 ]
[]
[]
[ "database", "mean", "numpy", "pandas", "python" ]
stackoverflow_0074305299_database_mean_numpy_pandas_python.txt
Q: How to convert PySpark dataframe to dictionary: first column as main key, the other columns and their contents key-value pairs? I have created a data frame as follows in PySpark: from pyspark.sql.types import StructType, StructField, StringType, IntegerType data_1 = [ ("rule1", "", "1", "2", "3", "4"), ("...
How to convert PySpark dataframe to dictionary: first column as main key, the other columns and their contents key-value pairs?
I have created a data frame as follows in PySpark: from pyspark.sql.types import StructType, StructField, StringType, IntegerType data_1 = [ ("rule1", "", "1", "2", "3", "4"), ("rule2", "1", "3", "5", "6", "4"), ("rule3", "", "0", "1", "2", "5"), ("rule4", "0", "1", "3", "6", "2"), ] schema = StructTy...
[ "You can try these nested dictionary comprehensions:\ndict_rules = {r['_c0']: {k: v \n for k, v in r.asDict().items() \n if k != '_c0' and v != ''}\n for r in df.collect()}\n\n# {'rule1': {'para2': '1', 'para3': '2', 'para4': '3', 'para5': '4'},\n# 'rule...
[ 1 ]
[]
[]
[ "apache_spark", "dictionary", "pyspark", "python", "rdd" ]
stackoverflow_0074305383_apache_spark_dictionary_pyspark_python_rdd.txt
Q: serverless-python-requirements not working I have a "hello-world" python project with serverless framework. I'm trying to deploy a simple lambda function that needs numpy. But currently, when I run sls deploy and try to call the lambda function, I get an internal server error. Here is the structure of my project: ...
serverless-python-requirements not working
I have a "hello-world" python project with serverless framework. I'm trying to deploy a simple lambda function that needs numpy. But currently, when I run sls deploy and try to call the lambda function, I get an internal server error. Here is the structure of my project: test_api/ serverless.yml test_api.py ...
[ "Is it a typo in your serverless.yml file?\nyou have\nhandler: tes_api.handler \n\nI imagine it's meant to be test_api.handler\n", "Looking at the structure of your project, it seems you missed an important step mentioned in the documentation - no package.json. You need to run the following command in your projec...
[ 0, 0 ]
[]
[]
[ "aws_lambda", "python", "serverless_framework" ]
stackoverflow_0072645324_aws_lambda_python_serverless_framework.txt
Q: How to check if the current item's key name matches a certain string in Python? I'm looping through two lists "rows" and "columns" to create a dictionary "fields", which should look like that: fields = { "A0": " ", "A1": " ", "A2": " ", ... "A7": " ", "B0": " ", "B1": " ", ... ... "H6": " ", ...
How to check if the current item's key name matches a certain string in Python?
I'm looping through two lists "rows" and "columns" to create a dictionary "fields", which should look like that: fields = { "A0": " ", "A1": " ", "A2": " ", ... "A7": " ", "B0": " ", "B1": " ", ... ... "H6": " ", "H7": " " } After each of the items is created, I want to check whether the curre...
[ "you can use this expression to check if key is similar to the apple.\nfor r in rows:\n for c in columns:\n fields[r+c] = \" \"\n if r+c == apple:\n fields[r+c] = \"O\" \n\nThis way you are checking if current key is equal to what you want.\n", "You can do the following to find a key and update i...
[ 0, 0 ]
[]
[]
[ "dictionary", "key", "python", "python_3.x" ]
stackoverflow_0074303394_dictionary_key_python_python_3.x.txt
Q: Randomize a Number in python with conditions I have a list made up by these numbers: 3,7,15,31,63. I need to randomly take one of these numbers, but the one I obtain must be smaller of a Number taken from a cycle (it changes everytime and it is between an interval (10,100). Can somenone help me please? P.S. I rece...
Randomize a Number in python with conditions
I have a list made up by these numbers: 3,7,15,31,63. I need to randomly take one of these numbers, but the one I obtain must be smaller of a Number taken from a cycle (it changes everytime and it is between an interval (10,100). Can somenone help me please? P.S. I recently started using python and i don't know a loro ...
[ "Your best option is probably to simply select a random element form the list,\nimport random\nr = random.choice([3, 7, 15, 31, 63])\n\nand then check if is smaller than the number taken from your cycle.\nif r < cycle_num:\n print(r)\n\n", "Try this:\nimport random\n\n\nlst = [3, 7, 15, 31, 63]\n\nwhile True: #...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074306032_python.txt
Q: Translating np.einsum to something more performant Using python/numpy, I have the following np.einsum: np.einsum('abde,abc->bcde', X, Y) Y is sparse: for each [a,b], only one c == 1; all others := 0. For an example of relative size of the axes, X.shape is on the order of (1000, 5, 30, 30), and Y.shape is equivale...
Translating np.einsum to something more performant
Using python/numpy, I have the following np.einsum: np.einsum('abde,abc->bcde', X, Y) Y is sparse: for each [a,b], only one c == 1; all others := 0. For an example of relative size of the axes, X.shape is on the order of (1000, 5, 30, 30), and Y.shape is equivalently (1000, 5, 300). This operation is extremely costly;...
[ "You can do that pretty easily with Numba:\nimport numba\n\n@numba.njit('float64[:,:,:,::1](float64[:,:,:,::1], float64[:,:,::1])', fastmath=True, parallel=True)\ndef compute(x, y):\n na, nb, nd, ne = x.shape\n nc = y.shape[2]\n assert y.shape == (na, nb, nc)\n\n out = np.zeros((nb, nc, nd, ne))\n\n ...
[ 1, 1 ]
[]
[]
[ "numpy", "numpy_einsum", "python", "sparse_matrix", "tensordot" ]
stackoverflow_0074300919_numpy_numpy_einsum_python_sparse_matrix_tensordot.txt
Q: Split the given integer value as date 20160116 Suppose this is the data with datatype integer in a column and now I want to convert it like 2016/01/16 or 2016-01-16 and datatype as date. My column name is system and dataframe is df. How can I do that? I tried using many date format function but It was not good eno...
Split the given integer value as date
20160116 Suppose this is the data with datatype integer in a column and now I want to convert it like 2016/01/16 or 2016-01-16 and datatype as date. My column name is system and dataframe is df. How can I do that? I tried using many date format function but It was not good enough to achieve the answer.
[ "convert using to_datetime, provide the format\nthen convert to the format of your desire\npd.to_datetime(df['dte'], format='%Y%m%d').dt.strftime('%Y/%m/%d')\n\n0 2016/01/06\nName: dte, dtype: object\n\n", "Using str.replace we can try:\ndf[\"date\"] = df[\"system\"].astype(str).str.replace(r'(\\d{4})(\\d{2})(...
[ 2, 0 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074306334_dataframe_datetime_pandas_python.txt
Q: Apple M1 - Symbol not found: _CFRelease while running Python app I am hoping to run my app without any problem, but I got this attached error. Could someone help or point me into the right direction as to why this is happening? Traceback (most recent call last): File "/Users/andre.sitorus/Documents/GitHub/nexus/...
Apple M1 - Symbol not found: _CFRelease while running Python app
I am hoping to run my app without any problem, but I got this attached error. Could someone help or point me into the right direction as to why this is happening? Traceback (most recent call last): File "/Users/andre.sitorus/Documents/GitHub/nexus/automation-api/app/main.py", line 4, in <module> from configuratio...
[ "Had the same issue; turned out it's because of the grpcio build. Doing this helped:\npip uninstall grpcio\nconda install grpcio\n\n(Make sure you use the conda-forge channel with conda; the community puts in work to make sure packages play well with M1/arm64)\n", "I was able to get around the problem by rebuildi...
[ 12, 1 ]
[]
[]
[ "apple_m1", "conda", "grpc_python", "python", "python_3.x" ]
stackoverflow_0072620996_apple_m1_conda_grpc_python_python_python_3.x.txt
Q: Calculating duration per user per location user of Wi-Fi timeseries logs I have a Wi-Fi log dataset that shows users interacting with Wireless access points (AP). I was able to generate new column named floor that shows which floor the APs are on, giving a very rough estimation of user position in the building. He...
Calculating duration per user per location user of Wi-Fi timeseries logs
I have a Wi-Fi log dataset that shows users interacting with Wireless access points (AP). I was able to generate new column named floor that shows which floor the APs are on, giving a very rough estimation of user position in the building. Here is a simplified sample of the data set: ID _user vlan_role Floor Dateti...
[ "So it looks like there are a few problems with the data set that we'll need to resolve before getting good information:\n\nThere are duplicate values (ie - ID 7 and 8 have the same timestamp)\nThe user can interact with a floor more than once before moving\n\nThe first one can be cleaned up by running df.drop_dupl...
[ 2 ]
[]
[]
[ "indoor_positioning_system", "pandas", "python", "time_series" ]
stackoverflow_0074305827_indoor_positioning_system_pandas_python_time_series.txt
Q: GA Multi Channel Funnels Reporting Python errors I have successfully be able to query data from Google Analytics with the python exemple available on G web site using reports().batchGet() Now I have to do the same with the multi channel funnel (mcf). Everything I can see on StackO or anywhere else is to call servi...
GA Multi Channel Funnels Reporting Python errors
I have successfully be able to query data from Google Analytics with the python exemple available on G web site using reports().batchGet() Now I have to do the same with the multi channel funnel (mcf). Everything I can see on StackO or anywhere else is to call service.data().mcf().get(). But then I got the error Attrib...
[ "You can pull data using below code:\ndef initialize_mcf_analyticsreporting():\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n KEY_FILE_LOCATION, SCOPES)\n analytics = build('analytics', 'v3', credentials=credentials)\n mcf_service = analytics.data().mcf()\n return mcf_service...
[ 1 ]
[]
[]
[ "google_analytics_api", "python" ]
stackoverflow_0055005329_google_analytics_api_python.txt
Q: How can I scrape restaurant titles and descriptions if website has load more button? I am using Beautiful Soup and I'm trying to get all restaurant titles and descriptions from the infatuation. This is proving difficult as the website has lots of nested HTML structure as well as a load more button. Here's where I ...
How can I scrape restaurant titles and descriptions if website has load more button?
I am using Beautiful Soup and I'm trying to get all restaurant titles and descriptions from the infatuation. This is proving difficult as the website has lots of nested HTML structure as well as a load more button. Here's where I am. Code: #Request to website and download HTML contents url='https://www.theinfatuation.c...
[ "Your best option is probably to use the python requests library to request the JSON with the reviews. \nWhen you click on the button, the website's JavaScript requests JSON that contains all the data for the reviews. This means you can bypass the button by just requesting the JSON with python. I just took a quick ...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "web_scraping" ]
stackoverflow_0074305581_beautifulsoup_python_selenium_web_scraping.txt
Q: Unable to solve, Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter state is not initialized Unable to solve this error: tensorflow.python.framework.errors_impl.InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [4,1] and lab...
Unable to solve, Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter state is not initialized
Unable to solve this error: tensorflow.python.framework.errors_impl.InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [4,1] and labels shape [12] [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits (defined at /U...
[ "The following solved the issue for me:\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\n\n\ndef fix_gpu():\n config = ConfigProto()\n config.gpu_options.allow_growth = True\n session = InteractiveSession(config=config)\n\n\nfix_gpu()\n\nCall this function...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "conv_neural_network", "python", "python_3.x", "tensorflow", "tensorflow2.0" ]
stackoverflow_0062943048_conv_neural_network_python_python_3.x_tensorflow_tensorflow2.0.txt
Q: How can i make user enter "string" and enter (index) and remove this (index) from "string" which he entered? Text = input(">> Please, Enter The Text: ") index_X = input(">> Please, Enter The index_X which you want to remove from 'Text': ") print(Text.remove(index_X)) i tried to use replace method but i think ther...
How can i make user enter "string" and enter (index) and remove this (index) from "string" which he entered?
Text = input(">> Please, Enter The Text: ") index_X = input(">> Please, Enter The index_X which you want to remove from 'Text': ") print(Text.remove(index_X)) i tried to use replace method but i think there is another way
[ "You could take the piece of the string prior to the index and then the piece of the string after the index and put them together.\nText = input(\">> Please, Enter The Text: \")\nindex_X = int(input(\">> Please, Enter The index_X which you want to remove from 'Text': \")) #convert to int\nnew_text = Text[:index_X] ...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074306409_python_python_3.x.txt
Q: Get Bokeh's selection in notebook I'd like to select some points on a plot (e.g. from box_select or lasso_select) and retrieve them in a Jupyter notebook for further data exploration. How can I do that? For instance, in the code below, how to export the selection from Bokeh to the notebook? If I need a Bokeh serve...
Get Bokeh's selection in notebook
I'd like to select some points on a plot (e.g. from box_select or lasso_select) and retrieve them in a Jupyter notebook for further data exploration. How can I do that? For instance, in the code below, how to export the selection from Bokeh to the notebook? If I need a Bokeh server, this is fine too (I saw in the docs ...
[ "To select some points on a plot and retrieve them in a Jupyter notebook, you can use a CustomJS callback.\nWithin the CustomJS callback javascript code, you can access the Jupyter notebook kernel using IPython.notebook.kernel. Then, you can use kernal.execute(python_code) to run Python code and (for example) expor...
[ 4, 3, 1 ]
[]
[]
[ "bokeh", "jupyter_notebook", "python" ]
stackoverflow_0061340741_bokeh_jupyter_notebook_python.txt
Q: Why a method works differently with a list when stored in the variable and used and in other case not stored, but used directly? This works.. indices = [1, 2, 3, 5, 8] sample_reviews = reviews.loc[indices] But... this does not works the same way, instead shows an error sample_reviews = reviews.loc[1, 2, 3, 5, 8] ...
Why a method works differently with a list when stored in the variable and used and in other case not stored, but used directly?
This works.. indices = [1, 2, 3, 5, 8] sample_reviews = reviews.loc[indices] But... this does not works the same way, instead shows an error sample_reviews = reviews.loc[1, 2, 3, 5, 8]
[ "In the first case your are passing a list called indicies to the function, which is correct. In the second, you are passing 5 ints, which is incorrect. You need to change the second to:\nsample_reviews = reviews.loc[[1, 2, 3, 5, 8]]\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074306426_pandas_python.txt
Q: second derivative is None in tensorflow automatic differentiation In the code below, I'm computing the second derivative (y_xx_lin) of a linear network modelLinear which has linear activation functions throughout, and the second derivative (y_xx_tanh) of a tanh network modelTanh which has tanh activations for all ...
second derivative is None in tensorflow automatic differentiation
In the code below, I'm computing the second derivative (y_xx_lin) of a linear network modelLinear which has linear activation functions throughout, and the second derivative (y_xx_tanh) of a tanh network modelTanh which has tanh activations for all its layers except the last layer which is linear. My question is: y_xx_...
[ "It works if you set lambda x: x ** 1 instead of 'linear' like\n...\n\nid_func = lambda x: x ** 1\n\ndef build_network(activation=id_func):\n input_layer = Input(1)\n inner_layer = Dense(6, activation=activation)(input_layer)\n inner_layer1 = Dense(6, activation=activation)(inner_layer)\n inner_layer2...
[ 1 ]
[ "If you want to calculate deviation from input as a series ( I see your question and intention but you can do it with the model layer as codes example, you may adjust a bit for convenience)\nSample: << How fast it growths is how fast they turn out >>\nimport tensorflow as tf\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\...
[ -3 ]
[ "automatic_differentiation", "gradient", "machine_learning", "python", "tensorflow" ]
stackoverflow_0074298007_automatic_differentiation_gradient_machine_learning_python_tensorflow.txt
Q: I launched a django server and now I can't stop the process Can anyone please tell me how to stop my server? I did like the first few things you need to do in order to commence a django webpage, url pattern, request, HttpResponce etc. and I ran my server but that rocket is still showing on my screen despite trying...
I launched a django server and now I can't stop the process
Can anyone please tell me how to stop my server? I did like the first few things you need to do in order to commence a django webpage, url pattern, request, HttpResponce etc. and I ran my server but that rocket is still showing on my screen despite trying to kill, pkill, ctrl+pause, ctrl+C. I'm so done with this... I l...
[ "Without a screenshot, we can only guess the issue.\nI see you've tried some of the basic keybinds, have you tried CTRL+F4?\nYou could also kill the process.\nps auxw | grep runserver\nThis will return a process and the associated PID\nde 7956 1.8 0.6 540204 55212 ? Sl 13:27 0:09 /home/de/Develo...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074306261_django_python.txt
Q: How to set pandas table properties globally? I want to print my pandas dataframes with newline characters actually being new lines. I can use the following code but it's quite verbose. How can I set this globally, i.e., for this jupyter notebook? df = pd.DataFrame({ 'data': ['Laughing\nIs\nGood\nFor\nYou'] }) ...
How to set pandas table properties globally?
I want to print my pandas dataframes with newline characters actually being new lines. I can use the following code but it's quite verbose. How can I set this globally, i.e., for this jupyter notebook? df = pd.DataFrame({ 'data': ['Laughing\nIs\nGood\nFor\nYou'] }) # Shows newline characters as '\n' display(df) #...
[ "Illustrating with code adapted from OP code my comment about the use of Sharing styles to export a style and use again to be less verbose:\nimport pandas as pd\ndf = pd.DataFrame({\n 'data': ['Laughing\\nIs\\nGood\\nFor\\nYou']\n})\n\n# Shows newline characters as '\\n'\ndisplay(df)\n\nmy_df_styled=df.style.set...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074306265_pandas_python.txt
Q: Automatic change of Discord "About me" THE PROBLEM: In Discord, as you may know, there is an "About me" section. This section is a description of a profile that you can write yourself. Bots can have an "About me" section. What I want to do is to edit this "About me" section automatically in discord.py; For example...
Automatic change of Discord "About me"
THE PROBLEM: In Discord, as you may know, there is an "About me" section. This section is a description of a profile that you can write yourself. Bots can have an "About me" section. What I want to do is to edit this "About me" section automatically in discord.py; For example, the "About me" section of the bot changes ...
[ "There is an answer.\nYou can fully automate it with Python in a few lines.\nWith the requests library.\nYou just have to first include requests with:\nimport requests\n\nThen, do a patch request\nrequests.patch(url=\"https://discord.com/api/v9/users/@me\", headers= {\"authorization\": token}, json = {\"bio\": abio...
[ 3, 0 ]
[ "You can only do this as the application owner/a team member manually in the Developer Portal.\nAutomating this would count as automating your user account (eg. self-boting) wich is against Discords Terms of Service and can get your account banned.\nThe bot itself has no access to this endpoint.\n", "You can’t ch...
[ -1, -1 ]
[ "discord", "discord.py", "http", "python", "python_requests" ]
stackoverflow_0070350364_discord_discord.py_http_python_python_requests.txt
Q: When i run my program.exe six times open new windows (PYQT5) My program is pdf file compressing firstly convert pdf to image and resize this image and finally convert image to pdf. When i compile this code in Spyder. Program is run correctly but i convert to exe using pyinstaller and choosing mid quality or low qu...
When i run my program.exe six times open new windows (PYQT5)
My program is pdf file compressing firstly convert pdf to image and resize this image and finally convert image to pdf. When i compile this code in Spyder. Program is run correctly but i convert to exe using pyinstaller and choosing mid quality or low quaility and press compress button six times open new window. i did...
[ "pypdfium2's PdfDocument.render_to() method is a multi-page renderer backed by a process pool. With PyInstaller, the spawning of a new process would launch a new instance of your app, so the code needs to be protected with a call to multiprocessing.freeze_support() right at the start of your if __name__ == '__main_...
[ 1 ]
[]
[]
[ "progress_bar", "pyinstaller", "pyqt5", "python", "spyder" ]
stackoverflow_0074053212_progress_bar_pyinstaller_pyqt5_python_spyder.txt
Q: How do you conda install a library in an environment created with virtualenv? I'm working on a (python) project where the choice was to create a virtual environment using virtualenv. However, one of the project dependencies can't be installed through pip on macOS due to this bug: https://github.com/streamlit/strea...
How do you conda install a library in an environment created with virtualenv?
I'm working on a (python) project where the choice was to create a virtual environment using virtualenv. However, one of the project dependencies can't be installed through pip on macOS due to this bug: https://github.com/streamlit/streamlit/issues/283 The workaround is to conda install one of the dependencies to bypas...
[ "I think the easiest approach would be to create a conda env by it's own. \n1) Create a requirement.txt file by doing pip freeze > requirements.txt inside your virtualenv environment\n2) Create conda env: conda create --name myenv\n3) Activate your environment: source activate myenv\n4) Install your dependencies: c...
[ 17, 0 ]
[]
[]
[ "conda", "pip", "python", "virtualenv" ]
stackoverflow_0059210762_conda_pip_python_virtualenv.txt
Q: module 'numpy' has no attribute 'round' I quite begginer with Python and have actually a problem with numpy. When I try to import seaborn (chart visualisation) or to do a kmeans with sklearn, I have a message of error : "AttributeError: module 'numpy' has no attribute 'round'" I don't really understand the problem...
module 'numpy' has no attribute 'round'
I quite begginer with Python and have actually a problem with numpy. When I try to import seaborn (chart visualisation) or to do a kmeans with sklearn, I have a message of error : "AttributeError: module 'numpy' has no attribute 'round'" I don't really understand the problem. My numpy package is version 1.23.4 and I al...
[ "If you are performing the rounding yourself:\nThere is no numpy round function but there is a round_ function.\n\nnp.round(arr) #does not exist\nnp.round_(arr) #does exist\n\n\nIf you are NOT:\nPlease check that you have NOT overwritten numpy.py somewhere on accident\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "numpy", "python" ]
stackoverflow_0074306351_attributeerror_numpy_python.txt
Q: How can i Parse my Date Column after getting Nasdaq dataset from yahoofinance in Python I got a live data from yahoo finance as follows: ndx = yf.Ticker("NDX") # get stock info print(ndx.info) # get historical market data hist = ndx.history(period="1825d") I downloaded it and Exported to CSV file as follows: ...
How can i Parse my Date Column after getting Nasdaq dataset from yahoofinance in Python
I got a live data from yahoo finance as follows: ndx = yf.Ticker("NDX") # get stock info print(ndx.info) # get historical market data hist = ndx.history(period="1825d") I downloaded it and Exported to CSV file as follows: #Download stock data then export as CSV df = yf.download("NDX", start="2016-01-01", end="202...
[ "Always great to see people trying to learn financial analysis:\n\nBefore I get into the solution I just want to remind you to make sure you put your imports in your question (yfinance isn't always aliased as yf). Also make sure you type or copy/paste your code so that we can easily grab it and run it!\n\nSo, I am...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074305842_python.txt
Q: Selenium xpath no result I am trying to do some web scrawling through Selenium. However, when I run the code, it does not show the result. Here is my code: import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from bs4 import Bea...
Selenium xpath no result
I am trying to do some web scrawling through Selenium. However, when I run the code, it does not show the result. Here is my code: import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from bs4 import BeautifulSoup import time import ...
[ "Hi sometimes errors may occur in xpath copying. There may be inconsistencies with the command you want to take action.You can try using commands.\nfind_element_by_css_selector\nfind_element_by_class_name\n\nMy example project may help you.\nhttps://github.com/kaayaumutt/instagramBotApp/blob/main/instagramBotApp/in...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "xpath" ]
stackoverflow_0074306417_python_selenium_xpath.txt
Q: transposing data based on column value using python I have web traffic data for a different channel. I want to transpose based on the channel name and get multiple time series. day main_channel visits CR 11/2/2022 a 443645 1.248513488 11/2/2022 b 382870 3.441750617 11/2/2022 c 51249 0.315164766...
transposing data based on column value using python
I have web traffic data for a different channel. I want to transpose based on the channel name and get multiple time series. day main_channel visits CR 11/2/2022 a 443645 1.248513488 11/2/2022 b 382870 3.441750617 11/2/2022 c 51249 0.315164766 11/1/2022 a 390267 2.725545677 11/1/2022 b 1536...
[ "IF using pandas are fine. you could import your data as csv\ndf = pd.read_csv('data.csv')\ndf = df.pivot_table(columns='main_channel', index='day', values=['visits','CR'])\ndf.columns = ['_'.join(reversed(col)) for col in df.columns.values]\n\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python", "python_3.x", "transpose" ]
stackoverflow_0074306220_pandas_python_python_3.x_transpose.txt
Q: Optimization with solver 'trust-constr' how can I use the solver 'trust-constr only with linear inequality constraints? my constraints is c(x)>0 & c(x)=g(x,teta)-ymin how can I use only this linear inequality constraints for solver 'trust-constr' ? the python code for c(x) constraint is doing interpolation like be...
Optimization with solver 'trust-constr'
how can I use the solver 'trust-constr only with linear inequality constraints? my constraints is c(x)>0 & c(x)=g(x,teta)-ymin how can I use only this linear inequality constraints for solver 'trust-constr' ? the python code for c(x) constraint is doing interpolation like below: #pressure_cons_val is ymin #input_val is...
[ "please try to provide a minimal reproducible example.\nYou can find details about the solver here:\n\noptimize.minimize-trustconstr\n\nIf the constraint is linear in one or more variable, you need to wrap it into the SciPy's LinearConstraint object.\nI cannot help you better until I'm able to read and understand y...
[ 0 ]
[]
[]
[ "optimization", "python", "scipy", "scipy_optimize_minimize" ]
stackoverflow_0074306606_optimization_python_scipy_scipy_optimize_minimize.txt
Q: List in a List or Tuples I have a bunch of audio files ('ZOOM0001_LR.WAV', 'ZOOM0001_TR1.WAV', 'ZOOM0001_TR3.WAV', 'ZOOM0002_LR.WAV', 'ZOOM0002_TR1.WAV', 'ZOOM0002_TR3.WAV') What I want to do is group Zoom0001_XX files into a list in the list and Zoom0002_XX into the list as well and so forth. files = list(glob.g...
List in a List or Tuples
I have a bunch of audio files ('ZOOM0001_LR.WAV', 'ZOOM0001_TR1.WAV', 'ZOOM0001_TR3.WAV', 'ZOOM0002_LR.WAV', 'ZOOM0002_TR1.WAV', 'ZOOM0002_TR3.WAV') What I want to do is group Zoom0001_XX files into a list in the list and Zoom0002_XX into the list as well and so forth. files = list(glob.glob(os.path.join(r'C:\Users\ad...
[ "Once you have your list of files you can use itertools.groupby:\nfrom itertools import groupby\n\nfiles = ('ZOOM0001_LR.WAV',\n 'ZOOM0001_TR1.WAV',\n 'ZOOM0001_TR3.WAV',\n 'ZOOM0002_LR.WAV',\n 'ZOOM0002_TR1.WAV',\n 'ZOOM0002_TR3.WAV')\n\nresult = []\nfor _, group in grouby(f...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074306598_python.txt
Q: Global dependency as an argument to each handler Looking at the docs I got to use my app settings in this way: import config ... @router.post('') async def my_handler( ... settings: config.SettingsCommon = fastapi.Depends(config.get_settings), ): ... But I am not satisfied with repeating everywhere ...
Global dependency as an argument to each handler
Looking at the docs I got to use my app settings in this way: import config ... @router.post('') async def my_handler( ... settings: config.SettingsCommon = fastapi.Depends(config.get_settings), ): ... But I am not satisfied with repeating everywhere import config, config.get_settings. Is there a way to ...
[ "You can use Class Based Views from the fastapi_utils package.\nAs an example:\nfrom fastapi import APIRouter, Depends, FastAPI\nfrom fastapi_utils.cbv import cbv\nfrom starlette import requests\nfrom logging import Logger\n\nimport config\nfrom auth import my_auth\n\nrouter = APIRouter(\n tags=['Settings test']...
[ 2, 1 ]
[]
[]
[ "fastapi", "python" ]
stackoverflow_0067191870_fastapi_python.txt
Q: In Django, how does one filter a QuerySet with dynamic field lookups? Given a class: from django.db import models class Person(models.Model): name = models.CharField(max_length=20) Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example: # Instead of: Person....
In Django, how does one filter a QuerySet with dynamic field lookups?
Given a class: from django.db import models class Person(models.Model): name = models.CharField(max_length=20) Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example: # Instead of: Person.objects.filter(name__startswith='B') # ... and: Person.objects.filter(nam...
[ "Python's argument expansion may be used to solve this problem:\nkwargs = {\n '{0}__{1}'.format('name', 'startswith'): 'A',\n '{0}__{1}'.format('name', 'endswith'): 'Z'\n}\n\nPerson.objects.filter(**kwargs)\n\nThis is a very common and useful Python idiom.\n", "A simplified example: \nIn a Django survey app...
[ 358, 7, 6, 5, 0 ]
[ "A really complex search forms usually indicates that a simpler model is trying to dig it's way out.\nHow, exactly, do you expect to get the values for the column name and operation?\nWhere do you get the values of 'name' an 'startswith'?\n filter_by = '%s__%s' % ('name', 'startswith')\n\n\nA \"search\" form? You'...
[ -3 ]
[ "django", "django_models", "python" ]
stackoverflow_0000310732_django_django_models_python.txt
Q: Nested groupby using Pandas I would like to sum the energy values for US, China and Japan and label this 'group1' Then groupby date, country, type and sum the energy values. Data We are grouping by date, and type and taking the sum of these specific countries: US, China and Japan - renaming this combination as gro...
Nested groupby using Pandas
I would like to sum the energy values for US, China and Japan and label this 'group1' Then groupby date, country, type and sum the energy values. Data We are grouping by date, and type and taking the sum of these specific countries: US, China and Japan - renaming this combination as group1 date country type e...
[ "If you want to combine them, how about just filter first and change the value to group1 and then do the groupby?\ndf.loc[df['country'].isin(['US', 'China', 'Japan']), 'country'] = 'group1'\ndf.groupby(['date', 'type', 'country'], as_index=False, sort=False).agg({'energy': sum})\n\n date type country ene...
[ 1, 1 ]
[]
[]
[ "group_by", "numpy", "pandas", "python" ]
stackoverflow_0074306713_group_by_numpy_pandas_python.txt
Q: Ternary Max Heap Python I am trying to turn a Binary Max Heap into a Ternary Max Heap in Python. My code needs to remain in the same structure as the binary heap below. I need some help figuring out what changes to make. I know the max child method needs to be updated with 3 * i - 1, 3 * i, and 3 * i + 1. I don't ...
Ternary Max Heap Python
I am trying to turn a Binary Max Heap into a Ternary Max Heap in Python. My code needs to remain in the same structure as the binary heap below. I need some help figuring out what changes to make. I know the max child method needs to be updated with 3 * i - 1, 3 * i, and 3 * i + 1. I don't know where to begin. Any sugg...
[ "While a dummy entry can still be interesting for a binary heap implementation, to get the same \"benefit\" for a ternary heap, you would need 2 dummies. It is better to just adapt the index calculations and have no dummy needs. Without the dummy it becomes also overkill to have a size attribute, since it always co...
[ 1 ]
[]
[]
[ "heap", "python", "ternary" ]
stackoverflow_0074298132_heap_python_ternary.txt
Q: ValueError: Invalid classes inferred from unique values of `y` in XGBoost I'm new to the Data Science field and I'm trying to apply XGBoost in a table having 5 rows × 46 columns and my last column is my target column. import sys !{sys.executable} -m pip install xgboost import xgboost as xgb from sklearn.model_sele...
ValueError: Invalid classes inferred from unique values of `y` in XGBoost
I'm new to the Data Science field and I'm trying to apply XGBoost in a table having 5 rows × 46 columns and my last column is my target column. import sys !{sys.executable} -m pip install xgboost import xgboost as xgb from sklearn.model_selection import train_test_split x=df_null_mean.iloc[:,:-1] y=df_null_mean.iloc[:...
[ "I think you need to have the class numerotated from 0 to n-1 where n is your number of class.\nTry this:\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\ny_train = le.fit_transform(y_train)\n\n" ]
[ 0 ]
[]
[]
[ "machine_learning", "pandas", "python", "xgboost" ]
stackoverflow_0074306326_machine_learning_pandas_python_xgboost.txt
Q: Why the second variable `PP` in the loop FOR nested not take the value PP=0 y_vals,y_vals_max=[],[] y_vals = [7,6,5,4,3,2,1,7,6,5,4,3,2,1] c = 0 for jj in range(0,len (y_vals),1): for pp in range(1, len(y_vals),1): if y_vals[jj] > y_vals[pp]: ...
Why the second variable `PP` in the loop FOR nested not take the value PP=0
y_vals,y_vals_max=[],[] y_vals = [7,6,5,4,3,2,1,7,6,5,4,3,2,1] c = 0 for jj in range(0,len (y_vals),1): for pp in range(1, len(y_vals),1): if y_vals[jj] > y_vals[pp]: if (y_vals[jj] - y_vals[pp]) >=0: c = c + 1 ...
[ "Just by looking at this i see the number \"c\" goes way above the number of length of y_vals. Each iteration that starts with 7-6, 7-5, 7-4.. up to 6-7 where first FOR breaks increases \"c\" by one. Then you remove elements from y_vals with index of range(c) which makes the whole y_vals list empty. Then it would s...
[ 0 ]
[]
[]
[ "arrays", "for_loop", "list", "python", "python_3.x" ]
stackoverflow_0074305678_arrays_for_loop_list_python_python_3.x.txt
Q: Python asyncio double await For some reason I need to write a double await, but I don't exactly know why. Can someone explain this to me? I've created a small example of the issue I ran into. import asyncio from random import randint async def work(): return randint(1, 100) async def page(): return async...
Python asyncio double await
For some reason I need to write a double await, but I don't exactly know why. Can someone explain this to me? I've created a small example of the issue I ran into. import asyncio from random import randint async def work(): return randint(1, 100) async def page(): return asyncio.gather(*[ work() ...
[ "To actually execute awaitable objects you need to await on them.\nYour page here is coroutine function, when called, it returns a coroutine which is an awaitable object!\nWhen you say await page(), you're running the body of it. after execution it gives you(return) another awaitable object which is the result of c...
[ 1 ]
[]
[]
[ "async_await", "python", "python_3.x", "python_asyncio" ]
stackoverflow_0074306518_async_await_python_python_3.x_python_asyncio.txt
Q: How to add description to parameters of command in discord.py? Let's say that i have this command: @bot.command(description='command do some stuff') async def somecommand(ctx: commands.Context, arg1:str, arg2:str = "hello"): await ctx.channel.send(arg1+arg2) And when I call help command: !help somecommand or ...
How to add description to parameters of command in discord.py?
Let's say that i have this command: @bot.command(description='command do some stuff') async def somecommand(ctx: commands.Context, arg1:str, arg2:str = "hello"): await ctx.channel.send(arg1+arg2) And when I call help command: !help somecommand or ?help somecommand (depends on prefix) it returns: How can I add des...
[ "Use commands.parameter() as the value, and set the description kwarg. Only difference is that to give it a default value you now have to use the default kwarg of commands.parameter() instead of directly passing it in the function.\nasync def some_command(ctx, arg1: str = commands.parameter(default=\"Here be defaul...
[ 2 ]
[]
[]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0074306864_bots_discord_discord.py_python.txt
Q: Is it possible to download images from a private telegram channel? Is it possible to download images from a private telegram channel without admin rights using Python? Basically what I want is the script to wait till a picture is sent in the private channel and if one got sent, I want it download the picture with ...
Is it possible to download images from a private telegram channel?
Is it possible to download images from a private telegram channel without admin rights using Python? Basically what I want is the script to wait till a picture is sent in the private channel and if one got sent, I want it download the picture with the filename increasing(img1, img2...). Problem is I dont have admin rig...
[ "Sure. If you have access to this channel, you can use the \"telethon\" library to implement this function.\nhttps://docs.telethon.dev/en/stable/\nThe first thing you have to do is get a channel\ninput_entity = await UserMethods.get_input_entity(client, peer=\"https://t.me/example\")\nentity = await client.get_enti...
[ 0 ]
[]
[]
[ "python", "python_3.x", "telegram" ]
stackoverflow_0070328110_python_python_3.x_telegram.txt
Q: How to assert values that An Exception class contains I have a One Exception with a Type value inside it. I am using this exception ContentNotFoundException with type attribute that's says what content is missing (name, age, sex, etc.) So while unittesting, i would like to know the type of the exception. I have be...
How to assert values that An Exception class contains
I have a One Exception with a Type value inside it. I am using this exception ContentNotFoundException with type attribute that's says what content is missing (name, age, sex, etc.) So while unittesting, i would like to know the type of the exception. I have been using assertRaises but I am not able to verify if the ri...
[ "If you use Pytest, you can use code like this:\nwith pytest.raises(YourExceptionType) as ex:\n some_code_that_should_throw();\n\nassert ex.value == \"something\"\n\nNote that the assert must be outside the with block, as the with block is exited by the exception.\nSee the Pytest documentation for details.\n" ]
[ 0 ]
[]
[]
[ "python", "testing", "unit_testing" ]
stackoverflow_0074306708_python_testing_unit_testing.txt
Q: Finding ideal weekly staffing levels, while maintaining inventory levels using PuLP I'm trying to solve for the minimal weekly manufacturing staffing levels based on our weekly inventory deliveries. import numpy as np import pulp as p inventory_delivery = np.array([200, 500, 0, 900, 0]) # deliveries over 5 weeks ...
Finding ideal weekly staffing levels, while maintaining inventory levels using PuLP
I'm trying to solve for the minimal weekly manufacturing staffing levels based on our weekly inventory deliveries. import numpy as np import pulp as p inventory_delivery = np.array([200, 500, 0, 900, 0]) # deliveries over 5 weeks productivity = 1 # using 1 to keep it simple for now. This varies week by week. prob = p...
[ "Reading between the lines a bit, I think the below is about what you are looking for. A couple of key concepts that will help you:\n\nIt is generally good to set up your variables to be indexed by a set (or list in this case). That allows you to use easy-to-read loops to make constraints \"for each week\" in you...
[ 2 ]
[]
[]
[ "linear_programming", "numpy", "optimization", "pulp", "python" ]
stackoverflow_0074298560_linear_programming_numpy_optimization_pulp_python.txt
Q: Trying to have multiple turtles running and drawing at the same time NOT on a straight line I'm currently trying to have multiple turtles running at the same time to draw a sun and its rays, i'd like to draw both of them at the same time. I need other things to run also at the same time of them but once i get how ...
Trying to have multiple turtles running and drawing at the same time NOT on a straight line
I'm currently trying to have multiple turtles running at the same time to draw a sun and its rays, i'd like to draw both of them at the same time. I need other things to run also at the same time of them but once i get how to do with two, it shouldn't be that difficult to do it with more. I tried to look for answer her...
[ "Below is a minimal example of a simpler solution than threads or timer events -- just rearranging your loops:\nfrom turtle import Screen, Turtle\n\ndef drawCircle(t, radius):\n t.sety(t.ycor() - radius)\n\n t.begin_fill()\n t.circle(radius)\n t.end_fill()\n\n t.sety(t.ycor() + radius)\n\ndef drawEig...
[ 0 ]
[]
[]
[ "python", "turtle_graphics", "while_loop" ]
stackoverflow_0074300659_python_turtle_graphics_while_loop.txt
Q: Plotnine: color scale and legend issues I'm trying to make some plots with plotnine. I have clustered points into several clusters labeled 0 through 6. (but this range may change depending on the number of clusters in the future). My goal is to plot each cluster with its own point on the legend, using plotnine's d...
Plotnine: color scale and legend issues
I'm trying to make some plots with plotnine. I have clustered points into several clusters labeled 0 through 6. (but this range may change depending on the number of clusters in the future). My goal is to plot each cluster with its own point on the legend, using plotnine's default color palette (I actually like it bett...
[ "Use an ordered categorical.\npd.Categorical(data['cluster'], categories=[1, 2, 3, ...], ordered=True)\n\n", "For some reason my colors are changing when I use categorical, but I found a solution.\nI found some useful code (here) and adapted it slightly:\ndef discrete_cmap_hex(N, base_cmap=None):\n\"\"\"Create an...
[ 0, 0 ]
[]
[]
[ "colors", "matplotlib", "pandas", "plotnine", "python" ]
stackoverflow_0074295481_colors_matplotlib_pandas_plotnine_python.txt
Q: Have multiple names in a column, need to create a row for each one I have a dataframe in which I have a column with multiple values (column A), I need to create a row for each value in this column keeping the data from the other columns (column B and others) Column A Column B Xbox, Playstation Xbox Elite 2, Dual...
Have multiple names in a column, need to create a row for each one
I have a dataframe in which I have a column with multiple values (column A), I need to create a row for each value in this column keeping the data from the other columns (column B and others) Column A Column B Xbox, Playstation Xbox Elite 2, Dualsense Edge Xbox, Nintendo, Atlus Persona 3 Portable, Persona 4 G...
[ "here is one way to do it, convert the values to a list and then explode into rows\n# split the column on , which makes the content of columnA as a list\ndf['Column A']=df['Column A'].str.strip().str.split(',' )\n\n# explode\nout=df.explode(['Column A'])\nout\n\n\n Column A Column B\n0 Xbox X...
[ 0 ]
[]
[]
[ "dataframe", "group_by", "python" ]
stackoverflow_0074307058_dataframe_group_by_python.txt
Q: How can I only print a value if it is greater than zero? I am creating a coin return calculator. I have all the code wrote but I can't figure out how to only display the coins that are needed instead of getting the coins I don't need. Enter change amount to convert: 3 0 quarter(s) 0 dime(s) 0 nickle(s) 3 penny(ies...
How can I only print a value if it is greater than zero?
I am creating a coin return calculator. I have all the code wrote but I can't figure out how to only display the coins that are needed instead of getting the coins I don't need. Enter change amount to convert: 3 0 quarter(s) 0 dime(s) 0 nickle(s) 3 penny(ies) Want to calculate another amount? (y/n): I want to not dis...
[ "You could add an if-statement to check whether the coin's value is zero. If so, then don't print it.\nif quarters != 0:\n print(quarters, \"quarter(s)\")\nif dimes != 0:\n print(dimes, \"dime(s)\")\nif nickels != 0:\n print(nickels, \"nickle(s)\")\nif pennies != 0:\n print(pennies, \"penny(ies)\")\npri...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074307120_python.txt
Q: find x and y with the help of third number Suppose that I have three binary numbers, we must Or the first number(x) and the second number(y) together and make the third number(z). I have the third number, I also have some bits of the first and second number, now I need to get the number of possible states I can ma...
find x and y with the help of third number
Suppose that I have three binary numbers, we must Or the first number(x) and the second number(y) together and make the third number(z). I have the third number, I also have some bits of the first and second number, now I need to get the number of possible states I can make for the first and second numbers with the low...
[ "What you have is essentially a product where at each position there are between 1 and 3 possibilities for the x and y bits in that position. You can exploit this by using itertools.product. First construct, for each position, a list of the possibilities for that position, and then form their product.\nIn the follo...
[ 0 ]
[]
[]
[ "binary", "python" ]
stackoverflow_0074302600_binary_python.txt
Q: How to scrape tags inside li tag using python selinum I use selinum to scrape data from this website: https://www.sciencedirect.com/search?qs=physics. I want to select a specific tag inside tag. This is the structure of HTML. HTML structure A: Do not post code as an image. Please also read How to create a Minim...
How to scrape tags inside li tag using python selinum
I use selinum to scrape data from this website: https://www.sciencedirect.com/search?qs=physics. I want to select a specific tag inside tag. This is the structure of HTML. HTML structure
[ "Do not post code as an image. Please also read How to create a Minimal, Reproducible Example.\nSince I don't have the complete source code, I can only guess. You have to use an appropriate find strategy like CSS_SELECTOR or XPATH. Check out the documentation.\nHere is an example by using CSS_SELECTOR:\nelement = d...
[ 0 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074305895_python_selenium_web_scraping.txt
Q: Switching python interpreters for Heroku web app The problem For context: I have deployed an app with Heroku I have Python 3.9.2 running locally in VS Code vs Python 3.10.8 running on a Heroku machine I am currently encountering the problems as mentioned on this thread. I have found the solution to my problem se...
Switching python interpreters for Heroku web app
The problem For context: I have deployed an app with Heroku I have Python 3.9.2 running locally in VS Code vs Python 3.10.8 running on a Heroku machine I am currently encountering the problems as mentioned on this thread. I have found the solution to my problem seems to be switching python interpreters and copying my...
[ "The documentation for selecting a runtime says:\n\nTo specify a Python runtime, add a runtime.txt file to your app's root directory that declares the exact version number to use:\n$ cat runtime.txt\npython-3.10.8\n\n\nThe cat runtime part of that is a command that you can run on many systems (Linux, macOS, etc.) t...
[ 0 ]
[]
[]
[ "azure_speech", "heroku", "python" ]
stackoverflow_0074307007_azure_speech_heroku_python.txt
Q: Determine %Variance between two dataframes I have 2 data frames, for example: df1: REF Date Value 0 REF1 01/09/2022 00:00 15985.50 1 REF1 01/09/2022 00:00 15968.00 2 REF1 01/09/2022 00:00 15991.00 3 REF2 01/09/20...
Determine %Variance between two dataframes
I have 2 data frames, for example: df1: REF Date Value 0 REF1 01/09/2022 00:00 15985.50 1 REF1 01/09/2022 00:00 15968.00 2 REF1 01/09/2022 00:00 15991.00 3 REF2 01/09/2022 00:00 15908.50 4 REF2 01/09...
[ "Notice that you want to do something to groups of rows, where each group is a single REF*. This should tell you df.groupby is something you might be able to use.\ngrps1 = df1.groupby(\"REF\")\ngrps2 = df2.groupby(\"REF\")\n\nNext, you want the sum of each group. Conveniently, .groupby returns a GroupBy object, whi...
[ 0 ]
[]
[]
[ "compare", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074307061_compare_dataframe_group_by_pandas_python.txt
Q: How to save/export the emotions detected by a model in a dataframe? I have the following code and i want to know if there is a way to save in a dataframe or xlsx every time the program register a emotion?, and if there is a form how should i do it?. Here is the code: import cv2 import mediapipe as mp import math c...
How to save/export the emotions detected by a model in a dataframe?
I have the following code and i want to know if there is a way to save in a dataframe or xlsx every time the program register a emotion?, and if there is a form how should i do it?. Here is the code: import cv2 import mediapipe as mp import math cap = cv2.VideoCapture(0) cap.set(3,1280) cap.set(4,720) mpDibujo = mp.sol...
[ "You can create a function that would print to a file object.\nwith open('out.txt', 'w') as f:\nprint('output', output, file=f) # Python 3.x\nprint >> f, 'output', output # Python 2.x\n\nthere is also a standard library that can do this for you in python 3.4+\nfrom contextlib import redirect_stdout\n\nwith ope...
[ 0 ]
[]
[]
[ "dataframe", "face_detection", "face_recognition", "opencv", "python" ]
stackoverflow_0074307129_dataframe_face_detection_face_recognition_opencv_python.txt
Q: Matplotlib scatterplot, color as function of element in array I'm trying to plot data with different colors depending on their classification. The data is in an nx3 array, with the first column the x position, the second column the y position, and the third column an integer defining their categorical value. I can...
Matplotlib scatterplot, color as function of element in array
I'm trying to plot data with different colors depending on their classification. The data is in an nx3 array, with the first column the x position, the second column the y position, and the third column an integer defining their categorical value. I can do this by running a for loop over the entire array and plotting e...
[ "Without seeing your array it's hard to know exactly what your data look like (my answer doesn't have a %3, but that's easy enough to insert depending on what data[:,2] looks like). This has a for loop, but only loops 3 times so will be fast.\nfor ind,col in enumerate(colors):\n plt.scatter(data[:,0][data[:,2]==...
[ 0, 0 ]
[]
[]
[ "matplotlib", "python", "scatter_plot" ]
stackoverflow_0074306885_matplotlib_python_scatter_plot.txt
Q: Is there a better/faster way to find unique value count for a data frame than df.nunique()? (Python pandas) I noticed that df.nunique() roughly scales linearly with data size. I am wondering if there is a solution that would be better as data size increases? Here's an example, let me know if you can come up with a...
Is there a better/faster way to find unique value count for a data frame than df.nunique()? (Python pandas)
I noticed that df.nunique() roughly scales linearly with data size. I am wondering if there is a solution that would be better as data size increases? Here's an example, let me know if you can come up with a faster approach! import numpy as np import pandas as pd def createList(r1, r2): """ creates a list of value...
[ "In this particular case, I found this to be faster:\nsample_df.apply(lambda S: len(np.unique(S.values)))\n\nAnd it will be faster, e.g.:\nIn [16]: sample_df = pd.DataFrame(\n ...: data = {\n ...: 'a' : np.arange(1, 50_000_000+1),\n ...: 'b' : np.arange(1, 50_000_000+1),\n ...: ...
[ 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python", "python_3.x" ]
stackoverflow_0074306975_dataframe_numpy_pandas_python_python_3.x.txt
Q: Terminate scipy minimize as soon as function values is below threshold I have a function of some parameters that will return a probability. How can I set scipy's minimize to terminate as soon as finds some parameters that will return a probability below a certain threshold (even if it is a "large" probability lik...
Terminate scipy minimize as soon as function values is below threshold
I have a function of some parameters that will return a probability. How can I set scipy's minimize to terminate as soon as finds some parameters that will return a probability below a certain threshold (even if it is a "large" probability like 0.1 or so)? Thanks a lot!
[ "You can use the callback argument to minimize. This is a function that is called at each iteration of the minimization. You can use this to check the value of the function and terminate the minimization if it is below the threshold.\n", "It's a bit messy but I would use something like the following to wrap the o...
[ 0, 0, 0 ]
[]
[]
[ "python", "scipy", "scipy_optimize_minimize" ]
stackoverflow_0074154972_python_scipy_scipy_optimize_minimize.txt
Q: Scrapy - 400 Response with Headers Here's an example link I'm trying to scrape: https://www.lowes.com/pd/ZLINE-KITCHEN-BATH-Professional-7-Burners-4-cu-ft-2-cu-ft-Double-Oven-Convection-Dual-Fuel-Range-Stainless-Steel-Common-48-in-Actual-48-in/1000514227 My scraper was working fine till today so I'm guessing Lowe'...
Scrapy - 400 Response with Headers
Here's an example link I'm trying to scrape: https://www.lowes.com/pd/ZLINE-KITCHEN-BATH-Professional-7-Burners-4-cu-ft-2-cu-ft-Double-Oven-Convection-Dual-Fuel-Range-Stainless-Steel-Common-48-in-Actual-48-in/1000514227 My scraper was working fine till today so I'm guessing Lowe's added more protection against bots :( ...
[ "From what I can see about the network connection, the issue is related to the their CDN (Akamai) which is blocking the access.\nI was able to access your link and see the product from Microsoft Edge (version 107). In my request the user agent is:\nMozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTM...
[ 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0074187876_python_scrapy.txt
Q: Using MinMaxScaler on arrays and getting scaling parameters for later use: missing values I have this issue when trying to use sklearn.preprocessing.MinMaxScaler on a large array and obtaining the scaling parameters to do "redo" the normalization after handling the array for a while. The issue I have is that after...
Using MinMaxScaler on arrays and getting scaling parameters for later use: missing values
I have this issue when trying to use sklearn.preprocessing.MinMaxScaler on a large array and obtaining the scaling parameters to do "redo" the normalization after handling the array for a while. The issue I have is that after doing my MinMaxScaler.fit_transform(data), where data is a numpy array with shape (8,412719), ...
[ "I build my X dataframe and y target then scaler the X dataframe\ndf3.dropna(inplace=True)\nX_Columns=[column for column in df3.columns if not column in[\"Target\",\"DateTime\",\"Date\",\"CO2Intensity\",\"ActualWindProduction\",\"ORKWindspeed\",\"ForecastWindProduction\"]]\n#print(X_Columns)\nX=df3[X_Columns]\n#pri...
[ 0 ]
[]
[]
[ "minmax", "numpy_ndarray", "python", "scikit_learn" ]
stackoverflow_0074304617_minmax_numpy_ndarray_python_scikit_learn.txt
Q: Why isn't my Gensim fastText model continuing to train on a new corpus? I am trying to continue training a fastText model with Gensim, using my own corpus of text. I've followed along with the documentation here: https://radimrehurek.com/gensim/models/fasttext.html And I have written the following code: First, cre...
Why isn't my Gensim fastText model continuing to train on a new corpus?
I am trying to continue training a fastText model with Gensim, using my own corpus of text. I've followed along with the documentation here: https://radimrehurek.com/gensim/models/fasttext.html And I have written the following code: First, create a small corpus: corpus = [ "The brown dog jumps over the kangaroo", ...
[ "Models generally have a min_count value of at least 5 - meaning words with fewer occurrences are ignored. Discarding the rarest words typically improves model quality, as both:\n\nsuch rare words have too few usage examples to get a good vector themselves; and further…\nby pushing surrounding words outside each ot...
[ 1 ]
[]
[]
[ "fasttext", "gensim", "nlp", "python" ]
stackoverflow_0074307142_fasttext_gensim_nlp_python.txt
Q: Python: Why do functools.partial functions not become bound methods when set as class attributes? I was reading about how functions become bound methods when being set as class atrributes. I then observed that this is not the case for functions that are wrapped by functools.partial. What is the explanation for thi...
Python: Why do functools.partial functions not become bound methods when set as class attributes?
I was reading about how functions become bound methods when being set as class atrributes. I then observed that this is not the case for functions that are wrapped by functools.partial. What is the explanation for this? Simple example: from functools import partial def func1(): print("foo") func1_partial = partia...
[ "The trick that allows functions to become bound methods is the __get__ magic method.\nTo very briefly summarize that page, when you access a field on an instance, say foo.bar, Python first checks whether bar exists in foo's __dict__ (or __slots__, if it has one). If it does, we return it, no harm done. If not, the...
[ 5, 4 ]
[]
[]
[ "class", "functools", "python", "python_3.x" ]
stackoverflow_0074307236_class_functools_python_python_3.x.txt
Q: Problems with concatenating rows using pd.groupby().agg() For example, let's say that I have the dataframe: NAME = ['BOB', 'BOB', 'BOB', 'SUE', 'SUE', 'MARY', 'JOHN', 'JOHN', 'MARK', 'MARK', 'MARK', 'MARK'] STATE = ['CA','CA','CA','DC','DC','PA','GA','GA','NY','NY','NY','NY'] MAJOR = ['MARKETING','BUSINESS...
Problems with concatenating rows using pd.groupby().agg()
For example, let's say that I have the dataframe: NAME = ['BOB', 'BOB', 'BOB', 'SUE', 'SUE', 'MARY', 'JOHN', 'JOHN', 'MARK', 'MARK', 'MARK', 'MARK'] STATE = ['CA','CA','CA','DC','DC','PA','GA','GA','NY','NY','NY','NY'] MAJOR = ['MARKETING','BUSINESS ADM',np.nan,'ECONOMICS','MATH','PSYCHOLOGY','HISTORY','BUSINES...
[ "It is because your np.nan cannot be converted to str, so it is dropped automatically by pandas. You need to convert its type to str first:\ndf.groupby(['NAME', 'STATE']).agg(lambda x: ','.join(x.astype(str)))\n\nTo drop na and keep NAME and STATE as columns:\ndf.groupby(['NAME', 'STATE']).agg(lambda x: ','.join(x....
[ 0 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074307083_group_by_pandas_python.txt
Q: python ghostscript: RuntimeError: Can not find Ghostscript library (libgs) When trying to run hello-world example import sys import ghostscript args = [ "ps2pdf", # actual value doesn't matter "-dNOPAUSE", "-dBATCH", "-dSAFER", "-sDEVICE=pdfwrite", "-sOutputFile=" + sys.argv[1], "-c", ".setpdf...
python ghostscript: RuntimeError: Can not find Ghostscript library (libgs)
When trying to run hello-world example import sys import ghostscript args = [ "ps2pdf", # actual value doesn't matter "-dNOPAUSE", "-dBATCH", "-dSAFER", "-sDEVICE=pdfwrite", "-sOutputFile=" + sys.argv[1], "-c", ".setpdfwrite", "-f", sys.argv[2] ] ghostscript.Ghostscript(*args) getting er...
[ "For newer user who are using M1 mac, ghostscript might show a missing libgs file error and the file would be unavailable at usr/local/lib \nThe issue can be resolved by following these steps, in the same order:\n\nbrew install ghostscript\nconda install ghostscript, which installs the arm_64 based library from con...
[ 7, 2, 1, 1, 0, 0 ]
[]
[]
[ "ghostscript", "macos", "python" ]
stackoverflow_0006848903_ghostscript_macos_python.txt
Q: Log to Cloud Logging with correct severity from Cloud Run Job and package used in the job What we are trying: We are trying to Run a Cloud Run Job that does some computation and also uses one our custom package to do the computation. The cloud run job is using google-cloud-logging and python's default logging pac...
Log to Cloud Logging with correct severity from Cloud Run Job and package used in the job
What we are trying: We are trying to Run a Cloud Run Job that does some computation and also uses one our custom package to do the computation. The cloud run job is using google-cloud-logging and python's default logging package as described here. The custom python package also logs its data (only logger is defined as...
[ "Cloud Functions get your code, wrap it in a webserver, build a container and deploy it.\nWith Cloud Run, you only build and deploy the container.\nThat means, Cloud Functions webserver wrapper do something more that you do: it initialize correctly the logger in Python.\nHave a look to that doc page, you should sol...
[ 0 ]
[]
[]
[ "google_cloud_functions", "google_cloud_logging", "google_cloud_platform", "google_cloud_run", "python" ]
stackoverflow_0074302649_google_cloud_functions_google_cloud_logging_google_cloud_platform_google_cloud_run_python.txt
Q: How a create a random string combination of postive, Negative, floats, Upper case, Lower case elements I'm new to python seeking your help. I would like to create a string combination of postive, Negative, floats, Upper case, Lower case elements Example: Like random combination. As-1jP0.7M -->output Explanation A...
How a create a random string combination of postive, Negative, floats, Upper case, Lower case elements
I'm new to python seeking your help. I would like to create a string combination of postive, Negative, floats, Upper case, Lower case elements Example: Like random combination. As-1jP0.7M -->output Explanation A - caps A s- small S -1 - Negative 1 j- small j 0.7 - float 0.7 M- caps M My ranges Caps - A - Z small- ...
[ "Try this:\nimport random, string\nx = ''.join(random.choice(list(string.ascii_uppercase) + \n list(string.ascii_lowercase) + \n ['0']+[ch+dig for dig in string.digits[1:] for ch in ['', '-', '0.'] ]) \n for _ in range(10))\nprint(x)\n\nRandom output:0.3z...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074307186_python_python_3.x.txt
Q: python-pptx having a problem with fit_text() I'm trying to call fit_text() on a textbox, but I keep getting this error: 'NoneType' object is not iterable from this line python3.6/site-packages/pptx/text/layout.py in _wrap_lines, line 112 which is text, remainder = self._break_line(line_source, point_size) This...
python-pptx having a problem with fit_text()
I'm trying to call fit_text() on a textbox, but I keep getting this error: 'NoneType' object is not iterable from this line python3.6/site-packages/pptx/text/layout.py in _wrap_lines, line 112 which is text, remainder = self._break_line(line_source, point_size) This is my code which produces the error. I have no id...
[ "I received the same error recently. I'm not sure I have the best solutions but what I found is that the string(data) you are trying to save in your text frame is too big. I'm not sure if you are setting the bound on the text frame but you can either make it bigger by doing something like:(vary the size of obj_wi...
[ 2, 1, 0 ]
[]
[]
[ "python", "python_pptx" ]
stackoverflow_0053621750_python_python_pptx.txt
Q: How to access an item within a list within a key of a dictionary? In the below dictionary, how would I print the highest overall score? scores = { 'Monday': [21, 23, 24, 19], 'Tuesday': [16, 15, 12, 19], 'Wednesday': [23, 22, 23], 'Thursday': [18, 20, 26, 24], 'Friday': [17, 22], 'Saturday'...
How to access an item within a list within a key of a dictionary?
In the below dictionary, how would I print the highest overall score? scores = { 'Monday': [21, 23, 24, 19], 'Tuesday': [16, 15, 12, 19], 'Wednesday': [23, 22, 23], 'Thursday': [18, 20, 26, 24], 'Friday': [17, 22], 'Saturday': [22, 24], 'Sunday': [21, 21, 28, 25] } I am very new to python a...
[ "You can use max built-in passing the dictionary items, and a key function which will calculate the sum of the values in the list:\n>>> max(scores.items(), key=lambda x:sum(x[1]))\n('Sunday', [21, 21, 28, 25])\n\nOr if you need the maximum score instead of the list of the score values:\n>>> max(map(lambda x:(x[0], ...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074307132_dictionary_list_python.txt
Q: How to add new column to an existing csv file and find age from DOB of that csv file? My CSV file has three columns, the first column names, the second column is DOB(YYYYMM-DD) the third column is salary looks like this kind of Name,DOB,Salary Sam,2000-01-05,23000 Tyson,1989-09-11,29000 Lara,2002-11-19,19000 Brian...
How to add new column to an existing csv file and find age from DOB of that csv file?
My CSV file has three columns, the first column names, the second column is DOB(YYYYMM-DD) the third column is salary looks like this kind of Name,DOB,Salary Sam,2000-01-05,23000 Tyson,1989-09-11,29000 Lara,2002-11-19,19000 Brian,1990-04-20,21000 Tessa,2000-08-17,15000 Problem statement- Read the file and display the ...
[ "It is probably easiest to use pandas\nimport pandas as pd\nimport datetime\n\n\ndf = pd.read_csv('some/file/path/file_name.csv') # read your csv using the file's path\ndf['DOB'] = pd.to_datetime(df['DOB']) # convert date to datetime\ndf['Age'] = (datetime.datetime.now() - df['DOB']).dt.days // 365 # calculate t...
[ 1, 0 ]
[]
[]
[ "csv", "opencsv", "python" ]
stackoverflow_0074306695_csv_opencsv_python.txt
Q: ValueError: empty range for randrange() (0, 0, 0) I try to export random proxy from a webpage with this script: def randProxy(): url = 'https://free-proxy-list.net/anonymous-proxy.html' response = requests.get(url) parser = fromstring(response.text) proxies = [] for i in parser.xpath('//tbody/t...
ValueError: empty range for randrange() (0, 0, 0)
I try to export random proxy from a webpage with this script: def randProxy(): url = 'https://free-proxy-list.net/anonymous-proxy.html' response = requests.get(url) parser = fromstring(response.text) proxies = [] for i in parser.xpath('//tbody/tr')[:20]: if i.xpath('.//td[7][contains(text(),...
[ "That happens when the second argument is a negative. Look here.\nimport random\nprint(random.randint(0,-1))\n\noutput\nTraceback (most recent call last):\n File \"<string>\", line 2, in <module>\nFile \"/usr/lib/python3.8/random.py\", line 248, in randint\n return self.randrange(a, b+1)\n File \"/usr/lib/pyth...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0067186692_python.txt
Q: is it possible to log an ROC Curve onto a CSV file I have generated an ROC curve using sklearn on python and was wondering if there was anyway to log the results onto a CSV file? I was able to log model training data to CSV using the following CSV logger from keras csv_logger = CSVLogger('training.log') model.fit(...
is it possible to log an ROC Curve onto a CSV file
I have generated an ROC curve using sklearn on python and was wondering if there was anyway to log the results onto a CSV file? I was able to log model training data to CSV using the following CSV logger from keras csv_logger = CSVLogger('training.log') model.fit(X_train, Y_train, callbacks=[csv_logger]) If there was ...
[ "Do you want it as a callback or post-fit is fine?\npost:\nimport pandas as pd\nfrom sklearn import metrics\n...\nfpr, tpr, thresholds = metrics.roc_curve(...)\npd.DataFrame([fpr, tpr, thresholds]).to_csv(\"ROC.csv\")\n...\nroc = pd.read_csv(\"ROC.csv\")\n\n" ]
[ 0 ]
[]
[]
[ "csv", "keras", "machine_learning", "python", "roc" ]
stackoverflow_0074307362_csv_keras_machine_learning_python_roc.txt
Q: Import pyaudio doesn't work - Symbol not found: _PaMacCore_SetupChannelMap on mac (Big Sur M1 Apple Silicon) I am trying to install pyaudio on my new Macbook Air with the M1 chip (Big Sur). At first I couldn't get past the famous src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found error. I reme...
Import pyaudio doesn't work - Symbol not found: _PaMacCore_SetupChannelMap on mac (Big Sur M1 Apple Silicon)
I am trying to install pyaudio on my new Macbook Air with the M1 chip (Big Sur). At first I couldn't get past the famous src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found error. I remember I had this issue on my other laptop as well, but then a simple brew install portaudio fixed it. Well, not thi...
[ "Don't know if you still need the solution, but here was mine after hours of googling (I also owned a Mac m1):\nI could not install PyAudio at first and encountered problems even after I successfully installed PyAudio. I used python 3.9 installed with brew for the process.\n\nuninstall previous version of portaudio...
[ 9, 1, 0, 0 ]
[]
[]
[ "apple_m1", "apple_silicon", "portaudio", "pyaudio", "python" ]
stackoverflow_0065709212_apple_m1_apple_silicon_portaudio_pyaudio_python.txt
Q: Is there a way to make flake8 ignore a violation in a specific circumstance? I'm using the pandas package in Python and I'm working in visual studio code. I regularly use queries on dataframes, which can reference variable names in the external scope like this import pandas as pd df = pd.DataFrame({'a': [1, 2], 'b...
Is there a way to make flake8 ignore a violation in a specific circumstance?
I'm using the pandas package in Python and I'm working in visual studio code. I regularly use queries on dataframes, which can reference variable names in the external scope like this import pandas as pd df = pd.DataFrame({'a': [1, 2], 'b': [10, 20]}) query_value = 20 print(df.query('b == @query_value')) which would p...
[ "There's a suggestion on the flake8 issue tracker of a way to do this that doesn't cause a F841 violation.\nquery_value = 20\nprint(df.query('b == @q', local_dict={'q': query_value}))\n\nIt's a bit more verbose, though.\n" ]
[ 1 ]
[]
[]
[ "flake8", "pandas", "python", "visual_studio_code" ]
stackoverflow_0074307474_flake8_pandas_python_visual_studio_code.txt
Q: face_recognition python operands could not be broadcast together with shapes fellows Googled before decided to ask by myself. Trying to recieve true or falls, but unfortunately recieving an error. Doing as https://www.youtube.com/watch?v=sz25xxF_AVE says My code: ` import cv2 import numpy as np import face_recogni...
face_recognition python operands could not be broadcast together with shapes
fellows Googled before decided to ask by myself. Trying to recieve true or falls, but unfortunately recieving an error. Doing as https://www.youtube.com/watch?v=sz25xxF_AVE says My code: ` import cv2 import numpy as np import face_recognition import os path = 'ImageAttendance' # создаем список файлов myList = os.listd...
[ "Found solutions by watching array i've created. As a original image take bright images guys.\nThe issue is when we encode images with improper light on your face, the method face_encoding returns an empty list and when you compare this with that new image's encoding this error occurs... this might even occur in th...
[ 0 ]
[]
[]
[ "face_recognition", "opencv", "python", "typeerror" ]
stackoverflow_0074295622_face_recognition_opencv_python_typeerror.txt