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: How do I open an .eml file from object using Python? I am writing a Lambda function to read an email from a .eml file when the .eml file is stored in the S3 Bucket. import email . . . # get the .eml file object from S3 bucket file_content = s3_client.get_object(Bucket=S3_BUCKET, ...
How do I open an .eml file from object using Python?
I am writing a Lambda function to read an email from a .eml file when the .eml file is stored in the S3 Bucket. import email . . . # get the .eml file object from S3 bucket file_content = s3_client.get_object(Bucket=S3_BUCKET, Key=email_key) # get .eml file contents email_content ...
[ "You can use pandas:\npd.read_csv(\n <botocore.response.StreamingBody object at 0x000001D64812BF70>\n)\n\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "aws_lambda", "email", "python", "python_3.x" ]
stackoverflow_0073479504_amazon_s3_aws_lambda_email_python_python_3.x.txt
Q: How to sum second element in each tuple in string, if second value is string? I try to sum per fruit sort the total. So I have it: listfruit= [('Watermeloenen', '123,20'), ('Watermeloenen', '2.772,00'), ('Watermeloenen', '46,20'), ('Watermeloenen', '577,50'), ('Watermeloenen', '69,30'), ('Appels', '3.488,16'), ('S...
How to sum second element in each tuple in string, if second value is string?
I try to sum per fruit sort the total. So I have it: listfruit= [('Watermeloenen', '123,20'), ('Watermeloenen', '2.772,00'), ('Watermeloenen', '46,20'), ('Watermeloenen', '577,50'), ('Watermeloenen', '69,30'), ('Appels', '3.488,16'), ('Sinaasappels', '137,50'), ('Sinaasappels', '500,00'), ('Sinaasappels', '1.000,00'), ...
[ "Since your numbers are localized with specific separators for thousands and decimals, the proper way to do this is to use the locales module to parse teh numbers. (They could be \"brute-force\" parsed by hardocoding replacements of \".\" for \"\" and \",\" for \".\" - and for begginer programmers sometime it is mo...
[ 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074447128_python.txt
Q: How do i convert a las file into a txt (or csv) file in python? As the title suggested, how can i convert a .las file in a .txt or .csv file? Does laspy library do that? Someone suggested to use pdal (.LAS into a .CSV file using python) but it is not clear how to do that A: Solved in this way: inFile = laspy.fil...
How do i convert a las file into a txt (or csv) file in python?
As the title suggested, how can i convert a .las file in a .txt or .csv file? Does laspy library do that? Someone suggested to use pdal (.LAS into a .CSV file using python) but it is not clear how to do that
[ "Solved in this way:\ninFile = laspy.file.File(inputFile, mode='r')\ntest = np.vstack((inFile.x, inFile.y, inFile.z, inFile.raw_classification)).transpose()\n\nwith open(outFolder+\"\\\\test.txt\", mode='w') as f:\nfor i in range(len(test)):\n f.write(\"%f \"%float(test[i][0].item()))\n f.write(\"%f \"%...
[ 0 ]
[]
[]
[ "las", "point_cloud_library", "point_clouds", "python", "txt" ]
stackoverflow_0074446500_las_point_cloud_library_point_clouds_python_txt.txt
Q: WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 127 I'd like to construct my crawler using selenium on my server. Thus I had installed/download required dependencies- such as chromedriver, chromium-browser etc on my Ubuntu17.10 server However, when I run following code: driv...
WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 127
I'd like to construct my crawler using selenium on my server. Thus I had installed/download required dependencies- such as chromedriver, chromium-browser etc on my Ubuntu17.10 server However, when I run following code: driver = webdriver.Chrome() It returns following error: --------------------------------------------...
[ "It seems chromedriver needs some extra libraries. This solved the issue for me:\napt-get install -y libglib2.0-0=2.50.3-2 \\\n libnss3=2:3.26.2-1.1+deb9u1 \\\n libgconf-2-4=3.2.6-4+b1 \\\n libfontconfig1=2.11.0-6.7+b1\n\nI was working on a similar setup using a docker container instead of a server/VM with...
[ 49, 28, 20, 8, 5, 3, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "google_chrome", "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0049323099_google_chrome_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: loop to count how many time the column has a different character I have a dataframe shown below: I would like to count how many time the "code" column has a different character from the Key column group: Ex: in this example the first group has two S but one Q then will count one. The second group it does not have ...
loop to count how many time the column has a different character
I have a dataframe shown below: I would like to count how many time the "code" column has a different character from the Key column group: Ex: in this example the first group has two S but one Q then will count one. The second group it does not have a different char. The third group has three F but one N then will coun...
[ "It appears that you don't want duplicates... I recommend splitting the Key column then drop_duplicates.\ndf = {'Key': ['111*1', '111*2','111*3', '222*1','222*2', '333*1','333*2', '333*3','333*4', '444*1'],\n 'code': ['S', 'S','Q', 'M','M', 'F','F', 'F','N', 'C']}\n \n# Create DataFrame\ndf = pd.DataFrame(d...
[ 1, 1 ]
[]
[]
[ "logic", "loops", "pandas", "python" ]
stackoverflow_0074438148_logic_loops_pandas_python.txt
Q: Django Logging: ValueError: Unable to configure handler 'gunicorn' I configured logging for a new Django project, and here is the code for my settings.py: LOGGING = { "version": 1, # The version number of our log "disable_existing_loggers": False, # django uses some of its own loggers for internal operations. In c...
Django Logging: ValueError: Unable to configure handler 'gunicorn'
I configured logging for a new Django project, and here is the code for my settings.py: LOGGING = { "version": 1, # The version number of our log "disable_existing_loggers": False, # django uses some of its own loggers for internal operations. In case you want to disable them just replace the False above with true. # A...
[ "You need to define a Formatter available under the key verbose, for example like this:\n\"formatters\": {\n \"verbose\": {\n \"format\": \"%(levelname)-8s - %(message)s\"\n }\n}\n\nIt needs to be at the same level as handlers and loggers in your configuration.\n" ]
[ 0 ]
[]
[]
[ "django", "gunicorn", "logging", "python" ]
stackoverflow_0074447339_django_gunicorn_logging_python.txt
Q: Python - Create output files from an input file that has the same name as it for all file in a directory Good morning. I would need a script that reads information in one file and reports it in an order I indicated in another text file. With simple input/output statements I managed to do it but the problem is that...
Python - Create output files from an input file that has the same name as it for all file in a directory
Good morning. I would need a script that reads information in one file and reports it in an order I indicated in another text file. With simple input/output statements I managed to do it but the problem is that I need this to be done for all the files in the directory and that each output produced has the same name as ...
[ "import os\n\n# Constants for program\n# These folders must exist before runtime\nnew_text_file_path = \"C:\\\\path\\\\to\\\\new_text_files\"\nxyz_files_path = \"C:\\\\path\\\\to\\\\xyz_files\"\n\n# Get the list of \".xyz\" files in the \"xyz_files_path\" directory\nxyz_files = [file for file in os.listdir(xyz_file...
[ 0 ]
[]
[]
[ "data_science", "io", "iteration", "python", "spyder" ]
stackoverflow_0074447277_data_science_io_iteration_python_spyder.txt
Q: AttributeError: module 'customtkinter' has no attribute 'CTkFont', i imported customtkinter? Does someone know, why I get this error? I imported customtkinter the correct way and already redownloaded it, do i have to import it seperately? I import customtkinter and get this error: AttributeError: module 'customtki...
AttributeError: module 'customtkinter' has no attribute 'CTkFont', i imported customtkinter?
Does someone know, why I get this error? I imported customtkinter the correct way and already redownloaded it, do i have to import it seperately? I import customtkinter and get this error: AttributeError: module 'customtkinter' has no attribute 'CTkFont' when executing this piece of code: label1 = customtkinter.CTkLabe...
[ "I think I found the problem...it says at the top of the utility wiki page: \"Widget will be available with version 5.0.0!\" - the current version is 4.6.3\n" ]
[ 2 ]
[]
[]
[ "customtkinter", "fonts", "python" ]
stackoverflow_0074447475_customtkinter_fonts_python.txt
Q: Printing issues when moving from Python 2 to 3 with code I have a code that I am trying to convert but it's written in Python 2 and I would like to print this code in Python 3. However, it's not able to print in matrix format. I am getting output in an unrecognizable table format. The code is following: for n in ...
Printing issues when moving from Python 2 to 3 with code
I have a code that I am trying to convert but it's written in Python 2 and I would like to print this code in Python 3. However, it's not able to print in matrix format. I am getting output in an unrecognizable table format. The code is following: for n in cols: print('/t',n), print cost = 0 for g in sorted(costs...
[ "Your print calls must always be enclosed in parenthesis like this:\nprint(\"\\t\", n)\n\n", "Another thing - whenever you see the Python 2 print command with\na comma at the end, such as\nprint y, \n\nyou need to change that line to:\nprint(y,end=\"\")\n\nThis will print the variable without a new line.\n", "...
[ 0, 0, 0 ]
[]
[]
[ "python", "python_3.x", "tabs" ]
stackoverflow_0074447314_python_python_3.x_tabs.txt
Q: python program won't handle systemd KillSignal at reboot I have a set of LEDs that I start and turn into a specific colour when the machine starts up and during other events. At power-off/reboot I want the LEDs to reset to the default colour. To achieve this I start a systemd service that starts up the LED code an...
python program won't handle systemd KillSignal at reboot
I have a set of LEDs that I start and turn into a specific colour when the machine starts up and during other events. At power-off/reboot I want the LEDs to reset to the default colour. To achieve this I start a systemd service that starts up the LED code and have a handle for the signal in the python code. Unfortunate...
[ "The callback executed by signal expects two arguments. Your implementation does not take any. The right prototype is:\ndef system_exit(signum, frame):\n stop_event.set()\n\nThis might have thrown a TypeError upon signal receive and execution. As you forward your logs output to syslog, then the journalctl should...
[ 1 ]
[]
[]
[ "linux", "python", "service", "systemd", "ubuntu" ]
stackoverflow_0074447263_linux_python_service_systemd_ubuntu.txt
Q: Is it possible to do a binary search on an unordered list Is it possible to do a binary search on an unordered list, and if so, what would the code look like? Thank you very much for the help. A: Read this Binary Search. In the second line it says "...is a search algorithm that finds the position of a target va...
Is it possible to do a binary search on an unordered list
Is it possible to do a binary search on an unordered list, and if so, what would the code look like? Thank you very much for the help.
[ "Read this Binary Search.\nIn the second line it says\n\n\"...is a search algorithm that finds the position of a target value within a sorted array.\"\n\nIf we have the following list: lst = [1, 3, 4, 6, 2, 9, 8, 5, 7], and we want to find where 6 is.\nWe would look at the element in the middle of the list. In this...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074447466_python.txt
Q: Skip for loop if file exists I am processing some files from a folder that is being frequently updated. I need to add a piece of code that would check whether the file is already in a folder, and if not then go ahead with processing. If yes, then just skip and go for another one. So far I have this: files_processe...
Skip for loop if file exists
I am processing some files from a folder that is being frequently updated. I need to add a piece of code that would check whether the file is already in a folder, and if not then go ahead with processing. If yes, then just skip and go for another one. So far I have this: files_processed = os.listdir(path) # ['AZ_saturd...
[ "You can use the os library, like so:\nimport os\n\nos.path.exists(\"file.txt\")\n\nOr like this:\nimport os.path\n\nif os.path.isfile('filename.txt'):\n print (\"File exists\")\nelse:\n print (\"File does not exist\")\n\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074447641_python.txt
Q: Python PySimpleGUI & time.sleep(): how to wait for condition to be met without freezing GUI? I am learning about making a GUI in Python, with the goal of eventually using a GUI to operate some devices in my laboratory. I am having a problem with telling the GUI to wait for a condition to be met. I tried first to ...
Python PySimpleGUI & time.sleep(): how to wait for condition to be met without freezing GUI?
I am learning about making a GUI in Python, with the goal of eventually using a GUI to operate some devices in my laboratory. I am having a problem with telling the GUI to wait for a condition to be met. I tried first to use a while loop like this while i < some_limit: time.sleep(1) print(i) i+=1 #in the...
[ "Main thread blocked at c_thread.join(), so GUI show no response.\nUsing method window.write_event_value to generate an event to main thread to update GUI.\nimport time\nimport threading\nimport PySimpleGUI as sg\n\ndef side_thread(window, limit):\n i=0\n while i<=limit:\n time.sleep(1)\n print(...
[ 0 ]
[]
[]
[ "pysimplegui", "python", "python_multithreading", "sleep" ]
stackoverflow_0074447308_pysimplegui_python_python_multithreading_sleep.txt
Q: I want to put different command in tkinter Button (made by for()) from tkinter import * window2 = Tk() Var = ' ' store = ['a', 'b', 'c', 'd'] count = 3 for i in store: if i != None: chs_store = Button(window2, text = i).grid(row = count , column = 4) count += 1 I made buttons and placed t...
I want to put different command in tkinter Button (made by for())
from tkinter import * window2 = Tk() Var = ' ' store = ['a', 'b', 'c', 'd'] count = 3 for i in store: if i != None: chs_store = Button(window2, text = i).grid(row = count , column = 4) count += 1 I made buttons and placed them on the frame like this. In order to place buttons as same as the or...
[ "Put each command function in a list similar to what you're doing with store\n# define the functions you want your buttons to call up here, e.g.:\ndef func_a():\n print('hello!')\n\n# note: no parentheses () since you're not calling these functions here!\ncommands = [func_a, func_b, func_c, func_d]\nstore = ['a'...
[ 0, 0, 0 ]
[]
[]
[ "button", "command", "python", "tkinter" ]
stackoverflow_0074445564_button_command_python_tkinter.txt
Q: Extrapolating time series data into the future by repeating/scaling existing values I have hourly data on electricity consumption for a specific day. I would like to use this data to "predict" the hourly electricity consumption for the following days. The value for the following day should be the value from the sa...
Extrapolating time series data into the future by repeating/scaling existing values
I have hourly data on electricity consumption for a specific day. I would like to use this data to "predict" the hourly electricity consumption for the following days. The value for the following day should be the value from the same hour the day before, multiplied by a scaling factor f (e.g. 2). The dataframe df that ...
[ "To create the data you need to iterate one day at a time.\nAssuming that the original data has at least a full day of data then you can do:\nimport pandas as pd\nimport itertools\nimport datetime as dt\n\nstart = \"2021-01-01 00:00\"\nend = \"2021-01-01 23:00\"\nfreq = \"H\"\n\ndf = pd.DataFrame(\n {\"load_kWh\...
[ 0, 0 ]
[]
[]
[ "datetimeindex", "extrapolation", "pandas", "python", "time_series" ]
stackoverflow_0074433008_datetimeindex_extrapolation_pandas_python_time_series.txt
Q: Execute @api.onchange only once in Odoo I'm getting a datetime from a .js file. This datetime have a random time, and I want to modify it to be 14:00:00 at first time. I have to be able to modify this time later. I'm doing it with an @api.onchange, but then I can't modify the hour. It always return to 14:00:00. Th...
Execute @api.onchange only once in Odoo
I'm getting a datetime from a .js file. This datetime have a random time, and I want to modify it to be 14:00:00 at first time. I have to be able to modify this time later. I'm doing it with an @api.onchange, but then I can't modify the hour. It always return to 14:00:00. The best way to do it I think is to execute @ap...
[ "In which moment you extract the datetime from the javascript resource?\nAnd how?\nAnyway, @api.onchange decorator can not be blind to run only once.\nWithout many informations, all i can suggest is to use 2 different fields, one where you're going to store your parsed datetime, and one where you're going to apply ...
[ 0 ]
[]
[]
[ "odoo", "odoo_15", "python" ]
stackoverflow_0074447072_odoo_odoo_15_python.txt
Q: How to plot only selected key value pair of a dictionary in python I need to plot seperate line plots for each of the key value pairs. The key value pairs are the following. pd_plot = {'MinMaxScalerLogisticRegression': [0,0,1,6,150,200], 'StandardScalerHoeffdingTreeClassifier': [2,0,50,100], 'MaxAbsScalerKNNClassi...
How to plot only selected key value pair of a dictionary in python
I need to plot seperate line plots for each of the key value pairs. The key value pairs are the following. pd_plot = {'MinMaxScalerLogisticRegression': [0,0,1,6,150,200], 'StandardScalerHoeffdingTreeClassifier': [2,0,50,100], 'MaxAbsScalerKNNClassifier': [23,45,56,0,0], 'MinMaxScalerGaussianNB': [43,56,76,87,35], 'MinM...
[ "I'm not too sure what you are trying to plot or what kind of plot you want, but you can iterate over your dictionary, and plot the values. I added the keys of your dictionary as labels for the lines.\nimport matplotlib.pyplot as plt\n\npd_plot = {'MinMaxScalerLogisticRegression': [0,0,1,6,150,200], 'StandardScaler...
[ 0 ]
[]
[]
[ "dictionary", "key_value", "line_plot", "matplotlib", "python" ]
stackoverflow_0074447536_dictionary_key_value_line_plot_matplotlib_python.txt
Q: add values to multiple columns of a pandas dataframe based on a condition I have a dataframe that look like: corpus zero_level_name time labels A B C 0 ff f 1 1 1 gg g G 2 hh h H 1 1 1 3 ii i ...
add values to multiple columns of a pandas dataframe based on a condition
I have a dataframe that look like: corpus zero_level_name time labels A B C 0 ff f 1 1 1 gg g G 2 hh h H 1 1 1 3 ii i I 4 jj j J 1 I want to add 0 to ...
[ "Assuming you have either NaNs or empty strings in your DataFrame, you can use:\ndf.update(df.loc[:, 'A':'C'].replace('', 0).fillna(0))\n\nNB. there is no output, the DataFrame is modified in place\nAlso note that changing the values does not change the dtypes. If you need integers, rather run:\ncols = df.loc[:, 'A...
[ 1, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074447695_pandas_python.txt
Q: flask how to get the HTTP_ORIGIN of a request I'd like to make a response with the "Access-Control-Allow-Origin" header been set all by myself, while it's seems messing up to figure out where the "HTTP_ORIGIN" parameter comes with the request is. A: I'm using flask - 0.10.1, and the HTTP_ORIGIN seems to be one o...
flask how to get the HTTP_ORIGIN of a request
I'd like to make a response with the "Access-Control-Allow-Origin" header been set all by myself, while it's seems messing up to figure out where the "HTTP_ORIGIN" parameter comes with the request is.
[ "I'm using flask - 0.10.1, and the HTTP_ORIGIN seems to be one of the attrs of this object\nflask.request.environ\n\nHere is what I got from print flask.request.environ when handling a request:\n{\n \"wsgi.multiprocess\": false,\n \"HTTP_REFERER\": \"http://www.freemerce.com/product/77104116\",\n \"SERVER_SOFTWA...
[ 14, 11, 3, 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0028448991_flask_python.txt
Q: tkinter strange phenomenon with buttons and images I don't know what to say because I am clueless on why this is not working. The first button appears but the image does not the second and third button does not appear. from tkinter import * Master = Tk() Master.geometry("1408x768") Master.configure(background = "...
tkinter strange phenomenon with buttons and images
I don't know what to say because I am clueless on why this is not working. The first button appears but the image does not the second and third button does not appear. from tkinter import * Master = Tk() Master.geometry("1408x768") Master.configure(background = "#000000") # Top Top = Frame(Master) Top.configure(back...
[ "Your primary issue here appears that you are expecting your widget placement to be relative to the root window but in fact they are relative to the frames they are placed in.\nTry this. Change all your buttons X/Y to 20 and see what I mean.\nYou will see all the buttons show up in the top left corner of each frame...
[ 0 ]
[]
[]
[ "button", "image", "python", "tkinter" ]
stackoverflow_0074446835_button_image_python_tkinter.txt
Q: How to read Enumeration values via. pyads I'm recently using the package pyads to connect to Beckhoff TwinCAT3. The reading and writing methods work smoothly. (BTW: TwinCAT3 works fine) But some error occurs when I try to write a value into an enumeration in TwinCAT3. I'm using the easiest code to test: eCtrlMode ...
How to read Enumeration values via. pyads
I'm recently using the package pyads to connect to Beckhoff TwinCAT3. The reading and writing methods work smoothly. (BTW: TwinCAT3 works fine) But some error occurs when I try to write a value into an enumeration in TwinCAT3. I'm using the easiest code to test: eCtrlMode = plc.write_by_name("GVL_Tset.stTest.eCtrlMode"...
[ "Solution right now:\nAn enumeration in this case is no other than a group of INT values. By using the write_by_name function, the pyads.PLCTYPE_INT property should always be added, otherwise it won't work:\neCtrlMode = plc.write_by_name(\"GVL_Tset.stTest.eCtrlMode\", 1, pyads.PLCTYPE_INT)\n\n", "I came to this q...
[ 3, 1 ]
[]
[]
[ "python", "twincat", "twincat_ads" ]
stackoverflow_0071141178_python_twincat_twincat_ads.txt
Q: Datascraping using Beautiful soup. Finding the wrong body I am trying to learning to web scrape. When I do ctrl + U to see the source code I don't see any of the data I want to however if I inspect the page i can find the information in a different body. I have written the following code: url = "https://hereford.t...
Datascraping using Beautiful soup. Finding the wrong body
I am trying to learning to web scrape. When I do ctrl + U to see the source code I don't see any of the data I want to however if I inspect the page i can find the information in a different body. I have written the following code: url = "https://hereford.ttleagues.com/rankings/24018e59-6861-4082-bb62-5455224a3ad8" re...
[ "The data that's in the body you want comes from an API and is dynamically rendered.\nYou can query the API endpoint and rebuild the table.\nFor example:\nimport datetime\n\nimport pandas as pd\nimport requests\nfrom tabulate import tabulate\n\nheaders = {\n \"Accept\": \"application/json\",\n \"User-Agent\":...
[ 2 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x", "web_scraping" ]
stackoverflow_0074447521_beautifulsoup_python_python_3.x_web_scraping.txt
Q: nglview installed but will not import inside Juypter Notebook via Anaconda.Navigator I'm having trouble importing nglview inside a Juypter Notebook (JNb) cell. The instance of JNb is started via the base (root) Environment inside Anaconda.Navigator GUI. Inside Anaconda.Navigator, I've installed nglview. But the im...
nglview installed but will not import inside Juypter Notebook via Anaconda.Navigator
I'm having trouble importing nglview inside a Juypter Notebook (JNb) cell. The instance of JNb is started via the base (root) Environment inside Anaconda.Navigator GUI. Inside Anaconda.Navigator, I've installed nglview. But the import continues to fail. Versions: Jupyter Notebook (inside Anaconda.Navigator) - 6.4.12 A...
[ "Check whether the version of ipywidget in your current conda version is above 8.0.0. Because Jupyter notebook is not compatible with the new version of ipywidget. Thus try the command below to install the older version of ipywidget, then ǹglview` should be properly imported:\nconda install \"ipywidgets <8\" -c con...
[ 0 ]
[]
[]
[ "ipython", "jupyter_notebook", "python" ]
stackoverflow_0074279848_ipython_jupyter_notebook_python.txt
Q: Python zipfile module can't extract filenames with Chinese characters I'm trying to use a python script to download files from a Chinese service provider (I'm not from China myself). The provider is giving me a .zip file which contains a file which seems to have Chinese characters in its name. This seems to be cau...
Python zipfile module can't extract filenames with Chinese characters
I'm trying to use a python script to download files from a Chinese service provider (I'm not from China myself). The provider is giving me a .zip file which contains a file which seems to have Chinese characters in its name. This seems to be causing the zipfile module to barf. Code: import zipfile f = "/path/to/zip_fi...
[ "The way of Python 2.x(2.7) and Python 3.x dealing with non utf-8 filename in module zipfile are a bit different.\nFirst, they both check ZipInfo.flag_bits of the file, if ZipInfo.flag_bits & 0x800, name of the file will be decode with utf-8.\nIf the check of above is False, in Python 2.x, the byte string of the na...
[ 13, 6, 1, 1, 0, 0 ]
[]
[]
[ "python", "python_2.7", "unicode", "zip" ]
stackoverflow_0041019624_python_python_2.7_unicode_zip.txt
Q: Python: How to create multi line cells in excel when exporting a pandas dataframe I have the following pandas Dataframe df = pd.DataFrame([ [['First Line', 'Second line']], [['First line', 'second line', 'third line']], [['first line']] ]) I am trying to export it into an Excel file. However I would l...
Python: How to create multi line cells in excel when exporting a pandas dataframe
I have the following pandas Dataframe df = pd.DataFrame([ [['First Line', 'Second line']], [['First line', 'second line', 'third line']], [['first line']] ]) I am trying to export it into an Excel file. However I would like that between each list-element a line break is entered, similar to ALT-ENTER in Exc...
[ "First you'll need to make sure to have a single string with '\\n' as a separator instead of the list:\ndf = pd.DataFrame([\n ['First Line\\nSecond line'],\n ['First line\\nsecond line\\nthird line'],\n ['first line']\n ])\n\nYou can then call to_excel like you normally do, then open the fil...
[ 13, 1, 0 ]
[]
[]
[ "excel", "pandas", "python" ]
stackoverflow_0050908676_excel_pandas_python.txt
Q: Is there a better way to convert json within a pandas dataframe into additional dataframes? I have a dataframe arguments with the columns RecordID(Int) and additional_arguments(Json formatted string object). I am trying to convert each of the jsons into a dataframe and then concatenate them all into one dataframe....
Is there a better way to convert json within a pandas dataframe into additional dataframes?
I have a dataframe arguments with the columns RecordID(Int) and additional_arguments(Json formatted string object). I am trying to convert each of the jsons into a dataframe and then concatenate them all into one dataframe. Currently, I am doing this with a for loop: arguments_output = pd.DataFrame([]); for i in range(...
[ "without seeing an example input, it's hard to say, but can un-nest json.\npandas.json_normalize()\n" ]
[ 0 ]
[]
[]
[ "dataframe", "for_loop", "pandas", "python" ]
stackoverflow_0074447898_dataframe_for_loop_pandas_python.txt
Q: Import "lab_utils_uni could not be resolved I need help with this Problem: Import "lab_utils_uni" could not be resolved. I installed numpy and matplotlib but lab_utils_uni didnt work. I am working with Visual Studio Code btw. import numpy as np import matplotlib.pyplot as plt from lab_utils_uni import plt_intuitio...
Import "lab_utils_uni could not be resolved
I need help with this Problem: Import "lab_utils_uni" could not be resolved. I installed numpy and matplotlib but lab_utils_uni didnt work. I am working with Visual Studio Code btw. import numpy as np import matplotlib.pyplot as plt from lab_utils_uni import plt_intuition, plt_stationary, plt_update_onclick, soup_bowl ...
[ "\nIt's a \"reportMissingImports\" warning.\nlab_utils_uni is local drawing routines.\nYou need a lab_utils_uni.py file in your workspace.\n", "Thatʻs simple, copy lab_utils_uni.py file to the same directory your code is saved to. You can download that python files from the \"files\" tab on Coursera online tab.\n...
[ 0, 0 ]
[]
[]
[ "import", "python", "visual_studio_code" ]
stackoverflow_0073935233_import_python_visual_studio_code.txt
Q: Python exception hook returning wrong function I want to customize Python exception format for easier searching in logs. For uncaught exceptions I think I should use an exception hook, so I did this: logging.basicConfig( level=logging.DEBUG, format="[%(levelname)s] [%(filename)s.%(funcName)s:%(lineno)d] %(...
Python exception hook returning wrong function
I want to customize Python exception format for easier searching in logs. For uncaught exceptions I think I should use an exception hook, so I did this: logging.basicConfig( level=logging.DEBUG, format="[%(levelname)s] [%(filename)s.%(funcName)s:%(lineno)d] %(message)s", ) def exception_hook(exc_type, exc_valu...
[ "The fix for this is the stacklevel keyword argument. As described in the docs for logger.debug:\n\nThe third optional keyword argument is stacklevel, which defaults to 1. If greater than 1, the corresponding number of stack frames are skipped when computing the line number and function name set in the LogRecord cr...
[ 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0074447833_exception_python.txt
Q: Intents value error in discord.py client subclass I am new in creating bots for discord. Recently, while creating it, I chose to do it using Client Subclass to create my bot. I am running the latest version of discord.py I have gone through the documentation but as I'm new being a developer on discord, I'm struggi...
Intents value error in discord.py client subclass
I am new in creating bots for discord. Recently, while creating it, I chose to do it using Client Subclass to create my bot. I am running the latest version of discord.py I have gone through the documentation but as I'm new being a developer on discord, I'm strugging to understand, how I can define my intents specifica...
[ "As the error suggests, __init__ of discord.Client expects intents argument, so pass it in super().__init__():\nclass MyClient(discord.Client):\n\n def __init__(self, model_name):\n intents = discord.Intents.default()\n intents.message_content = True\n super().__init__(intents=intents)\n ...\n\n" ]
[ 1 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074447940_discord_discord.py_python.txt
Q: How to get same output when we are using request.get(url) and driver.get(url) url = 'https://www.jma.go.jp/bosai/warning/#lang=en' page = requests.get(url) soup = BeautifulSoup(page.content,'html.parser') print(soup) driver = webdriver.Chrome(service=Service( ChromeDriverManager().install()), options=options) dr...
How to get same output when we are using request.get(url) and driver.get(url)
url = 'https://www.jma.go.jp/bosai/warning/#lang=en' page = requests.get(url) soup = BeautifulSoup(page.content,'html.parser') print(soup) driver = webdriver.Chrome(service=Service( ChromeDriverManager().install()), options=options) driver.get(url) page = driver.page_source soup = BeautifulSoup(page.content,'html.par...
[ "No, it is not.\ndriver.get() loads a web page in the current browser session.\nThis method does not return any value. So it will always be None.\nrequests.get() sends a GET request and returns requests.Response class.\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074447851_beautifulsoup_python_web_scraping.txt
Q: How do I get the console output of a subprocess regardless of the exit code I am trying to call a subprocess and record the output of said process no matter whether it exits with an exit code of zero or non-zero. Basically my subprocess will produce a bunch of debug output, part of which is an error code (like 404...
How do I get the console output of a subprocess regardless of the exit code
I am trying to call a subprocess and record the output of said process no matter whether it exits with an exit code of zero or non-zero. Basically my subprocess will produce a bunch of debug output, part of which is an error code (like 404: Not Found) and I want to read that Error code from the output or the "Success" ...
[ "I resolved the issue by using subprocess.run() instead of subprocess.call()\nand capturing the output. This also ensured that the correct output was always returned.\nCode:\ndef run_subprocess(directory, command):\n os.chdir(directory)\n result = None\n p1 = subprocess.run(command, shell=True, text=True, ...
[ 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0074447512_python_subprocess.txt
Q: Enumeration with auto-numbering starting at 0 Is there a better way to create a long list of enumeration with auto-numbering starting at 0? The closest that I can find is: class Color(Enum): red, green, blue=range(3) However, the above approach requires knowing the total items in the enumeration beforehand. ...
Enumeration with auto-numbering starting at 0
Is there a better way to create a long list of enumeration with auto-numbering starting at 0? The closest that I can find is: class Color(Enum): red, green, blue=range(3) However, the above approach requires knowing the total items in the enumeration beforehand.
[ "As @jonrsharpe already showed, an Enum can be created like this:\nColor = Enum('Color', ['RED', 'GREEN', 'BLUE'])\n\nThis will be indexed (starting) by 1.\nThe official documentation states, from Python 3.5:\n\nuse the start parameter to specify a different starting value\n\nAs the documentation states, you can do...
[ 14, 13, 7, 6, 1, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0041290874_python_python_3.x.txt
Q: Duplicate every nth row and column of a numpy array I have a given 2d np-array and want to duplicate every e.g. 3rd row and column. Basically, if I had an np-array a = np.array([ [1, 2, 3, 1, 2, 3], [2, 3, 4, 2, 3, 4], [3, 4, 5, 3, 4, 5], [4, 5, 6, 4, 5, 6] ]) I would want to produce: b = np.array([ [1,...
Duplicate every nth row and column of a numpy array
I have a given 2d np-array and want to duplicate every e.g. 3rd row and column. Basically, if I had an np-array a = np.array([ [1, 2, 3, 1, 2, 3], [2, 3, 4, 2, 3, 4], [3, 4, 5, 3, 4, 5], [4, 5, 6, 4, 5, 6] ]) I would want to produce: b = np.array([ [1, 2, 3, 3, 1, 2, 3, 3], [2, 3, 4, 4, 2, 3, 4, 4], [3, ...
[ "rows\nYou can identify the Nth row using arithmetic, then duplicate it with np.repeat:\nN = 3\n\nout = np.repeat(a, (np.arange(a.shape[0])%N == (N-1)) + 1, axis=0)\n\nOutput:\narray([[1, 2, 3, 1, 2, 3],\n [2, 3, 4, 2, 3, 4],\n [3, 4, 5, 3, 4, 5],\n [3, 4, 5, 3, 4, 5],\n [4, 5, 6, 4, 5, 6]])...
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074448030_arrays_numpy_python.txt
Q: Creating an object in Python from multiple classes I am creating a spellchecker where I will accept an input word and then produce a list of words with an edit distance of 1 while checking if these words can be found in the ternary tree I will create. This tree will be made using a list of valid words. Only the fu...
Creating an object in Python from multiple classes
I am creating a spellchecker where I will accept an input word and then produce a list of words with an edit distance of 1 while checking if these words can be found in the ternary tree I will create. This tree will be made using a list of valid words. Only the functions with ### TODO: YOUR CODE HERE ### can be revised...
[ "\nclass Spellchecker:\n def __init__(self, valid_words):\n # […]\n\n tree = TernarySearchTree()\n\n for word in valid_words:\n tree.root_node = tree.insert(word, tree.root_node)\n \n # […]\n\n def make_suggestions(self, word):\n # […]\n\n nearby_strings...
[ 0 ]
[]
[]
[ "python", "spell_checking", "ternary_tree", "tree" ]
stackoverflow_0074447957_python_spell_checking_ternary_tree_tree.txt
Q: How to remove nan value from a nested list I would like to update a webpage with these values. But I have nan values , i neeed to skip the values with nan. Here the list[1] has 3 nan values. I only need to update it by [[1, 8.4], [1, 2.2],[2, 4.0]] list[0] = [[1, 8.4], [1, 2.2], [1, 1.3], [2, 4.7], [2, 4.0], [8, 9...
How to remove nan value from a nested list
I would like to update a webpage with these values. But I have nan values , i neeed to skip the values with nan. Here the list[1] has 3 nan values. I only need to update it by [[1, 8.4], [1, 2.2],[2, 4.0]] list[0] = [[1, 8.4], [1, 2.2], [1, 1.3], [2, 4.7], [2, 4.0], [8, 9.6]] list[1] = [[1, 8.4], [1, 2.2], [1, nan], [2...
[ "You can iterate on your list and check if there are any None values in it, and remove it from it.\nI'm using the built-in list.copy() method to clone the list so that changes are not being made on both lists.\ndef remove_nan_values(my_list: list):\n new_list = my_list.copy()\n for elem in my_list:\n i...
[ 0 ]
[]
[]
[ "dataframe", "list", "nan", "python" ]
stackoverflow_0074448067_dataframe_list_nan_python.txt
Q: What does ‘ ERROR: No .egg-info directory found in tmp/pi p-pip-egg-info-kt94jnak’ mean? I tried installing clipboard on the Pyto IOS app and got the error. Is there any way to fix this problem? A: According to different responses, the error usually is because setuptools is not installed or updated. Install it: ...
What does ‘ ERROR: No .egg-info directory found in tmp/pi p-pip-egg-info-kt94jnak’ mean?
I tried installing clipboard on the Pyto IOS app and got the error. Is there any way to fix this problem?
[ "According to different responses, the error usually is because setuptools is not installed or updated.\nInstall it:\npython3 -m pip install --upgrade pip setuptools wheel\n\nSeen in these responses:\n\nresponse 1\nresponse 2\n\nIf is not solved, are you installing this? I would try installing the required librarie...
[ 0 ]
[]
[]
[ "ios", "python" ]
stackoverflow_0074440346_ios_python.txt
Q: How can I make python unittest failures not print the entire test? When using my python unit tests, sometimes my tests become somewhat long due to test-specific inputs, or other lengthy logic. If one of my tests fail, unittest will print out the entire test, from the top of the list down to the assertion failure. ...
How can I make python unittest failures not print the entire test?
When using my python unit tests, sometimes my tests become somewhat long due to test-specific inputs, or other lengthy logic. If one of my tests fail, unittest will print out the entire test, from the top of the list down to the assertion failure. The problem is that if my test is long for any reason, then when the tes...
[ "I believe unittest does not have such traceback by default:\nF\n======================================================================\nFAIL: testArbitraryStringTest (__main__.Test1)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"D:\\repos\\sta...
[ 1 ]
[]
[]
[ "python", "python_unittest" ]
stackoverflow_0074448017_python_python_unittest.txt
Q: fill out NA value with the same code char in the same group I have this dataset. I would like to fill out NA value with the same code char in the same group. in this example the first NA will be S, and the second one will be F Thank you, df = {'Key': ['111*1', '111*2','111*3', '222*1','222*2', '333*1','333*2', '3...
fill out NA value with the same code char in the same group
I have this dataset. I would like to fill out NA value with the same code char in the same group. in this example the first NA will be S, and the second one will be F Thank you, df = {'Key': ['111*1', '111*2','111*3', '222*1','222*2', '333*1','333*2', '333*3','333*4', '444*1'], 'code': ['S', 'S','NA', 'M','M',...
[ "You can use:\ns = df['code'].replace('NA', np.nan)\n\ndf['code'] = s.fillna(s.groupby(df['Key'].str.extract('([^*]+)*', expand=False))\n .transform('first')\n )\n\nIf you already have Keya:\ns = df['code'].replace('NA', np.nan)\n\ndf['code'] = s.fillna(s.groupby(df['Keya']...
[ 1 ]
[]
[]
[ "autofill", "na", "pandas", "python" ]
stackoverflow_0074448105_autofill_na_pandas_python.txt
Q: Python calculating percentages from list Hello i have a list that has the following information that is retrieved from a db test_list_1 = ['01/01/2022:79.86','02/01/2022:65.86','03/01/2022:600.23','04/01/2022:179.26'] test_list_2 = ['01/01/2022:55.86','02/01/2022:25.75','03/01/2022:300.23'] I would like to be abl...
Python calculating percentages from list
Hello i have a list that has the following information that is retrieved from a db test_list_1 = ['01/01/2022:79.86','02/01/2022:65.86','03/01/2022:600.23','04/01/2022:179.26'] test_list_2 = ['01/01/2022:55.86','02/01/2022:25.75','03/01/2022:300.23'] I would like to be able to produce the following output from that: #...
[ "A solution that relies on the powerful itertools module to first generate combinations.\nApplied here on test_list1.\nJust make a function of that to apply to any list in argument.\nfrom itertools import combinations\n\ndef pdiff(src: float, dst: float) -> float:\n return (dst-src)/src*100\n\ncombs = [(x,y) for...
[ 2, 2, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074447609_list_python.txt
Q: Pandas dataframe duplicates in a subset of column string I have a pandas dataframe, with two columns id and user_name. Where the id column have this format (xxxxxx-xxx-A): r'[0-9]{6}-[0-9]{3}$'+alphabet letter. Here's my dataframe example : id user name 095082-000-A name1 095772-101-A name2 095082-000-B ...
Pandas dataframe duplicates in a subset of column string
I have a pandas dataframe, with two columns id and user_name. Where the id column have this format (xxxxxx-xxx-A): r'[0-9]{6}-[0-9]{3}$'+alphabet letter. Here's my dataframe example : id user name 095082-000-A name1 095772-101-A name2 095082-000-B name3 095772-101-E name4 095772-101-Z name5 095772-101-D...
[ "You can split your string in the common identifier and the letter, then sort the values in the desired priority, finally get the last index per group:\nidx = (df['id']\n .str.extract(r'([0-9]{6}-[0-9]{3})-(.*)')\n .sort_values(by=1)\n .reset_index()\n .groupby(0, sort=False)['index'].last()\n)\n\nout = df.loc[idx]...
[ 0, 0 ]
[]
[]
[ "dataframe", "duplicates", "pandas", "python", "subset" ]
stackoverflow_0074447529_dataframe_duplicates_pandas_python_subset.txt
Q: Fill in the empty lists in a list with value in python Having the nested list like this: lst = [[1,3], [], [2,2,4], [], [3,5]] I'm trying to fill in the empty lists with a value (let's say 0). I know how can do it if we are flatting the list - so then we can use either list comprehension or some pandas solution, ...
Fill in the empty lists in a list with value in python
Having the nested list like this: lst = [[1,3], [], [2,2,4], [], [3,5]] I'm trying to fill in the empty lists with a value (let's say 0). I know how can do it if we are flatting the list - so then we can use either list comprehension or some pandas solution, but how is it possible to do not to change the structure of ...
[ "With i you can directly access to lst. Since i is not a copy you can modify it and then see the result in the original list.\nlst = [[1,3], [], [2,2,4], [], [3,5]]\nfor i in lst:\n if len(i) == 0:\n i.append(0)\n\nOutput:\n\n[[1, 3], [0], [2, 2, 4], [0], [3, 5]]\n\n", "Just loop over the list and use a...
[ 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074448144_list_python.txt
Q: How to wait for the specific image to appear on screen using pyautogui? I have one application which I am able to automate using the pyautogui module. I am keeping the reference image in the script directory, and after some sleep time, I am able to complete it. In some builds, the specific image takes a while to a...
How to wait for the specific image to appear on screen using pyautogui?
I have one application which I am able to automate using the pyautogui module. I am keeping the reference image in the script directory, and after some sleep time, I am able to complete it. In some builds, the specific image takes a while to appear. After which my script throws attribute not found error. I need to know...
[ "This will wait until it finds the image:\nicon_to_click = \"Recycle Bin\"\n\nr = None\nwhile r is None:\n r = pyautogui.locateOnScreen('rb.png', grayscale = True)\nprint icon_to_click + ' now loaded'\n\n", "In newer version of Python (3.6), locateOnScreen() no longer returns None if it can't find an image. It...
[ 3, 2, 0 ]
[]
[]
[ "pyautogui", "python", "python_3.x", "pywinauto" ]
stackoverflow_0050643931_pyautogui_python_python_3.x_pywinauto.txt
Q: scikitlearn - result from HTML code parsing Which ML model can be best used to learn to map between HTML code and resulting strings? For example, if a model trains on 1000 websites containing various grids and names in different HTML code as input, which model is best used to output the names and image tags associ...
scikitlearn - result from HTML code parsing
Which ML model can be best used to learn to map between HTML code and resulting strings? For example, if a model trains on 1000 websites containing various grids and names in different HTML code as input, which model is best used to output the names and image tags associated with the grid?
[ "Probably the best approach would be a Transformer. Transformers are currently the industry standard when it comes to NLP problems. There are many different Transformers on hugging face which you can find here: https://huggingface.co/transformers/v4.9.2/quicktour.html\nI am not sure if there is a pre-trained model ...
[ 0 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0074447994_python_scikit_learn.txt
Q: ***Time limit exceeded*** error on python program when i try to print this line: print(perfect_square(0)) i should get True but instead i get a time limit exceeded error and i dont know how to fix it. i tried chaging it to an elif statment instead of 2 separate if statements but i still get that error This is my c...
***Time limit exceeded*** error on python program
when i try to print this line: print(perfect_square(0)) i should get True but instead i get a time limit exceeded error and i dont know how to fix it. i tried chaging it to an elif statment instead of 2 separate if statements but i still get that error This is my current code: def perfect_square(n): s = 1 whil...
[ "Seems quite clear to me why the perfect_square(0) and perfect_cube(0) cases cause an infinite loop. You start s=1 and always increment it s+=1. It will never be equal to n=0 so you get an infinitely running program. Maybe try making checks for invalid values of n?\ndef perfect_cube(n):\n if n < 1: return False\...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074448283_python.txt
Q: Is there a parameter for GridSearchCV to select the best with the lowest difference between train and test set? My goal is to get good fit model (train and test set metrics differences are only 1% - 5%). This is because the Random Forest tends to overfit (the default params train set f1 score for class 1 is 1.0) T...
Is there a parameter for GridSearchCV to select the best with the lowest difference between train and test set?
My goal is to get good fit model (train and test set metrics differences are only 1% - 5%). This is because the Random Forest tends to overfit (the default params train set f1 score for class 1 is 1.0) The problem is, the GridSearchCV only consider the test set metrics. It disregard the train set metrics. Therefore, th...
[ "You can provide a callable for the refit parameter:\n\nWhere there are considerations other than maximum score in choosing a best estimator, refit can be set to a function which returns the selected best_index_ given cv_results_. In that case, the best_estimator_ and best_params_ will be set according to the retur...
[ 0 ]
[]
[]
[ "cross_validation", "grid_search", "imblearn", "python", "scikit_learn" ]
stackoverflow_0074439861_cross_validation_grid_search_imblearn_python_scikit_learn.txt
Q: Server fails to save or retrieve data and crashes app in python flask I first wrote the following code, which seemed to work: Full code Then I started to incorporate a password input field and kept getting an "Internal Server Error" whenever I tried putting in an existing user. When I used debugger it seems to fai...
Server fails to save or retrieve data and crashes app in python flask
I first wrote the following code, which seemed to work: Full code Then I started to incorporate a password input field and kept getting an "Internal Server Error" whenever I tried putting in an existing user. When I used debugger it seems to fail when the program tries to retrieve information from the database but the ...
[ "I'm not familiar w/ this .save() syntax and can't find it in the sqlalchemy docs. Have you tried instead using the following syntax inside your try statement?\ntry: # tries to save the data in to the database as a new user - if the email already exists this will fail\n user = User(name=name, email=email, passwo...
[ 0 ]
[]
[]
[ "flask", "python", "sqlalchemy" ]
stackoverflow_0074448043_flask_python_sqlalchemy.txt
Q: PyPy C++ API missing Py_Initialize() I'm trying to call PyPy from C++. When using CPython, I need to call Py_Initialize() function before calling any other Py_* functions. However, PyPy does not have Py_Initialize() or PyPy_Initialize() functions. How should it be replaced? If I don't have it, my program simply cr...
PyPy C++ API missing Py_Initialize()
I'm trying to call PyPy from C++. When using CPython, I need to call Py_Initialize() function before calling any other Py_* functions. However, PyPy does not have Py_Initialize() or PyPy_Initialize() functions. How should it be replaced? If I don't have it, my program simply crashes when I try to use any PyPy_* or Py_*...
[ "See this issue in the PyPy issue tracker. There is still a lot to do to make Py_Initialize work on PyPy. Help is welcome.\n" ]
[ 1 ]
[]
[]
[ "c++", "pypy", "python" ]
stackoverflow_0074445894_c++_pypy_python.txt
Q: How to specify upper and lower limits when using numpy.random.normal I want to be able to pick values from a normal distribution that only ever fall between 0 and 1. In some cases I want to be able to basically just return a completely random distribution, and in other cases I want to return values that fall in th...
How to specify upper and lower limits when using numpy.random.normal
I want to be able to pick values from a normal distribution that only ever fall between 0 and 1. In some cases I want to be able to basically just return a completely random distribution, and in other cases I want to return values that fall in the shape of a gaussian. At the moment I am using the following function: de...
[ "It sounds like you want a truncated normal distribution.\nUsing scipy, you could use scipy.stats.truncnorm to generate random variates from such a distribution:\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\n\nlower, upper = 3.5, 6\nmu, sigma = 5, 0.7\nX = stats.truncnorm(\n (lower - mu) / sigma...
[ 63, 18, 7, 6, 1, 0, 0, 0 ]
[]
[]
[ "gaussian", "numpy", "python", "random", "scipy" ]
stackoverflow_0018441779_gaussian_numpy_python_random_scipy.txt
Q: DBSCAN clustering with haversine distance I have a dataset with 33707 rows. I want to cluster my dataset using DBSCAN clustering algorithm with haversine distance metrics. My code is given in the image. I am getting only one clusters. Which value should I change eps or min_samples to get accurate number of cluster...
DBSCAN clustering with haversine distance
I have a dataset with 33707 rows. I want to cluster my dataset using DBSCAN clustering algorithm with haversine distance metrics. My code is given in the image. I am getting only one clusters. Which value should I change eps or min_samples to get accurate number of clusters. kms_per_radian = 6371.0088 epsilon = 0.5 / k...
[ "Please try to decrease the min_samples to small number.\n" ]
[ 1 ]
[]
[]
[ "dbscan", "haversine", "python" ]
stackoverflow_0064193057_dbscan_haversine_python.txt
Q: Jupyter notebook renders text instead of ipywidgets My Jupyter notebook is displaying text rather than ipywidgets. Here is a screenshot: I read several posts about similar problems, like this one: Jupyter Notebook not rendering ipywidgets. Most of them indicate that the solution is to enable an extension, e.g: ht...
Jupyter notebook renders text instead of ipywidgets
My Jupyter notebook is displaying text rather than ipywidgets. Here is a screenshot: I read several posts about similar problems, like this one: Jupyter Notebook not rendering ipywidgets. Most of them indicate that the solution is to enable an extension, e.g: https://stackoverflow.com/a/38001920/11692496 But it seems ...
[ "For the record, I didn't manage to solve this issue on my virtualenv.\nAs @Wayne suggested above, I went for a workaround, namely a docker container based on jupyter/tensorflow-notebook\n" ]
[ 0 ]
[]
[]
[ "ipywidgets", "jupyter_notebook", "python" ]
stackoverflow_0074142313_ipywidgets_jupyter_notebook_python.txt
Q: Monetory fields not taking 0 value instead its reverting to previous value in odoo 13.0 ver I have some custom modules developed from scratch in that Monetory fields are not taking 0 value instead its reverting to previous value. installation : odoo 13.0 exe installation installed on : 13.0.20200412 Example : In f...
Monetory fields not taking 0 value instead its reverting to previous value in odoo 13.0 ver
I have some custom modules developed from scratch in that Monetory fields are not taking 0 value instead its reverting to previous value. installation : odoo 13.0 exe installation installed on : 13.0.20200412 Example : In form view xxx_monetory : 5000 --> 0 when I click on save button the previous value i.e 5000 is rev...
[ "You should use fields.Integer or fields.Float instead of fields.Monetary to represent numbers in Odoo.\nIn your view:\n<field name=\"currency_id\" invisible=\"1\" />\n<field name=\"fee\" widget=\"monetary\" options=\"{'currency_field': 'currency_id'}\" />\n\n" ]
[ 0 ]
[]
[]
[ "field", "odoo_13", "python" ]
stackoverflow_0074448138_field_odoo_13_python.txt
Q: Reset random call I am making a blackjack game for class, my code works and there are no errors persay, but every time I call the play function it doesn't reset the cards you are dealt. It works if you stop and run the program again but when you say yes to try again it gives you and the dealer the same cards every...
Reset random call
I am making a blackjack game for class, my code works and there are no errors persay, but every time I call the play function it doesn't reset the cards you are dealt. It works if you stop and run the program again but when you say yes to try again it gives you and the dealer the same cards everytime. It isn't the same...
[ "The problem is that when a second game starts there is no code that changes the hands of both players. They still have the cards of the previous game.\nThe quick fix is to add the following code at the top of the play function:\ndef play():\n # Return all cards to the deck\n deck.extend(playerHand)\n deck...
[ 1 ]
[]
[]
[ "blackjack", "python", "random" ]
stackoverflow_0074442384_blackjack_python_random.txt
Q: how can i clean part of a data set that contains data from before 2000? im new to python and to working with datasets, i'm using a data set that has certain stocks and stuff about them since the 1980's till the late 2010's, i dont want to use any of the stocks in the data set when i use the knn prediction, what ca...
how can i clean part of a data set that contains data from before 2000?
im new to python and to working with datasets, i'm using a data set that has certain stocks and stuff about them since the 1980's till the late 2010's, i dont want to use any of the stocks in the data set when i use the knn prediction, what can i do? for i in df["Date"]: if(i.startswith("19")): f=df.drop(['Adj Cl...
[ "I would suggest you put the date as an index :\ndf.set_index(\"Date\", inplace=True)\n\nand then slice using this method (please put your dates)\ndf.loc['2000-01-01':'2020-02-01']\n\n", "In general it is not the best solution to iterate through rows in pandas datasets. The best way is using a mask, in your case:...
[ 0, 0, 0, 0 ]
[]
[]
[ "data_science", "google_colaboratory", "python" ]
stackoverflow_0074448186_data_science_google_colaboratory_python.txt
Q: pandas: list items converted to Decimals when writing csv. Cannot parse it back with read_csv I had a DataFrame with a column, in which each cell contained a list of Decimals like [Decimal('1'), Decimal('3')]. Then I wrote it into a csv file with pd.to_csv. Now I am trying to parse it with pd.read_csv and get a st...
pandas: list items converted to Decimals when writing csv. Cannot parse it back with read_csv
I had a DataFrame with a column, in which each cell contained a list of Decimals like [Decimal('1'), Decimal('3')]. Then I wrote it into a csv file with pd.to_csv. Now I am trying to parse it with pd.read_csv and get a string like "[Decimal('1'), Decimal('3')]" instead of a real list of Decimals. What should I do to ge...
[ "Because pd.to_csv only returns the resulting csv format as a string. Otherwise returns None. So you have to convert string to list manually. Please refer to my example below, hope it is similar to what you are asking.\nimport json\nd = {'col1': [[1.0,2.0], [1.0,2.0]], 'col2': [3.0, 4.0]}\ndf = pd.DataFrame(data=d)...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074447788_pandas_python.txt
Q: Where are the Type annotation constraints (`ValueRange`/`MinLen` etc) in python 3.9? After seeing the (awesome) new Annotated type annotation in python 3.9 (varaidic type constraints!), I rushed to upgrade so I could check them out. (https://docs.python.org/3/library/typing.html?highlight=valuerange) But when I tr...
Where are the Type annotation constraints (`ValueRange`/`MinLen` etc) in python 3.9?
After seeing the (awesome) new Annotated type annotation in python 3.9 (varaidic type constraints!), I rushed to upgrade so I could check them out. (https://docs.python.org/3/library/typing.html?highlight=valuerange) But when I tried using ValueRange[min,max] or MaxLen[n] - I couldn't seem to find them anywhere.. PyCha...
[ "As others have said, these classes are just an example of what can be annotated. Annotation just grabs a certain variable and adds some \"hints\" to them via the class you created (MaxLen, ValueRange, etc).\nYou can then obtain which \"hints\" are related to every parameter using get_type_hints, and crawl one per ...
[ 3, 0 ]
[]
[]
[ "python", "python_3.x", "types" ]
stackoverflow_0065385585_python_python_3.x_types.txt
Q: Can anyone suggest a quick fix for the error I am getting in L shape matrix traversal? I want to traverse my matrix in the L shape, and I took the code from this link https://www.geeksforgeeks.org/traverse-matrix-in-l-shape/. However, it throws an index out-of-range error with input values when rows = 3 and cols =...
Can anyone suggest a quick fix for the error I am getting in L shape matrix traversal?
I want to traverse my matrix in the L shape, and I took the code from this link https://www.geeksforgeeks.org/traverse-matrix-in-l-shape/. However, it throws an index out-of-range error with input values when rows = 3 and cols = 9. # Printing matrix in L shape def traverseLshape(a, n, m): # for each column or ...
[ "If m>n, then range(0, n - j) with j in [0,m) may be range(0,0) or even range(0,-?). Which is empty. That is not your main problem. Since then for i in range(0,n-j) will just do nothing. But just noting it, because it is obviously not wanted.\nBut more importantly, a[n - 1 - j][k] when j is m-1 (its biggest value) ...
[ 0 ]
[]
[]
[ "matrix", "python", "traversal" ]
stackoverflow_0074445358_matrix_python_traversal.txt
Q: Assistance in solving a linear system of equations with least_squares I'm hoping to just get some assistance conceptually about how to solve a linear system of equations with penalty functions. Example code is at the bottom. Let's say I'm trying trying to do a fit of this equation: Ie=IaX+IbY+IcZ where Ie, Ia, Ib...
Assistance in solving a linear system of equations with least_squares
I'm hoping to just get some assistance conceptually about how to solve a linear system of equations with penalty functions. Example code is at the bottom. Let's say I'm trying trying to do a fit of this equation: Ie=IaX+IbY+IcZ where Ie, Ia, Ib, and Ic are constants, and X,Y,Z are variables I could easily solve this s...
[ "Your initial guess xinit is not feasible and doesn't satisfy your constraint.\nIMO, solving the initial problem directly as a constrained nonlinear optimization problem (NLP) instead of rewriting it is the easier approach. Assuming you have all the data points Ia, Ib, Ic and Ie (you didn't provide all of them), yo...
[ 1 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0074439047_python_scipy.txt
Q: How would one extrapolate data from one column of strings and set a value in another column? I have some scraped data from an ecommerce website and that has the package unit count in the name (see example below). I want to take the unit count information from the name and add the number of units as a int into a "U...
How would one extrapolate data from one column of strings and set a value in another column?
I have some scraped data from an ecommerce website and that has the package unit count in the name (see example below). I want to take the unit count information from the name and add the number of units as a int into a "Unit" column. I know I can use df.loc[product_column].str.contains('10 pk'), unitColumn] = 10, or ...
[ "I ended up using this solution:\nPut all possibilities in a dictionary.\n dfQty={\n 2:tuple(['Pack x2', '2-pack', '2pk','2-pack']),\n 3: tuple(['3 pack', '3pk']),\n #4: tuple([]),\n 5: tuple(['5 pack', '5-pack','5pk']),\n 6: tuple(['6 pack']),\n 7: tuple(['7 pack', '7pk']),\n #8: tuple([]),...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074281339_pandas_python.txt
Q: NumPy - slow double for loop for heatmap color calculation In the following code I wanted to generate a color heatmap (w x h x 3) based on the values of a NumPy 2-d array, in the range [-1; 1], and, unsurprisingly, it is really slow on large arrays (10000 x 10000) compared to the rest of the program, which uses Nu...
NumPy - slow double for loop for heatmap color calculation
In the following code I wanted to generate a color heatmap (w x h x 3) based on the values of a NumPy 2-d array, in the range [-1; 1], and, unsurprisingly, it is really slow on large arrays (10000 x 10000) compared to the rest of the program, which uses NumPy numerical operations. Colors are in the [B, G, R] format. de...
[ "\nAs per your comment under your question - For example, -1 will display full bright red, -0.5 orange, 0 yellow, 0.5 lime, 1 green\n\nIIUC, you are trying to display a large matrix as a heatmap where you can set the color maps at fixed static values but, the color mixing should happen automatically. For example - ...
[ 1, 1 ]
[]
[]
[ "heatmap", "numpy", "python" ]
stackoverflow_0074447649_heatmap_numpy_python.txt
Q: Cmake problems after upgrading to MacOS 13.0 As mentioned on the title, CMake seems to be broken after upgrading to MacOS 13.0. Trying to install something that requires Cmakes takes unusually long then the following pop-up shows up. “CMake” is damaged and can’t be opened. You should move it to the Trash. This f...
Cmake problems after upgrading to MacOS 13.0
As mentioned on the title, CMake seems to be broken after upgrading to MacOS 13.0. Trying to install something that requires Cmakes takes unusually long then the following pop-up shows up. “CMake” is damaged and can’t be opened. You should move it to the Trash. This file was downloaded on an unknown date. # this txt...
[ "The pip package is broken on macOS 13 prior to CMake 3.24.2 due to improper code signing. You should upgrade CMake in your virtual environment by running:\n$ python -m pip install -U pip setuptools wheel\n$ python -m pip install -U 'cmake>=3.24.2'\n\nAs CMake is extremely backwards compatible, it should be safe. Y...
[ 0 ]
[]
[]
[ "cmake", "macos", "opencv", "python" ]
stackoverflow_0074194672_cmake_macos_opencv_python.txt
Q: How to read/process command line arguments? I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? Related What’s the best way to grab/parse command line arguments passed to a Python script? Implementing ...
How to read/process command line arguments?
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? Related What’s the best way to grab/parse command line arguments passed to a Python script? Implementing a “[command] [action] [parameter]” style command-...
[ "import sys\n\nprint(\"\\n\".join(sys.argv))\n\nsys.argv is a list that contains all the arguments passed to the script on the command line. sys.argv[0] is the script name.\nBasically,\nimport sys\nprint(sys.argv[1:])\n\n", "The canonical solution in the standard library is argparse (docs):\nHere is an example:\n...
[ 660, 575, 131, 76, 68, 52, 51, 26, 20, 9, 8, 8, 6, 5, 5, 4, 3, 0, 0, 0, 0, 0 ]
[]
[]
[ "command_line", "command_line_arguments", "python" ]
stackoverflow_0001009860_command_line_command_line_arguments_python.txt
Q: Add RobotFramework to Ubuntu:16.04 enter image description hereI want to download robotframework in ubuntu for dockerfile but i didn't found. What can i do? FROM ubuntu:16.04 RUN apt-get update RUN apt-get install software-properties-common -y RUN add-apt-repository --yes ppa:ansible/ansible-2.10 RUN apt-get ...
Add RobotFramework to Ubuntu:16.04
enter image description hereI want to download robotframework in ubuntu for dockerfile but i didn't found. What can i do? FROM ubuntu:16.04 RUN apt-get update RUN apt-get install software-properties-common -y RUN add-apt-repository --yes ppa:ansible/ansible-2.10 RUN apt-get install ansible -y RUN add-apt-repositor...
[ "You are having problems with the versions you are requesting. pip for example is failing to install. Also python3.6 is an old version.\nYou should update your Dockerfile to use Ubuntu LTS, which is currently in version 22.0.4.\n" ]
[ 1 ]
[]
[]
[ "python", "robotframework", "ubuntu_16.04" ]
stackoverflow_0074447146_python_robotframework_ubuntu_16.04.txt
Q: How to limit decimals when adjusting a raster array with rasterio I have multiple raster images. Currently all the cells have a value which is a count of something. I would like to have this as a percentage. I did this with the following code: This works fine, but it creates a lot of decimals for some values (33.3...
How to limit decimals when adjusting a raster array with rasterio
I have multiple raster images. Currently all the cells have a value which is a count of something. I would like to have this as a percentage. I did this with the following code: This works fine, but it creates a lot of decimals for some values (33.33333333). Because I'm working with big rasters this greatly increases f...
[ "Try this, for 3 decimals:\nwith rio.open(path_out, 'w', decimal_precision=3, **profile) as dst:\n # Write to disk\n dst.write(array)\n\nIt worked for me when writing a ASCII.\n" ]
[ 0 ]
[]
[]
[ "decimal", "precision", "python", "rasterio" ]
stackoverflow_0072477542_decimal_precision_python_rasterio.txt
Q: Determine basic color names from HEX or RGB in python I am trying to find out if a hex color is "blue". This might be a very subjective thing when comparing different (lighter/ darker) shades of blue or close to blue colors but in my case it does not have to be very precise. I just want to determine if a color is ...
Determine basic color names from HEX or RGB in python
I am trying to find out if a hex color is "blue". This might be a very subjective thing when comparing different (lighter/ darker) shades of blue or close to blue colors but in my case it does not have to be very precise. I just want to determine if a color is blue or not. The more generalized question would be, is the...
[ "This is a somewhat complicated question, see more discussion here: https://graphicdesign.stackexchange.com/questions/92984/how-can-i-tell-basic-color-a-hex-code-is-closest-to\nI don't know of any library or implementation that already exists for this. If you really need this functionality though and don't need it ...
[ 1 ]
[ "I mean you could do:\nhex = input() \n\nif hex == '#0000FF':\n print('Blue')\n\nelse:\n print('Not blue') \n\nIf that is what you are looking for.\n" ]
[ -1 ]
[ "colors", "hex", "python", "rgb" ]
stackoverflow_0074448363_colors_hex_python_rgb.txt
Q: Using python to create .bat file and the run the newly created .bat file does not work I'm using Deadline monitor to automate a few processes. I don't think you'll need to know about Deadline to answer my question though. I've created a Python script that takes a few arguments to be able to create the .bat file. I...
Using python to create .bat file and the run the newly created .bat file does not work
I'm using Deadline monitor to automate a few processes. I don't think you'll need to know about Deadline to answer my question though. I've created a Python script that takes a few arguments to be able to create the .bat file. I then want the same python script to run the .bat file to do what I need it to do. However, ...
[ "Perhaps the newly created .bat file has some hidden text characters in it that causes the batch file to fail?\nhttps://www.w3schools.io/editor/notepad++-view-hidden-chars/\n", "The answer to my problem was related to another one of the answers I got.\nEssentially I'm creating a batch file inside of Python. The w...
[ 1, 0 ]
[]
[]
[ "batch_file", "python" ]
stackoverflow_0074429458_batch_file_python.txt
Q: Combining multiple sets of data to one JSON file from api calls I need two sets of data from this website: https://www.nasdaq.com/market-activity/stocks/aapl/institutional-holdings Which include both the "Active Positions" and "New and Sold Out Positions" tables. The code i have can only provide one piece of data ...
Combining multiple sets of data to one JSON file from api calls
I need two sets of data from this website: https://www.nasdaq.com/market-activity/stocks/aapl/institutional-holdings Which include both the "Active Positions" and "New and Sold Out Positions" tables. The code i have can only provide one piece of data into a JSON: import requests import pandas as pd url = 'https://api....
[ "If you only want json data, there is no need to use pandas:\nimport requests\n\nnasdaq_dict = {}\n\nurl = 'https://api.nasdaq.com/api/company/AAPL/institutional-holdings?limit=15&type=TOTAL&sortColumn=marketValue&sortOrder=DESC'\n\nheaders = {\n 'accept': 'application/json, text/plain, */*',\n 'origin': 'htt...
[ 2 ]
[]
[]
[ "api", "json", "python", "web_scraping" ]
stackoverflow_0074447872_api_json_python_web_scraping.txt
Q: How do I split the definition of a long string over multiple lines? I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not re...
How do I split the definition of a long string over multiple lines?
I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). E...
[ "Are you talking about multi-line strings? Easy, use triple quotes to start and end them.\ns = \"\"\" this is a very\n long string if I had the\n energy to type more and more ...\"\"\"\n\nYou can use single quotes too (3 of them of course at start and end) and treat the resulting string s just like an...
[ 3035, 297, 184, 63, 61, 55, 42, 30, 24, 22, 20, 17, 14, 12, 11, 6, 6, 5, 5, 4, 4, 3, 3, 3, 2, 2, 1, 0, 0 ]
[ "Generally, I use list and join for multi-line comments/string.\nlines = list()\nlines.append('SELECT action.enter code here descr as \"action\", ')\nlines.append('role.id as role_id,')\nlines.append('role.descr as role')\nlines.append('FROM ')\nlines.append('public.role_action_def,')\nlines.append('public.role,')\...
[ -12 ]
[ "multiline", "multilinestring", "python", "string" ]
stackoverflow_0010660435_multiline_multilinestring_python_string.txt
Q: Calculating YTD change with dates as column headers my table looks something like this: Sector 1/1/2022 5/1/2022 6/1/2022 1Y Min X 10 05 12 05 Y 18 20 09 09 Z 02 09 12 02 I want to add a new column "YTD change" such that values of the new column is calculated using the formula: (Value as of the latest date - ...
Calculating YTD change with dates as column headers
my table looks something like this: Sector 1/1/2022 5/1/2022 6/1/2022 1Y Min X 10 05 12 05 Y 18 20 09 09 Z 02 09 12 02 I want to add a new column "YTD change" such that values of the new column is calculated using the formula: (Value as of the latest date - Value as of first available date of the year) ...
[ "How about something like this:\nimport pandas as pd\nfrom datetime import datetime \ndf = pd.DataFrame({\n \"Sector\": [\"X\", \"Y\", \"Z\"],\n \"1/1/2022\": [\"10\", \"18\", \"02\"],\n \"5/1/2022\": [\"05\", \"20\", \"09\"],\n \"6/1/2022\": [\"12\", \"60\", \"12\"],\n})\n\n\ndef add_YTD_chg(data):\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074447410_python.txt
Q: How to remove sentences with a specific character? I have a dataframe with article texts. One row, among others, has several sentences with the copyright symbol, "©". article_texts © Aaron Davidson/Getty Images Aaron Davidson/Getty Images Beyond Meat cuts 19% of workforce including disgraced COO, according to a ...
How to remove sentences with a specific character?
I have a dataframe with article texts. One row, among others, has several sentences with the copyright symbol, "©". article_texts © Aaron Davidson/Getty Images Aaron Davidson/Getty Images Beyond Meat cuts 19% of workforce including disgraced COO, according to a release from the company. CEO Ethan Brown says the...
[ "I will share simple proccess.\nReplace © with mask #\nsplit string by .\ndelete elemnst using list compression\ntext =\"\"\"© Aaron Davidson/Getty Images Aaron Davidson/Getty Images Beyond Meat cuts 19% of workforce including disgraced COO, according to a release from the company. CEO Ethan Brown says the plant-ba...
[ 2, 2 ]
[]
[]
[ "data_preprocessing", "dataframe", "nlp", "pandas", "python" ]
stackoverflow_0074448247_data_preprocessing_dataframe_nlp_pandas_python.txt
Q: Iterating through list of list in Python I want to iterate through list of list. I want to iterate through irregularly nested lists inside list also. Can anyone let me know how can I do that? x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], [...
Iterating through list of list in Python
I want to iterate through list of list. I want to iterate through irregularly nested lists inside list also. Can anyone let me know how can I do that? x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
[ "This traverse generator function can be used to iterate over all the values:\ndef traverse(o, tree_types=(list, tuple)):\n if isinstance(o, tree_types):\n for value in o:\n for subvalue in traverse(value, tree_types):\n yield subvalue\n else:\n yield o\n\ndata = [(1,1,...
[ 64, 47, 20, 5, 4, 4, 4, 3, 2, 1 ]
[ "mylist12 = [1,2,[3,4],[5,6,7],8]\n\nprint(dir(mylist12)) # iterable\n\n\nfor i in mylist12:\n if (isinstance(i,list)):\n for j in i:\n print(j)\n else:\n print(i)\n\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0006340351_list_python.txt
Q: How do I fix an ioreg Error In My Python App Code? I am getting the following error message when I run the code for my dash app on Pyto on an iPad. Everything else appears to be working fine, but I can't figure out the solution to this error. I have io imported and image files are going through a standard base 64 ...
How do I fix an ioreg Error In My Python App Code?
I am getting the following error message when I run the code for my dash app on Pyto on an iPad. Everything else appears to be working fine, but I can't figure out the solution to this error. I have io imported and image files are going through a standard base 64 function to encode them as follows. def b64_image(image_...
[ "Your traceback is not actually indicating a problem with this function. Its a warning that you did not close the images.\nConsider:\ndef b64_image(image_file):\n with open(image_file,'rb') as image_data:\n\n encoded = base64.b64encode(image_data.read())\n return 'data:image/png;base64,{}'.format(e...
[ 0 ]
[]
[]
[ "error_handling", "io", "ipad", "plotly_dash", "python" ]
stackoverflow_0074448376_error_handling_io_ipad_plotly_dash_python.txt
Q: Python How to break loop with 0 I don't understand why is not working on my code def random_calculation(num): return((num*77 + (90+2-9+3))) while random_calculation: num = int(input("Pleace enter number: ")) if num == "0": break else: print(random_calculation(num)) Can you guide m...
Python How to break loop with 0
I don't understand why is not working on my code def random_calculation(num): return((num*77 + (90+2-9+3))) while random_calculation: num = int(input("Pleace enter number: ")) if num == "0": break else: print(random_calculation(num)) Can you guide me what is wrong here, i really dont ...
[ "You have several errors in your code:\nYou cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.\nAlso, you are converting the input to int, but then comparing agains the string \"0\" instead of...
[ 1, 0 ]
[]
[]
[ "break", "python", "while_loop" ]
stackoverflow_0074448608_break_python_while_loop.txt
Q: shutil.move PermissionError: [WinError 5] Access is denied Hi i tried to move some local files to a nas but it raises an Access is denied error. I have compiled the script to .exe file with auto-py-to-exe. I tried to set some rights to the local folder but it didn't work. Run the script with adminrights but now i ...
shutil.move PermissionError: [WinError 5] Access is denied
Hi i tried to move some local files to a nas but it raises an Access is denied error. I have compiled the script to .exe file with auto-py-to-exe. I tried to set some rights to the local folder but it didn't work. Run the script with adminrights but now i haven't rights on the nas, the rights on the nas i can't change....
[ "Your path to file flips the '/' to '\\' at the filename. You can use 'r' in front of file names to ensure the slashes are maintained\nhttps://docs.python.org/3/reference/lexical_analysis.html#:~:text=Both%20string%20and,is%20not%20supported.\n" ]
[ 0 ]
[]
[]
[ "python", "shutil" ]
stackoverflow_0074448652_python_shutil.txt
Q: Merge List in Python next to the same index I have two list, i wanted to merge both the list in next to the same index with the delimiter. list1 = ['1', '2', '3', '4'] list2 = ['A', 'B', 'C', 'D'] Expected result, ['1 - A', '2 - B', '3 - C', '4 - D'] I can merge both the lists using Concatenate, append or extend...
Merge List in Python next to the same index
I have two list, i wanted to merge both the list in next to the same index with the delimiter. list1 = ['1', '2', '3', '4'] list2 = ['A', 'B', 'C', 'D'] Expected result, ['1 - A', '2 - B', '3 - C', '4 - D'] I can merge both the lists using Concatenate, append or extend methods. But not sure to concatenate with the de...
[ "Try this using zip() and list comprehension:\nlist1 = ['1', '2', '3', '4']\nlist2 = ['A', 'B', 'C', 'D']\n\n\nresult = [f'{i} - {j}' for i,j in zip(list1, list2)]\n\nthe result will be:\nOut[2]: ['1 - A', '2 - B', '3 - C', '4 - D']\n\n", "Without using zip():\n[n+' - '+list2[i] for i, n in enumerate(list1)]\n\no...
[ 2, 0 ]
[]
[]
[ "list", "merge", "python" ]
stackoverflow_0074448240_list_merge_python.txt
Q: Graphviz General Tree I can't render the whole Tree using graphviz. I am using DFS traversal. Renderd png only consits of root and 2 children of root, while the others are missing. class TreeNode: value: Any children: List['TreeNode'] def __init__(self, value:Any)->None: self.value=value ...
Graphviz General Tree
I can't render the whole Tree using graphviz. I am using DFS traversal. Renderd png only consits of root and 2 children of root, while the others are missing. class TreeNode: value: Any children: List['TreeNode'] def __init__(self, value:Any)->None: self.value=value self.children=[] def sh...
[ "I figured it out. Just had to pass dot as an argument. Here's code\ndef show(self,dot=None):\n if dot is None:\n dot=graphviz.Digraph(\"Tree\",format=\"png\")\n\n dot.node(str(self),str(self.value))\n\n if len(self.children) != 0:\n for child in self.children:\n dot.node(str(child...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074448767_python.txt
Q: Does python create a new List after 'del' in used on an element of the List? I plan to use an array as a stack for a binary tree print operation. Will it be more efficient to use Del operator to delete a node object from the list when it is printed, or sould I substitute some check symbol instead of the node objec...
Does python create a new List after 'del' in used on an element of the List?
I plan to use an array as a stack for a binary tree print operation. Will it be more efficient to use Del operator to delete a node object from the list when it is printed, or sould I substitute some check symbol instead of the node object? Is del operation efficient? After del operation does python still store the lis...
[ "Generally Python List is perfect candidate for using it as a stack.\nhttps://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks\n" ]
[ 0 ]
[]
[]
[ "data_structures", "del", "list", "processing_efficiency", "python" ]
stackoverflow_0074448759_data_structures_del_list_processing_efficiency_python.txt
Q: Transform a 2x2 array into a 2x2x2 arrays with numpy I use numpy to do image processing, I wanted to switch the image to black and white and for that I did the calculation in each cell to see the luminosity, but if i want to show it i have to transform a 2d array into 2d array with 3 times the same value for exemp...
Transform a 2x2 array into a 2x2x2 arrays with numpy
I use numpy to do image processing, I wanted to switch the image to black and white and for that I did the calculation in each cell to see the luminosity, but if i want to show it i have to transform a 2d array into 2d array with 3 times the same value for exemple i have this: a = np.array([[255,0][0,255]]) #into b = n...
[ "You'll want to us an explicit broadcast: https://numpy.org/doc/stable/reference/generated/numpy.broadcast_to.html#numpy.broadcast_to\nb = np.broadcast_to(a[..., np.newaxis], (2, 2, 3))\n\nUsually you don't need to do it explicitly, maybe try and see if just a[..., np.newaxis] and the standard broadcasting rules ar...
[ 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074445287_arrays_numpy_python.txt
Q: Viusal studio code can't run any programing language My vscode can't run any code.I've been trying to fix it for 2-3 days now but that doesn't work.I don't know it about I try to setup c/c++ in vscode about 15 days ago that time it work it can c c++ python however this few day I back to code something and have fou...
Viusal studio code can't run any programing language
My vscode can't run any code.I've been trying to fix it for 2-3 days now but that doesn't work.I don't know it about I try to setup c/c++ in vscode about 15 days ago that time it work it can c c++ python however this few day I back to code something and have found can't run any code. can anyone please suggested solutio...
[ "If you can't run any code inside VSCode it's most likely the lack of needed extensions causing the problem, you can download extensions by going to the extension menu with ctrl + shift + x and if you are connected to the internet, VSCode will show recommended extensions for you.\nAbout the problem that you can't r...
[ 1, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074448326_python_visual_studio_code.txt
Q: sticky does not work in a frame in Tkinter I tried to use sticky to make b_frame take half of a_frame , and c_frame also take half of a_frame. Each frame use half of a_frame. Sum of c_frame and b_frame will use the whole width of a_frame. But it does not work as I expected. a_frame=tk.Frame(frame, highlightbackgro...
sticky does not work in a frame in Tkinter
I tried to use sticky to make b_frame take half of a_frame , and c_frame also take half of a_frame. Each frame use half of a_frame. Sum of c_frame and b_frame will use the whole width of a_frame. But it does not work as I expected. a_frame=tk.Frame(frame, highlightbackground="red", highlightthi...
[ "You need to add a_frame.columnconfigure((0,1), weight=1) to make b_frame (in column 0) and c_frame (in column 1) to share the horizontal space of a_frame equally:\na_frame=tk.Frame(frame, highlightbackground=\"red\", highlightthickness=2)\na_frame.grid(row=3, column=0, sticky=\"nsew\", columnspan=2)\n\n# make colu...
[ 2, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074447931_python_tkinter.txt
Q: Is there a way to change the number of classes while using imagedatagenerator? I am currently working with my own dataset that has 4 classes (cat, dog, mouse, tuna) and so far I am able to classify between those 4 classes fairly good. I want now to change the problem into "Classify between Mammal and no Mammal" bu...
Is there a way to change the number of classes while using imagedatagenerator?
I am currently working with my own dataset that has 4 classes (cat, dog, mouse, tuna) and so far I am able to classify between those 4 classes fairly good. I want now to change the problem into "Classify between Mammal and no Mammal" but I cant find a way of doing so without changing the way the images are stored on ea...
[ "I was able to come to a solution and I want to post it in case someone has the same problem.\nFirst you have to forget about using \"Flow From Directory\" when creating the generator, instead use \"Flow From Dataframe\".\nTo create a dataframe you can use the following code:\nlst = list(data_train.glob(\"*/*.tiff\...
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074436812_keras_python_tensorflow.txt
Q: How to change the text of a button in tkinter inside a callback function Is it possible to change the text on a button when it is pressed, even when there are lots of buttons using the same callback command? button1 = Button(self, text="1", command=self.getPressed) button2 = Button(self, text="2", command=self.get...
How to change the text of a button in tkinter inside a callback function
Is it possible to change the text on a button when it is pressed, even when there are lots of buttons using the same callback command? button1 = Button(self, text="1", command=self.getPressed) button2 = Button(self, text="2", command=self.getPressed) button1.grid(row=0, column=0) button2.grid(row=0, column=1) def get...
[ "I know this answer comes 4 years after the question but maybe someone will find this solution useful. What can be done is to use partial function with a reference to the button and button.update(command=...) to set the command after the button is created.\nThis way we avoid creating a separate list with buttons an...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0052915501_python_python_3.x_tkinter.txt
Q: Python List comprehension error in Github-Actions I need to create a list from input passed as command line argument to python script. Input contains items separated by either comma or space. I am using list comprehension & filter to get desired output in list containing each items/elements without comma or space....
Python List comprehension error in Github-Actions
I need to create a list from input passed as command line argument to python script. Input contains items separated by either comma or space. I am using list comprehension & filter to get desired output in list containing each items/elements without comma or space. When using Python List comprehension on Github-Actions...
[ "Looks like the order of your list comprehension is wrong, to reproduce -\n>>> issueLinks = ['GBSAP-20628,GBSAP-20029']\n>>> list(filter(None, [subitem for subitem in item.split(',') for item in issueLinks]))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'item' is not...
[ 1 ]
[]
[]
[ "github_actions", "python" ]
stackoverflow_0074448537_github_actions_python.txt
Q: Why is my return function not allowing me to call the code I was creating an if-else loop based on the type of variable, to either convert a list of numbers to kilograms, or simply one number, and for some reason I cannot call the variable I created into my main() function. I am a beginner to python and any help w...
Why is my return function not allowing me to call the code
I was creating an if-else loop based on the type of variable, to either convert a list of numbers to kilograms, or simply one number, and for some reason I cannot call the variable I created into my main() function. I am a beginner to python and any help would be appreciated. Here is my code: # Testing Code def kgToLb...
[ "You're very close! Here's a working solution:\ndef kgToLb(weight):\n # Return the converted weight (kg)\n newWeight = []\n if type(weight) == list:\n for w in range(len(weight)):\n newWeight.append(weight[w] / 2.20462) # fix \"return\" and that you multiply. Should divide\n return new...
[ 0, 0 ]
[]
[]
[ "nameerror", "python" ]
stackoverflow_0074448782_nameerror_python.txt
Q: Convert Julian Date with Time to full datetime in pandas dataframe I have a field in a pandas data frame where I calculated the Julian date using to_julian_date() from a datetime64[ns] field and now have values like jul1 in the example below: df = pd.DataFrame({'dates':['2017-01-01 03:15:00','2017-01-01 03:15:00']...
Convert Julian Date with Time to full datetime in pandas dataframe
I have a field in a pandas data frame where I calculated the Julian date using to_julian_date() from a datetime64[ns] field and now have values like jul1 in the example below: df = pd.DataFrame({'dates':['2017-01-01 03:15:00','2017-01-01 03:15:00']}) df['dates'] = pd.to_datetime(df['dates']) df['jul1'] = pd.DatetimeIn...
[ "I stumbled across this question when trying to do the same thing myself. Turns out the solution is quite simple, but not obvious to find in the documentation. Using your example from above, I've just added the final line.\ndf = pd.DataFrame({'dates':['2017-01-01 03:15:00','2017-01-01 03:15:00']})\ndf['dates'] = pd...
[ 1 ]
[]
[]
[ "dataframe", "julian_date", "pandas", "python" ]
stackoverflow_0070292007_dataframe_julian_date_pandas_python.txt
Q: Distribute discount coupons evenly between new and old users I recently got this problem in an interview. Suppose you have 3 types of coupon: Free Shipping( To be distributed to 10% users) By one Get One (To be distributes to 10% users) Flat 10% off (To be distributed to 80%) The tasks is to find a way to distri...
Distribute discount coupons evenly between new and old users
I recently got this problem in an interview. Suppose you have 3 types of coupon: Free Shipping( To be distributed to 10% users) By one Get One (To be distributes to 10% users) Flat 10% off (To be distributed to 80%) The tasks is to find a way to distribute the coupons such that in every checkout the user is provided ...
[ "There are two major options: randomized approach and deterministic one.\nRandomized approach would use a distribution function to decide which coupon to assign to a given user. The challenge is to make this function fair and meet 10/10/80 numbers.\nA simple way to create a good distribution is to use hashing. For ...
[ 1 ]
[]
[]
[ "math", "probability", "python", "system_design" ]
stackoverflow_0074445141_math_probability_python_system_design.txt
Q: What does if x: mean in Python I have the following code segment in python if mask & selectors.EVENT_READ: recv_data = sock.recv(1024) if recv_data: data.outb += recv_data else: print(f"Closing connection to {data.addr}") Would I read this as: 'if mask and selectos.EVENT_READ are ...
What does if x: mean in Python
I have the following code segment in python if mask & selectors.EVENT_READ: recv_data = sock.recv(1024) if recv_data: data.outb += recv_data else: print(f"Closing connection to {data.addr}") Would I read this as: 'if mask and selectos.EVENT_READ are equivalent:' And similarly: 'if rec...
[ "For the second assumptions, yes.\nif var_name: is shorthand of saying if var_name evaluates to a truthy value.\nYour first assumption is wrong though, a logical AND operation in python is actually and, not & - many languages do use an ampersand as a logical and, but this is usually a double ampersand, as in &&. A ...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x", "sockets" ]
stackoverflow_0074448946_python_python_3.x_sockets.txt
Q: Is it possible to add lists inside a list? I created 2 lists in python ` ls = [] a = ['a','b','c','d','e','f'] i = 0 while i < 5: x = a[-1] a.pop(-1) a.insert(0, x) ls.insert(0, a) i += 1 print(ls) What I want to do is to add something from the list filled with letters into an empty list an...
Is it possible to add lists inside a list?
I created 2 lists in python ` ls = [] a = ['a','b','c','d','e','f'] i = 0 while i < 5: x = a[-1] a.pop(-1) a.insert(0, x) ls.insert(0, a) i += 1 print(ls) What I want to do is to add something from the list filled with letters into an empty list and making the result look like this ls = [ ['a','...
[ "The list is a mutable object in python, so when you insert the list a in the ls, you are just adding a reference to the list a, instead of adding the whole value.\nA workaround would be to insert a copy of a in the ls. One way to create a new copy of the list is using the list() on the list or you can use copy fun...
[ 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074448990_list_python.txt
Q: Why is my flask application following the error route? I am trying to write a code (CS50) that uses flask and HTML and I am supposed to create a server where you can input your name as well as a provided option. After this, the results are displayed in a table, the file is called registration.html, (using HTML) as...
Why is my flask application following the error route?
I am trying to write a code (CS50) that uses flask and HTML and I am supposed to create a server where you can input your name as well as a provided option. After this, the results are displayed in a table, the file is called registration.html, (using HTML) as well as recorded in a SQL database. This is the code for ap...
[ "<input name=\"option\" type=\"checkbox\" value=\"'{{option}}\">{{option}}\n\nYou have an extra single-quote inside value=. So the actual value being returned is e.g. 'Stochastic Calculus which does not match any value in the OPTIONS list.\nAlso you don't have a closing </option> tag.\n" ]
[ 2 ]
[]
[]
[ "flask", "html", "python" ]
stackoverflow_0074448992_flask_html_python.txt
Q: Can't find length of Dataframe Error: Float object can't be called So I have a Pandas Dataframe and I am trying to find the length of said data frame to split it in half. However when using the code half_df = len(df) // 2 I get the error: TypeError: 'float' object is not callable I can't seem to get my head around...
Can't find length of Dataframe Error: Float object can't be called
So I have a Pandas Dataframe and I am trying to find the length of said data frame to split it in half. However when using the code half_df = len(df) // 2 I get the error: TypeError: 'float' object is not callable I can't seem to get my head around the problem. Shouldn't the Pandas data frame be a Dataframe and not a f...
[ "It appears that you have redefined the builtin len() function, assigning the name len to a float. That is, you must have done something like this earlier in your code:\nlen = 5.0\n\nWhen you later write len(df), Python tries to call the float that has been assigned to len, but floats are not callable, and so it ra...
[ 2 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074448949_numpy_pandas_python.txt
Q: Pandas .to_csv taking long to save relatively large dataframe? My df is ~4 GB in memory, of float16 dtype columns. I am trying to save to a CSV file using pd.to_csv but it is taking excessively long for a not-too-large data frame. Any help is appreciated. A: float16 is a pretty dense data type - each floating po...
Pandas .to_csv taking long to save relatively large dataframe?
My df is ~4 GB in memory, of float16 dtype columns. I am trying to save to a CSV file using pd.to_csv but it is taking excessively long for a not-too-large data frame. Any help is appreciated.
[ "float16 is a pretty dense data type - each floating point number is stored in 16 bits, or 2 bytes.\nAssuming the entire data frame is float16, that would mean your data frame has roughly 2,000,000 numbers in it.\nBy contrast, an ASCII character is 1 byte, and a floating point number of unspecified precision often ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074448516_pandas_python.txt
Q: Create MS Access database from a Python app I'm working with Python and interacting with a MS Access database via the JayDeBeApi library. Everything works well, I can create tables and all but the file *.accdb need to be created previously in the MS Access software Is there a way to dynamically create the *.accdb ...
Create MS Access database from a Python app
I'm working with Python and interacting with a MS Access database via the JayDeBeApi library. Everything works well, I can create tables and all but the file *.accdb need to be created previously in the MS Access software Is there a way to dynamically create the *.accdb file via my Python code?
[ "You can use the msaccessdb package to create the .accdb file.\n(I am the maintainer of that package.)\n" ]
[ 3 ]
[]
[]
[ "database", "jaydebeapi", "ms_access", "python" ]
stackoverflow_0074447560_database_jaydebeapi_ms_access_python.txt
Q: Pandas: randomly select a row based on a group of two columns I have a table like the following: id color type category age location 123 red civic single 21 california 456 red civic family 35 michigan 603 red civic single 32 seattle 673 blue rav4 single 23 toranto 897 blue rav4 family 54 texas 578 black rav...
Pandas: randomly select a row based on a group of two columns
I have a table like the following: id color type category age location 123 red civic single 21 california 456 red civic family 35 michigan 603 red civic single 32 seattle 673 blue rav4 single 23 toranto 897 blue rav4 family 54 texas 578 black rav4 family 63 california What I need to do is to keep ...
[ "You can do a simple .groupby().sample and pass in 1 to retrieve a single observation from each group.\nprint(df.groupby(['color', 'type']).sample(1))\n id color type category age location\n5 578 black rav4 family 63 california\n3 673 blue rav4 single 23 toranto\n0 123 red civic...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074449057_dataframe_pandas_python.txt
Q: How to get key value by another key value of dict I am trying to get hero name by hero id for my program. Let's assume that I have an array with hero ids: hero_ids = [1, 15, 27, 44, 135] and a dict with a list of dicts with hero information: { "heroes": [ { "name": "hero1", "id"...
How to get key value by another key value of dict
I am trying to get hero name by hero id for my program. Let's assume that I have an array with hero ids: hero_ids = [1, 15, 27, 44, 135] and a dict with a list of dicts with hero information: { "heroes": [ { "name": "hero1", "id": 1, }, { "name": "hero2", ...
[ "You can use list comprehension -\ndata = {\n \"heroes\": [\n {\n \"name\": \"hero1\",\n \"id\": 1,\n },\n {\n \"name\": \"hero2\",\n \"id\": 2,\n },\n {\n \"name\": \"hero3\",\n \"id\": 3,\n }]\n}\nhero_i...
[ 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074447452_dictionary_list_python.txt
Q: How to find index in a matrix using another list as a reference using Numpy? Let A be a matrix: A = array([[0. , 0. , 0. , ..., 0. , 0. , 0. ], [0. , 0.28867513, 0.28867513, ..., 0. , 0. , 0. ], [0. , 0. , 0. ,...
How to find index in a matrix using another list as a reference using Numpy?
Let A be a matrix: A = array([[0. , 0. , 0. , ..., 0. , 0. , 0. ], [0. , 0.28867513, 0.28867513, ..., 0. , 0. , 0. ], [0. , 0. , 0. , ..., 0. , 0. , 0. ], [0. , 0. , 0. ...
[ "numpy.all has a axis input so you can check if a row/column is all True. To get the index of the row you can use np.where\nnp.where(np.all(A==B, axis=1))\n\n", "With your original example\nIn [436]: A = [[0, 1, 2, 3],\n ...: [4, 5, 6, 7],\n ...: [8, 9, 10, 11]]\n ...: \n ...: B = [2, 5,...
[ 1, 0 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0074430656_matrix_numpy_python.txt
Q: Multiple Server Actions in Odoo 8 I'm adding a new server action to my Odoo, but is not working ok. It's supposed to check the n selected items, but only is checking the first one. What I'm missing? XML <record id="action_server_validate" model="ir.actions.server"> <field name="name">Validate / Unvalidate</fi...
Multiple Server Actions in Odoo 8
I'm adding a new server action to my Odoo, but is not working ok. It's supposed to check the n selected items, but only is checking the first one. What I'm missing? XML <record id="action_server_validate" model="ir.actions.server"> <field name="name">Validate / Unvalidate</field> <field name="type">ir.actions...
[ "object is a record on which the action is triggered if there is one, otherwise None (In your example above it should be the last item)\nYou probably couldn't use records because of the following error:\n ValueError: \"name 'records' is not defined\n\nThe available locals are:\n\ntime, datetime, dateutil: Python li...
[ 1, 0 ]
[]
[]
[ "odoo", "odoo_8", "python" ]
stackoverflow_0074439065_odoo_odoo_8_python.txt
Q: Python + pdfkit: Generate stream with pdfkit I'm trying to use pdfkit to turn html pages into PDFs, and then return a stream of that PDF as this code is a Flask API called by a webpage. As far as I can tell, when you use pdfkit.from_file, you have provide both an input and output path: pdfkit.from_file("input.html...
Python + pdfkit: Generate stream with pdfkit
I'm trying to use pdfkit to turn html pages into PDFs, and then return a stream of that PDF as this code is a Flask API called by a webpage. As far as I can tell, when you use pdfkit.from_file, you have provide both an input and output path: pdfkit.from_file("input.html", "output.pdf") The problem is, I don't want to ...
[ "Upgrading to 1.0.0 of pdfkit solved my problem. At that point, the output file is an optional parameter. If you are on an earlier version like I was (0.6.1), if you just provided False instead of a file, it will work the same as 1.0.0.\nRegardless of your version, when you call it as above the file is returned as ...
[ 0 ]
[]
[]
[ "flask", "pdfkit", "python" ]
stackoverflow_0074438277_flask_pdfkit_python.txt
Q: How to formulate a constraint to order the items in ascending order in PuLP? I am using the PuLP package to solve a bin-packing problem and I wanted to formulate a constraint to group the items based on days in ascending order. Below is the code snippet that is giving us the results which are not desired. from ite...
How to formulate a constraint to order the items in ascending order in PuLP?
I am using the PuLP package to solve a bin-packing problem and I wanted to formulate a constraint to group the items based on days in ascending order. Below is the code snippet that is giving us the results which are not desired. from itertools import product import pandas as pd import pulp df = pd.DataFrame([["item0"...
[ "You can do this by cleverly using the bin number/days as a penalty in your objective function. (See the modified objective below.)\nThis will incentivize putting low-day items in low number bins.\nRealize, you may discover corner cases that might use an extra bin because of this penalty, so you might need to tink...
[ 1 ]
[]
[]
[ "linear_programming", "optimization", "pulp", "python" ]
stackoverflow_0074448474_linear_programming_optimization_pulp_python.txt
Q: PyQt6 QTableWidgetItem Change Background Color if Value Changes After creating a custom QLabel class that opens a QInputDiaglog popup when double clicked to change the value displayed in the cell, I realized that a QTableWidgetItem can be double clicked to edit its value. I prefer this over the popup from a user p...
PyQt6 QTableWidgetItem Change Background Color if Value Changes
After creating a custom QLabel class that opens a QInputDiaglog popup when double clicked to change the value displayed in the cell, I realized that a QTableWidgetItem can be double clicked to edit its value. I prefer this over the popup from a user perspective. I need to add a new property "init_val" and override a me...
[ "Using the table's itemChanged signal as @musicamante suggested I got it to work. This is so much easier than the way I tried before.\nfrom PyQt6.QtWidgets import QApplication, QWidget, QTableWidget, QTableWidgetItem, QHBoxLayout, QVBoxLayout, QHeaderView, QPushButton, QScrollArea, QLabel, QMainWindow, QInputDialog...
[ 0 ]
[]
[]
[ "pyqt", "pyqt6", "python" ]
stackoverflow_0074448082_pyqt_pyqt6_python.txt
Q: Yield a list of matching elements from 2 different lists I have a (somewhat long) list of words. And a function 1 (linsok(lista, elem)) which asks the user for a word, and if the user-inputted word exists in the list, we get a confirmation in the form of exists/does not exist. I then have a 2nd function which for ...
Yield a list of matching elements from 2 different lists
I have a (somewhat long) list of words. And a function 1 (linsok(lista, elem)) which asks the user for a word, and if the user-inputted word exists in the list, we get a confirmation in the form of exists/does not exist. I then have a 2nd function which for any word in the list will create 4 variations of it (creating ...
[ "Your explanation is a little unclear but here goes.\nAssuming concantenation as in your function is correct.\ncat -> [(catc),(catca),(catcat)]\nYou can simply use a dict to save a lot of time.\ndef kupering(ord,mydict):\n nylista = []\n if ord in lista:\n for i in range(min(len(ord),3)):\n ...
[ 0, 0 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0074448753_function_list_python.txt
Q: Validate dataframe dates, return non-matching values This is the workflow I need to accomplish: Validate the date format of all dates in column_1 and column_2. If date is not in either format: mm/dd/yy hh:mm or mm/dd/yyyy hh:mm Need assistance - Print the non-matching values. Note: I do not know what format the ...
Validate dataframe dates, return non-matching values
This is the workflow I need to accomplish: Validate the date format of all dates in column_1 and column_2. If date is not in either format: mm/dd/yy hh:mm or mm/dd/yyyy hh:mm Need assistance - Print the non-matching values. Note: I do not know what format the dates will be in and some will not be dates at all. Sample...
[ "You'll need to test each allowed format individually (they're all in the same try block at the moment, in the example given in the question). A general solution could make use of masking values that cannot be converted by any of the formats. That could look like\nimport pandas as pd\n\nallowed = ('%m/%d/%y %H:%M',...
[ 1, 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python", "validation" ]
stackoverflow_0074448566_dataframe_datetime_pandas_python_validation.txt