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: Is there a way to access a block of elements in a dataframe? I have a 2 dimensional dataframe with 1000 rows and columns. I am hoping to access blocks of the dataframe such as a square from row 100:200 and column 100:200. Block will look like this. Tried using a for loop in a for loop to loop through every elemen...
Is there a way to access a block of elements in a dataframe?
I have a 2 dimensional dataframe with 1000 rows and columns. I am hoping to access blocks of the dataframe such as a square from row 100:200 and column 100:200. Block will look like this. Tried using a for loop in a for loop to loop through every element and append to a new df. Was far too slow and am hoping that ther...
[ "df.iloc[100:200,100:200] works. oops\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074395717_dataframe_pandas_python.txt
Q: Console Screen printing bug at max line with escape code to set Cursor's position simplified code, original _ could be more than 2 length import msvcrt import os os.system(f'mode con: cols={100} lines={10}') _='' while True: print('\r'+' '*9+f'{_}') print('TypeHere:\0337',end='\r') print('\n\0338',end...
Console Screen printing bug at max line with escape code to set Cursor's position
simplified code, original _ could be more than 2 length import msvcrt import os os.system(f'mode con: cols={100} lines={10}') _='' while True: print('\r'+' '*9+f'{_}') print('TypeHere:\0337',end='\r') print('\n\0338',end='') _=msvcrt.getwch() when line is over max cmd size(10), bug(?) occurs. It see...
[ "Save/restore cursor save/restore the row/column on the screen. Scrolling doesn't affect that (your text moved, but the screen did not).\n" ]
[ 0 ]
[]
[]
[ "ansi_escape", "console", "escaping", "python", "shell" ]
stackoverflow_0074384724_ansi_escape_console_escaping_python_shell.txt
Q: Why is year 1900 not returning False? def is_leap_year(year): if (year%4==0 & (year%100!=0)) | (year%4==0 & year%100==0 & year%400==0): return True else: return False print(is_leap_year(1900)) I would like for the argument (1900) to yield a False, since both sides of the or ( | ) statement...
Why is year 1900 not returning False?
def is_leap_year(year): if (year%4==0 & (year%100!=0)) | (year%4==0 & year%100==0 & year%400==0): return True else: return False print(is_leap_year(1900)) I would like for the argument (1900) to yield a False, since both sides of the or ( | ) statement fails to be true. What am I missing? This ...
[ "Try\ndef is_leap_year(year):\n if (year%4==0 and year%100!=0) or (year%4==0 and year%100==0 and year%400==0):\n return True\n else:\n return False\nprint(is_leap_year(1900))\n\n& and | are bitwise AND and OR respectively, not logical operators.\n" ]
[ 1 ]
[]
[]
[ "boolean_expression", "python" ]
stackoverflow_0074395823_boolean_expression_python.txt
Q: Tuple data keeps reverting after being changed from a list I am currently trying to change the value of Job in a tuple. I initially converted it to a list in order to do so, but after converting it back to a tuple and then calling a function to display the tuple, it still shows the original data. x = [('Rae', 31, ...
Tuple data keeps reverting after being changed from a list
I am currently trying to change the value of Job in a tuple. I initially converted it to a list in order to do so, but after converting it back to a tuple and then calling a function to display the tuple, it still shows the original data. x = [('Rae', 31, 'Student'), ('Anna', 30, 'Nurse')] print(x) def show_info...
[ "Don't make a copy of x. Just assign a new tuple to the element of x that you want to replace.\ndef change_job(newJob, x):\n name = x[0][0]\n age = x[0][1]\n \n x[0] = (name, age, newJob)\n print(\"Tuple: \", x[0])\n\n" ]
[ 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0074395867_list_python_tuples.txt
Q: How do I add different IPTC keywords to multiple images? I have a folder containing thousands of images and each image needs a unique list of keywords added to it. I also have a table with fields showing the file path and associated list of desired keywords for each image. For example, one record might need the ta...
How do I add different IPTC keywords to multiple images?
I have a folder containing thousands of images and each image needs a unique list of keywords added to it. I also have a table with fields showing the file path and associated list of desired keywords for each image. For example, one record might need the tags, "ORASH (a survey site code), Crew 1, Transect A Upstream, ...
[ "I saved the table with the filenames and keywords as a .csv file where the fields and records looked like this (though the text in the 'Subject' field didn't include the quotes):\n\nSourceFile, Artist, Subject\nE:\\photos\\0048.JPG, MARY GRAY, \"YEAR2022, REQUIRED, GPS UNIT WITH\nTIME\"\n\nBecause I use Jupyter ...
[ 1 ]
[]
[]
[ "exiftool", "image_processing", "iptc", "metadata", "python" ]
stackoverflow_0074295451_exiftool_image_processing_iptc_metadata_python.txt
Q: Python TypeError: main() takes 0 positional arguments but 1 was given. Cloud function I am trying to run a cloud function that pulls in data via the search analytics API. I've tested the code in both a Jupyter and Colab notebook. It runs in both just fine. However, when I deploy as a cloud function in Google Cloud...
Python TypeError: main() takes 0 positional arguments but 1 was given. Cloud function
I am trying to run a cloud function that pulls in data via the search analytics API. I've tested the code in both a Jupyter and Colab notebook. It runs in both just fine. However, when I deploy as a cloud function in Google Cloud I get the following error: TypeError: main() takes 0 positional arguments but 1 was given ...
[ "Google Cloud Functions entry point must take an argument (a request object) as shown here.\nIf you don't want to use the argument, you can ignore it like this:\ndef main(_):\n # ...\n\nIf you want it to be optional, you can use:\ndef main(*args, **kwargs):\n # ...\n\n" ]
[ 1 ]
[]
[]
[ "google_cloud_functions", "google_cloud_platform", "google_cloud_storage", "pandas", "python" ]
stackoverflow_0074389046_google_cloud_functions_google_cloud_platform_google_cloud_storage_pandas_python.txt
Q: Convert google script (*.gs) file to Python I have found an interesting google script file, but would like to change it a bit to run it locally on my system. Locally I use Python. How can this be easily converted or to which language is it comparable? The script is generating a new presentation with a specific sli...
Convert google script (*.gs) file to Python
I have found an interesting google script file, but would like to change it a bit to run it locally on my system. Locally I use Python. How can this be easily converted or to which language is it comparable? The script is generating a new presentation with a specific slide template (shape). This part raises the most qu...
[ "If you are looking \"easy\" options, keep using Google Apps Script.\n\nGoogle Apps Script uses JavaScript as programming language and has several services that make it convenient to automate Google apps like Google Slides.\nIn order to minimize the convertion work, you might create a web app using Google Apps Scri...
[ 1 ]
[]
[]
[ "google_apps_script", "javascript", "python" ]
stackoverflow_0074395466_google_apps_script_javascript_python.txt
Q: Generate combinations by randomly selecting a row from multiple groups (using pandas) I have a pandas dataframe df which appears as following: (toy version below but the real df contains many more columns and groups) group sub fruit a 1 apple a 2 banana a 3 orange b 1 pear b ...
Generate combinations by randomly selecting a row from multiple groups (using pandas)
I have a pandas dataframe df which appears as following: (toy version below but the real df contains many more columns and groups) group sub fruit a 1 apple a 2 banana a 3 orange b 1 pear b 2 strawberry b 3 cherry c 1 kiwi c 2 tomato c 3 lemon A...
[ "You can use itertools.product on the groups of indices:\nfrom itertools import product\n\nout = pd.concat({i: df.loc[list(idx)] for i, idx in\n enumerate(product(*df.index.groupby(df['group']).values()), start=1)})\n\noutput:\n group sub fruit\n1 0 a 1 apple\n 3 b 1 pea...
[ 0 ]
[]
[]
[ "combinations", "pandas", "python" ]
stackoverflow_0074395879_combinations_pandas_python.txt
Q: Import local python file to Jupyter Notebook I need to import a few python files stored in my local memory as modules in my Jupyter Notebook. My jupyter notebook is store in C:\snip\Pictures\demo and I need to import python files stored in C:\snip\Pictures\demo\mrcnn. When I try this: from mrcnn import utils from ...
Import local python file to Jupyter Notebook
I need to import a few python files stored in my local memory as modules in my Jupyter Notebook. My jupyter notebook is store in C:\snip\Pictures\demo and I need to import python files stored in C:\snip\Pictures\demo\mrcnn. When I try this: from mrcnn import utils from mrcnn import visualize from mrcnn.visualize import...
[ "What you are doing works with using .py files, but Jupyter files are a bit different. You need to import modules by adding %run \nIf you wish to also use the variables in the py file, use %run -i.\n", "Do this. Print the sys.path like this. This lists the directories that the python interpreter is looking insid...
[ 2, 0, 0, 0 ]
[]
[]
[ "anaconda", "import", "jupyter_notebook", "python", "python_3.x" ]
stackoverflow_0068994934_anaconda_import_jupyter_notebook_python_python_3.x.txt
Q: authorize.net creating customer profile from transaction I'm currently charging a customer and then trying to create a customer profile based on that charge. The problem is that when I try and actually create the customer it fails, telling me that there is no response and instead prints out ` AttributeError: no ...
authorize.net creating customer profile from transaction
I'm currently charging a customer and then trying to create a customer profile based on that charge. The problem is that when I try and actually create the customer it fails, telling me that there is no response and instead prints out ` AttributeError: no such child: {AnetApi/xml/v1/schema/AnetApiSchema.xsd}custome...
[ "Having the same problem in C# SDK. Diving into this it states an error message: \"Customer profile creation failed. This payment method does not support profile creation.\" So I'm guessing you can't make a payment profile from opaque card data! :(\n", "One thing I was able to do. Create a Transaction with the...
[ 0, 0 ]
[]
[]
[ "authorize.net", "python" ]
stackoverflow_0046186998_authorize.net_python.txt
Q: Python. How to constrain the particles to only move on the surface of the sphere? I am using vpython to simulate the movement of the particles on the sphere when repelled by other particles located on a plate below the sphere. I calculate each force using the following code. for i in range(len(charOS)): #COS ...
Python. How to constrain the particles to only move on the surface of the sphere?
I am using vpython to simulate the movement of the particles on the sphere when repelled by other particles located on a plate below the sphere. I calculate each force using the following code. for i in range(len(charOS)): #COS for j in range(len(charges_on_plate)): #COP d = sqrt((charOS[i].pos.x - charges_...
[ "I have finally found an answer. In fact, it is fairly easy, at first I allow the new position to be calculated outside the sphere radius and then I can perform a vector normalization by dividing each vector x, y, z by the magnitude of the vector. This gives a unit vector and then finally the unit vector is multipl...
[ 1 ]
[]
[]
[ "for_loop", "physics", "python", "simulation", "vector" ]
stackoverflow_0074371866_for_loop_physics_python_simulation_vector.txt
Q: How to open a new pyghmi Session via pyghmi.impi.command.Command after the previous one has timed out? I'm having some issues with the pyghmi python library, which is used for sending IPMI commands with python scripts. My goal is to implement an HTTP API to send IPMI commands through HTTP requests. I am already ab...
How to open a new pyghmi Session via pyghmi.impi.command.Command after the previous one has timed out?
I'm having some issues with the pyghmi python library, which is used for sending IPMI commands with python scripts. My goal is to implement an HTTP API to send IPMI commands through HTTP requests. I am already able to create a Session and send a few commands with the library, but if the Session remains IDLE for 30 seco...
[ "So I finally achieved a sort of solution. I emailed the Pyghmi's main contributor and he said that this lib was not suited for a multi- and reuseable- Session implementation (there is currently an open issue \"Session reuse\" on Pyghmi repository).\nFirst \"solution\": use processes\nMy goal was to create an HTTP ...
[ 1, 1 ]
[]
[]
[ "ipmi", "openstack", "python" ]
stackoverflow_0066637872_ipmi_openstack_python.txt
Q: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')) I tried to scrape some data on booking.com but I've got this error : requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.booking.com%0a', port=443): Max retries exceeded with url: /hotel/fr/elyseesunion.fr.html?label=gen173nr-...
Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
I tried to scrape some data on booking.com but I've got this error : requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.booking.com%0a', port=443): Max retries exceeded with url: /hotel/fr/elyseesunion.fr.html?label=gen173nr-1FCA0oTUIMZWx5c2Vlc3VuaW9uSA1YBGhNiAEBmAENuAEXyAEM2AEB6AEB-AECiAIBqAIDuAL_5ZqEB...
[ "I am using requests_html Library. Use this doc link.\nTry This Code Snippet. It worked for me. It is scraping the page and storing it in an HTML page.\n\nfrom requests_html import HTMLSession\n\nsession = HTMLSession()\n\nurl = \"https://www.booking.com/searchresults.en-gb.html?label=gen173nr-1FCA0oTUIMZWx5c2Vlc3V...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x", "web_scraping" ]
stackoverflow_0067567668_beautifulsoup_python_python_3.x_web_scraping.txt
Q: Selenium not updating current window Selenium seems to be looking for data in an old page and not the new one. I'm trying to automate a search where I select from a dropdown menu and fill a box with some value from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.co...
Selenium not updating current window
Selenium seems to be looking for data in an old page and not the new one. I'm trying to automate a search where I select from a dropdown menu and fill a box with some value from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver....
[ "This happens because you getting the data = driver.find_element(By.XPATH, \"//div[@id='content_column']\") immediately after clicking the Enter. The page still not refreshed. You should add a short delay there and then wait for element visibility on the refreshed page.\nPlease try this:\nfrom selenium import webdr...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074395953_python_selenium_selenium_chromedriver_selenium_webdriver_webdriverwait.txt
Q: Asyncio Server with Timer in python I'm using asyncio to run a straightforward server and a client. The server is a simple echo server with two "special" commands sent by the client, "quit" and "timer". The quit command closes the connection, and the timer command starts a timer that will print a message in the co...
Asyncio Server with Timer in python
I'm using asyncio to run a straightforward server and a client. The server is a simple echo server with two "special" commands sent by the client, "quit" and "timer". The quit command closes the connection, and the timer command starts a timer that will print a message in the console (server and client) every second. T...
[ "I slightly updated your server code: removed the await timertask line (this task never ends, can be only canceled):\nServer.py\nimport asyncio\nimport time\n\nHOST = \"127.0.0.1\"\nPORT = 9999\n\n\nasync def timer():\n while True:\n print(\"tick\")\n await asyncio.sleep(1)\n\n\nasync def handle_ec...
[ 2 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074395835_python_python_asyncio.txt
Q: How to let myprogram.py use venv without setting any envs beforehand? I'm a newbie to python(3), but not to programming in general. I'd like to distribute a git repo with myprogram consisting of these files: requirements.txt myprogram.py lib/modulea.py lib/moduleb.py My question is: What is the best-practice and ...
How to let myprogram.py use venv without setting any envs beforehand?
I'm a newbie to python(3), but not to programming in general. I'd like to distribute a git repo with myprogram consisting of these files: requirements.txt myprogram.py lib/modulea.py lib/moduleb.py My question is: What is the best-practice and least surprising way to let users run myprogram.py using the dependencies ...
[ "Expanding @sinoroc's comment into an answer:\nI've looked at https://packaging.python.org/en/latest/tutorials/packaging-projects/ and also at \"entrypoints\", and this is the smallest example I can think of. Create an empty directory with these two files:\npyproject.toml:\n[build-system]\nrequires = [\"hatchling\"...
[ 1, 0 ]
[]
[]
[ "python", "python_venv" ]
stackoverflow_0074353627_python_python_venv.txt
Q: How to fix "DeprecationWarning: DataFrames with non-bool types result in worse computationalperformance..." I have been trying to implement the Apriori Algorithm in python. There are several examples online, they all use similar methods and mostly the same example dataset. The reference link: https://www.kaggle.co...
How to fix "DeprecationWarning: DataFrames with non-bool types result in worse computationalperformance..."
I have been trying to implement the Apriori Algorithm in python. There are several examples online, they all use similar methods and mostly the same example dataset. The reference link: https://www.kaggle.com/code/rockystats/apriori-algorithm-or-market-basket-analysis/notebook (starting from the line [26]) I have a dif...
[ "I ran into the same issue even after converting my dataframe fields to 0 and 1.\nThe fix was just making sure the apriori module knows the dataframe is of boolean type, so in your case you should run this :\n frequent_itemsets = apriori(basket_sets.astype('bool'), min_support=0.07, use_colnames=True)\n\n\nIn ad...
[ 1 ]
[]
[]
[ "apriori", "dataframe", "pandas", "python" ]
stackoverflow_0074114745_apriori_dataframe_pandas_python.txt
Q: Numpy Vector (N,1) dimension -> (N,) dimension conversion I have a question regarding the conversion between (N,) dimension arrays and (N,1) dimension arrays. For example, y is (2,) dimension. A=np.array([[1,2],[3,4]]) x=np.array([1,2]) y=np.dot(A,x) y.shape Out[6]: (2,) But the following will show y2 to be (2...
Numpy Vector (N,1) dimension -> (N,) dimension conversion
I have a question regarding the conversion between (N,) dimension arrays and (N,1) dimension arrays. For example, y is (2,) dimension. A=np.array([[1,2],[3,4]]) x=np.array([1,2]) y=np.dot(A,x) y.shape Out[6]: (2,) But the following will show y2 to be (2,1) dimension. x2=x[:,np.newaxis] y2=np.dot(A,x2) y2.shape O...
[ "reshape works for this\na = np.arange(3) # a.shape = (3,)\nb = a.reshape((3,1)) # b.shape = (3,1)\nb2 = a.reshape((-1,1)) # b2.shape = (3,1)\nc = b.reshape((3,)) # c.shape = (3,)\nc2 = b.reshape((-1,)) # c2.shape = (3,)\n\nnote also that reshape doesn't copy the data unless it needs to for...
[ 54, 22, 5, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0017869840_arrays_numpy_python.txt
Q: Sorting Lists in a lexicographical way using priority queues I have been trying to sort a group of lists in a lexicographical way using priority queues which are constructed using linked lists. the priorities are the elements of the lists for example: A=[1,70,60] B=[0,100,100] C=[1,70,70] D=[1,80,30] suppose that...
Sorting Lists in a lexicographical way using priority queues
I have been trying to sort a group of lists in a lexicographical way using priority queues which are constructed using linked lists. the priorities are the elements of the lists for example: A=[1,70,60] B=[0,100,100] C=[1,70,70] D=[1,80,30] suppose that A,B,C,D are four college students applying for a job, and suppos...
[ "The problem is that in the second while loop you should not continue the loop when current.att is no longer the same as node.att. That while loop is intended to break a tie when those are the same.\nFor similar reasons the third loop should only continue when both the att and fin attributes are the same for curren...
[ 0 ]
[]
[]
[ "linked_list", "priority_queue", "python" ]
stackoverflow_0074381274_linked_list_priority_queue_python.txt
Q: How do I create an API that counts the number of records containing my search criteria with data that's in JSON? I'm running Python 3.9 in a Jupyter Notebook. I'm trying to create an API that returns a count of the number of records containing my search string in the column. This column includes strings with multi...
How do I create an API that counts the number of records containing my search criteria with data that's in JSON?
I'm running Python 3.9 in a Jupyter Notebook. I'm trying to create an API that returns a count of the number of records containing my search string in the column. This column includes strings with multiple words in them, not just the term specified in the search. (https://i.stack.imgur.com/IOU3y.png) in the specified ...
[ "I discovered this, and it works when 'technology' is called. My problem was that I wasn't including or setting 'number_of_jobs' to a defined starting INT. I also had tried to use len but wasn't setting it to loop w/ +.\napi_url=\"http://127.0.0.1:5000/data\"\n\ndef get_number_of_jobs_T(technology):\n\n number_o...
[ 0 ]
[]
[]
[ "api", "json", "pandas", "python" ]
stackoverflow_0074380774_api_json_pandas_python.txt
Q: Visual Studio Code: Intellisense not working My Visual Studio Code's Intellisense is not working properly. Every time I try to use it with Ctrl + Shift, it only displays a loading message. I'm using Python (with Django) and have installed ms-python.python. I also have Djaneiro. It is still not working. What seem...
Visual Studio Code: Intellisense not working
My Visual Studio Code's Intellisense is not working properly. Every time I try to use it with Ctrl + Shift, it only displays a loading message. I'm using Python (with Django) and have installed ms-python.python. I also have Djaneiro. It is still not working. What seems to be the problem here?
[ "This can be caused by many reasons, some of them are as follows.\n\nPython executable path in vscode is incorrect\n\nSolution: Configure the path to the python executable in settings.json. Remember to restart vscode after.\n\n\nThe module is located in a non-standard location\n\nSolution: Configure settings.json ...
[ 63, 37, 14, 10, 6, 5, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ "I use this settings to have full auto-completion support. It isn't obligatory to set \"python.defaultInterpreterPath\" because you can set it from the status bar. Although if the venv is located in the same place for every developer you can set it for example to \"${workspaceFolder}/.venv/bin/python\".\n{\n // In...
[ -1 ]
[ "django", "python", "visual_studio_code" ]
stackoverflow_0050389852_django_python_visual_studio_code.txt
Q: How do I create a histogram fit for letter recognition I am trying to write a letter recognition program and display some values on a histogram. But I cannot show the number of each letter and the number on the histogram. I am using matplotlib to create a histogram. I was expecting that the histogram would show me...
How do I create a histogram fit for letter recognition
I am trying to write a letter recognition program and display some values on a histogram. But I cannot show the number of each letter and the number on the histogram. I am using matplotlib to create a histogram. I was expecting that the histogram would show me the letters as x values and the numbers as y values. but it...
[ "Assuming you're storing your data in a dictionary called let_dict with the keys the letters and the values the count of the letters. You can plot your histogram with plt.bar(let_dict.keys(), let_dict.values()) (see this SO post for more examples on how to plot the histogram of a dictionary).\nHere is the full code...
[ 0 ]
[]
[]
[ "dataframe", "histogram", "machine_learning", "matplotlib", "python" ]
stackoverflow_0074392076_dataframe_histogram_machine_learning_matplotlib_python.txt
Q: Some annoying characters are not normalised by unicodedata I have a python string that looks like as shown below. This string is from the SEC filing of one public company in the US. I am trying to remove some annoying characters from the string using unicodedata.normalise function, but this is not removing all cha...
Some annoying characters are not normalised by unicodedata
I have a python string that looks like as shown below. This string is from the SEC filing of one public company in the US. I am trying to remove some annoying characters from the string using unicodedata.normalise function, but this is not removing all characters. What could be the reason behind such behavior? from uni...
[ "Your data was decoded as ISO-8859-1 (aka latin1), but those Unicode code points are control characters in that encoding. In Windows-1252 (aka cp1252) they are so-called smart quotes:\n>>> '\\x92\\x93\\x94'.encode('latin1').decode('cp1252')\n'’“”'\n\nThey also don't change when normalized, but at least they displa...
[ 5, 2 ]
[]
[]
[ "python", "python_3.x", "python_unicode", "unicode", "unicode_normalization" ]
stackoverflow_0074396051_python_python_3.x_python_unicode_unicode_unicode_normalization.txt
Q: using LaTex in matplotlib results in: "Environment align* undefined." I'm trying to use the align* environment in matplotlib, following this thread original thread However I run into the following error: ! LaTeX Error: Environment align undefined. See the LaTeX manual or LaTeX Companion for explanation. Type H <...
using LaTex in matplotlib results in: "Environment align* undefined."
I'm trying to use the align* environment in matplotlib, following this thread original thread However I run into the following error: ! LaTeX Error: Environment align undefined. See the LaTeX manual or LaTeX Companion for explanation. Type H <return> for immediate help. ... I assume that someting do...
[ "The value in the params dictionary needs to be a string (not list of strings):\nparams= {'text.latex.preamble' : r'\\usepackage{amsmath}'}\n#instead of\n#params= {'text.latex.preamble' : [r'\\usepackage{amsmath}']}\n\n" ]
[ 0 ]
[]
[]
[ "latex", "matplotlib", "python" ]
stackoverflow_0074359796_latex_matplotlib_python.txt
Q: Looping over a dictionary keys and values for matching data I have one dictionary, with city names, and I am trying to compare if a value (city) exists in a second dictionary with more information (coordinates) and a different length. In case there's a match, it would add that information to a new dictionary based...
Looping over a dictionary keys and values for matching data
I have one dictionary, with city names, and I am trying to compare if a value (city) exists in a second dictionary with more information (coordinates) and a different length. In case there's a match, it would add that information to a new dictionary based on the information (cities) provided in the first dictionary. Th...
[ "finalDict[\"City\"] should be a list, not a dictionary. Then you can append to it.\nYou shouldn't assign to finalDict[\"City\"] inside the loop, because that will discard all the previous cities. You should append conversionDefault to the list.\nlistCities = d[\"City\"]\nfinalDict = {\"City\": [], 'POINT_X': [], '...
[ 0 ]
[]
[]
[ "dictionary", "list", "loops", "pandas", "python" ]
stackoverflow_0074396205_dictionary_list_loops_pandas_python.txt
Q: Alphabetically sorting tuples in a list using two parameters I have a list of tuples of [(city name, country name), ...]. I'm trying to sort the list alphabetically so that the country names are ordered A-Z, and then if there is more than one city in that country, the cities in that country are then also ordered a...
Alphabetically sorting tuples in a list using two parameters
I have a list of tuples of [(city name, country name), ...]. I'm trying to sort the list alphabetically so that the country names are ordered A-Z, and then if there is more than one city in that country, the cities in that country are then also ordered alphabetically. So far I've tried using sorted() with a lambda func...
[ "If I understand your question correctly, just reverse the order of elements in the key function:\nlst = [\n (\"Prague\", \"Czech Republic\"),\n (\"Bratislava\", \"Slovakia\"),\n (\"Brno\", \"Czech Republic\"),\n]\n\nprint(sorted(lst, key=lambda t: (t[1], t[0])))\n\nPrints:\n[\n (\"Brno\", \"Czech Repub...
[ 2, 1 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0074396182_list_python_tuples.txt
Q: Trying to append values to list in a loop and it appends the new value to the end but overwrites every previous value I am trying to index words from a csv in per page in a pdftext object. Everything is working fine in the reading and writing except when it goes to append the new page count to the end of the page_...
Trying to append values to list in a loop and it appends the new value to the end but overwrites every previous value
I am trying to index words from a csv in per page in a pdftext object. Everything is working fine in the reading and writing except when it goes to append the new page count to the end of the page_list. Instead of just adding the new item to the end of the list, it does that and also replaces every previous item with t...
[ "Each time through the for i in range(pages): loop you create a new, empty page_list, which you assign to the dictionary elements. So you're discarding the pages that were appended on previous iterations.\nYou need to keep the existing list in the dictionary and append to it, not crate a new list each time.\ndata =...
[ -1 ]
[]
[]
[ "append", "list", "loops", "python" ]
stackoverflow_0074396168_append_list_loops_python.txt
Q: How to print line for specific conditions using lxml in a long XML XML example as follows: <File> <Sub_Function_1> <Messages> <Setting> <Data> <Label>Setting_2</Label> <Value> <Measure> ...
How to print line for specific conditions using lxml in a long XML
XML example as follows: <File> <Sub_Function_1> <Messages> <Setting> <Data> <Label>Setting_2</Label> <Value> <Measure> <Data>Area_2</Data> <Bound> ...
[ "The structure of the xml in this question is different from the one in your other question. To reflect that, change your for loop to this:\nfor k in doc2.xpath('//Value//Measure'):\n val1 = k.xpath('.//Bound[1]//Value/*')[0]\n val2 = k.xpath('.//Bound[2]//Value/*')[0]\n if val1.tag !=val2.tag:\n pr...
[ 0 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0074393898_lxml_python_xml.txt
Q: How to find the version of an azure Function App? I want to check what is the python version that my Azure Function App is running. A: This can be achieved using azure CLI - az Install az - https://learn.microsoft.com/en-us/cli/azure/. Use az login to login to your azure account Then execute az functionapp show...
How to find the version of an azure Function App?
I want to check what is the python version that my Azure Function App is running.
[ "This can be achieved using azure CLI - az\n\nInstall az - https://learn.microsoft.com/en-us/cli/azure/.\nUse az login to login to your azure account\nThen execute az functionapp show -g [resource_name] --name [Function APP name] | grep linuxFxVersion\n\nHelpful: You might need to install azure-functions-core-tools...
[ 1, 1 ]
[]
[]
[ "azure_functions", "cloud", "python" ]
stackoverflow_0071936193_azure_functions_cloud_python.txt
Q: Understanding mypy coverage report coloring (Any Types, Omitted Generics) I'm getting started with type checking in Python and using the mypy tool. I've run a mypy html coverage report on a snippet of my code and see the following: If I hover over this portion of the code it says "Any Types on this Line: Omitted ...
Understanding mypy coverage report coloring (Any Types, Omitted Generics)
I'm getting started with type checking in Python and using the mypy tool. I've run a mypy html coverage report on a snippet of my code and see the following: If I hover over this portion of the code it says "Any Types on this Line: Omitted Generics(x2)". My question is, what exactly does this mean? While mypy doesn't ...
[ "First off, it's discouraged to just post images in your question - here it's useful because you're trying to figure out why your IDE is rendering something this way, but it would be very helpful to people who use screen readers to summarize what is going on in the image.\nSecond, you didn't mention which IDE gener...
[ 1, 0 ]
[]
[]
[ "mypy", "python", "type_hinting" ]
stackoverflow_0067112890_mypy_python_type_hinting.txt
Q: Date format changes after the 240th Row in Date Column of CSV: goes from 1880-01-15 (%Y-%m-%d) to 15-01-00 (%d-%m-%y). How do I make them the same? I need to be able to change the following dates in new_file["Date] from 15,01,00 (%d,%m,%y) format to 1880-01-15 (%Y-%m-%d) format so that the column is completely uni...
Date format changes after the 240th Row in Date Column of CSV: goes from 1880-01-15 (%Y-%m-%d) to 15-01-00 (%d-%m-%y). How do I make them the same?
I need to be able to change the following dates in new_file["Date] from 15,01,00 (%d,%m,%y) format to 1880-01-15 (%Y-%m-%d) format so that the column is completely uniform. The formats change at the 240th index of the column. [] Here is my following attempt. Can someone help me? from datetime import date, datetime imp...
[ "Assuming:\n\non your example each date represent seperate month,\nfor some reason dates after hitting 1900 moved to 15th of each month instead of 1st, like it was in 1800s (or you cut the last 5 when preparing the example),\nyour data doesn't go over 1999,\n\nThis should solve your problem:\nnew_file['Date'] = new...
[ 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python", "python_datetime" ]
stackoverflow_0074395981_csv_dataframe_pandas_python_python_datetime.txt
Q: matplotlib quiver() displaying double arrows The code below is producing double arrows. This is most noticeable in the center and along the bottom row. Am I missing something or is this a bug of some sort? The Googlebox has yielded nothing helpful. X = [[ 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, ...
matplotlib quiver() displaying double arrows
The code below is producing double arrows. This is most noticeable in the center and along the bottom row. Am I missing something or is this a bug of some sort? The Googlebox has yielded nothing helpful. X = [[ 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22], ...
[ "Didn't you ask for exactly that, repeating values 1 and 12?\n#(...)\nX = [[ 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22],\n [ 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22],\n#(...)\nY = [[ 1, ...
[ 0 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0074396400_matplotlib_plot_python.txt
Q: How to display the rows in a float column that contains decimals? I have a data frame that has a quantity column and I need to check if the data was inputted correctly. If there's a number that was inputted with decimals I receive de data frame with de quantity column as a float and not as an integer, but I need t...
How to display the rows in a float column that contains decimals?
I have a data frame that has a quantity column and I need to check if the data was inputted correctly. If there's a number that was inputted with decimals I receive de data frame with de quantity column as a float and not as an integer, but I need to print out the index of the rows that were inputted with decimals. For...
[ "You can compare the values to the rounded versions of the values and use boolean masking to select only those rows\ntestdf[testdf['quantity']!=testdf['quantity'].round()]\\\n.index\\\n.tolist()\n\n[3, 5]\n\n", "One possibility is to use the modulo operator, as in this example, and then extract the indexes that s...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074396419_pandas_python.txt
Q: Scraping a website but the order of ratings vary built a scraper for glassdoor.com out of curiosity and as a learning experience, however just realized that the website has some gimmicks and I don't have any idea how to take them in to consideration. Attached a picture to visualize the problem, every review has th...
Scraping a website but the order of ratings vary
built a scraper for glassdoor.com out of curiosity and as a learning experience, however just realized that the website has some gimmicks and I don't have any idea how to take them in to consideration. Attached a picture to visualize the problem, every review has these categories in it, and in my original script I had ...
[ "I think you will want to select the li (and its descendant span with the star rating) based on the text of the li element's first child div, e.g.\n//li\n [div[1]='Work/Life Balance']\n /div/span\n [contains(@class, 'gd-ui-star')]\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074373901_python_selenium_selenium_webdriver_xpath.txt
Q: How can I separate a superscript from its root word using python? I am working on a project that requires the separating of a superscript from its root word so that it can be tokenized as a separate token. if I tokenize "This is a sentence about testString™" the results will be ["this, "is", "a", "sentence", "abou...
How can I separate a superscript from its root word using python?
I am working on a project that requires the separating of a superscript from its root word so that it can be tokenized as a separate token. if I tokenize "This is a sentence about testString™" the results will be ["this, "is", "a", "sentence", "about", "testString™"] and I need to get to a solution where the output can...
[ "Here is a solution that handles every case I could think to throw at it.\nThe code loops over each character in a word and detects whether its unicode value is greater than 127, if it is, it detects the original position of the character and then adds appropriate white space such that the split() function can be u...
[ 1 ]
[]
[]
[ "nlp", "nltk", "python", "superscript" ]
stackoverflow_0074381488_nlp_nltk_python_superscript.txt
Q: How to call Python functions from JavaScript in Django? I've been struggling on this for a couple days. I've read through many posts, blogs, and watch video demo on Django projects, but nothing quite answers my problem. I have a Django webapp that uses a Python API to connects to a third-party service to analyze t...
How to call Python functions from JavaScript in Django?
I've been struggling on this for a couple days. I've read through many posts, blogs, and watch video demo on Django projects, but nothing quite answers my problem. I have a Django webapp that uses a Python API to connects to a third-party service to analyze text data. The user writes into a text area, presses the butto...
[ "in the urls.py you create an url\npath('my-ajax-test/', views.myajaxtestview, name='ajax-test-view'),\n\nthen your ajax should loook like\npay attention to the csrf_token otherwise will send you an error \n $ajax({\n type: \"POST\",\n url: '{{ url 'ajax-test-view'}}', \n data: {csrfm...
[ 4, 0, 0, 0, 0 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0051106830_ajax_django_python.txt
Q: get multiple wiki tables pass to csv How to get tables and pass to csv file? import pandas as pd # 'https://en.wikipedia.org/wiki/List_of_Linux_distributions' url = 'https://en.wikipedia.org/wiki/List_of_Linux_distributions' tables = pd.read_html(url) df = tables df.to_csv("linux_distros.csv", sep=",") Attri...
get multiple wiki tables pass to csv
How to get tables and pass to csv file? import pandas as pd # 'https://en.wikipedia.org/wiki/List_of_Linux_distributions' url = 'https://en.wikipedia.org/wiki/List_of_Linux_distributions' tables = pd.read_html(url) df = tables df.to_csv("linux_distros.csv", sep=",") AttributeError: 'list' object has no attribute...
[ "read_html returns a list of dataframes, one for each table found.\nYou'd need to concatenate all relevant tables and then save that to a csv.\nimport pandas as pd\n\nurl = 'https://en.wikipedia.org/wiki/List_of_Linux_distributions'\ntables = pd.read_html(url)\n\ntables = [table for table in tables if ('Distributio...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074396475_python.txt
Q: Why am I author of message send by byt - python discord I am trying to send discord message to channel using python bot, but when I print it's author, it's me and not the bot. So later I can't edit it because of the author. How can I send message as the bot? My function: @bot.command(name="send") async def send(ct...
Why am I author of message send by byt - python discord
I am trying to send discord message to channel using python bot, but when I print it's author, it's me and not the bot. So later I can't edit it because of the author. How can I send message as the bot? My function: @bot.command(name="send") async def send(ctx: Context) -> None: message = "message" await ctx.ch...
[ "Because ctx.message is the message that invoked the command, not the message sent by the bot... So ctx.message.author is the person that invoked the command, which is you.\nprint(ctx.message.author) # <- \"print the author of the message that invoked this command\"\n\nWhen you use Messageable.send(), it returns t...
[ 1, 1 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074394034_discord_discord.py_python.txt
Q: Trying to Iterate Through File and Having Issues So I have a file "game.txt" which consist of an instruction and a number. The instruction is either "coin," "jump," or "none." "Coin" stores the number following the instruction, "jump" will jump to a new instruction relative to itself and do whatever that instructi...
Trying to Iterate Through File and Having Issues
So I have a file "game.txt" which consist of an instruction and a number. The instruction is either "coin," "jump," or "none." "Coin" stores the number following the instruction, "jump" will jump to a new instruction relative to itself and do whatever that instructions says, and "none" will do nothing. However, "jump +...
[ "Don't use all those nested if statements for jumping. Just reset the current index of the main loop to the element that you're jumping to.\nYou'll need to use a while loop instead of looping over range() so you can reset the index.\nInstead of all that slicing, use split() to split each line into a command and arg...
[ 0 ]
[]
[]
[ "file", "list", "python" ]
stackoverflow_0074396507_file_list_python.txt
Q: How to get ['1 0', '2 0', '3 1 2'] to be [[1, 0], [2,0] , [3,1] , [ 3,2] ] in so I can unpack the values. Python. Adjacency list My goal is to take lists that contain strings such as ['1 0', '2 0', '3 1 2'] or [['1 0'], ['2 0'], ['3 1 2']] and turn that into an adjacency list like so: [[1, 0], [2,0], [3,1], [3,2]]...
How to get ['1 0', '2 0', '3 1 2'] to be [[1, 0], [2,0] , [3,1] , [ 3,2] ] in so I can unpack the values. Python. Adjacency list
My goal is to take lists that contain strings such as ['1 0', '2 0', '3 1 2'] or [['1 0'], ['2 0'], ['3 1 2']] and turn that into an adjacency list like so: [[1, 0], [2,0], [3,1], [3,2]] The issue I have is that the last string in the list has more than two digits ['3 1 2']. This causes unpacking the sublist to generat...
[ "You can try:\nlst = [\"1 0\", \"2 0\", \"3 1 2\"]\n\nout = []\nfor s in lst:\n n, *rest = map(int, s.split())\n out.extend([n, v] for v in rest)\n\nprint(out)\n\nPrints:\n[[1, 0], [2, 0], [3, 1], [3, 2]]\n\n", "Essentially all we need to do to get from your desired input to output is\n\nread each entry in ...
[ 1, 0, 0, 0 ]
[]
[]
[ "adjacency_matrix", "arrays", "dictionary", "python", "string" ]
stackoverflow_0074396440_adjacency_matrix_arrays_dictionary_python_string.txt
Q: How to diagonally populate a matrix using numpy diagonal Suppose I have: arr1 = np.array([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]]) And the empty matrix: matrix = np.zeros((10, 10)) matrix[:] = np.NaN I want to populate matrix with each element within arr1, but diagonally. ...
How to diagonally populate a matrix using numpy diagonal
Suppose I have: arr1 = np.array([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]]) And the empty matrix: matrix = np.zeros((10, 10)) matrix[:] = np.NaN I want to populate matrix with each element within arr1, but diagonally. This is the expected output: array([[ nan, nan, nan, nan, na...
[ "Try:\nfor i, col in enumerate(arr1.T, 1):\n matrix[i : i + len(col), i - 1] = col\n\nprint(matrix)\n\nPrints:\n[[nan nan nan nan nan nan nan nan nan nan]\n [ 1. nan nan nan nan nan nan nan nan nan]\n [ 6. 2. nan nan nan nan nan nan nan nan]\n [11. 7. 3. nan nan nan nan nan nan nan]\n [16. 12. 8. 4. nan nan...
[ 1, 1 ]
[]
[]
[ "arrays", "diagonal", "matrix", "numpy", "python" ]
stackoverflow_0074396305_arrays_diagonal_matrix_numpy_python.txt
Q: how to create a row for each corresponding column I have a data frame which formatted like this: - Name 0 1 2 3 0 John object 1 object 2 Object 3 object 4 1 Smith object 1 object 2 Object 3 object 4 2 Jack object 1 object 2 Object 3 object 4 and I want to transform it to the following: - Name 0 0 John objec...
how to create a row for each corresponding column
I have a data frame which formatted like this: - Name 0 1 2 3 0 John object 1 object 2 Object 3 object 4 1 Smith object 1 object 2 Object 3 object 4 2 Jack object 1 object 2 Object 3 object 4 and I want to transform it to the following: - Name 0 0 John object1 1 John object2 2 John object3 ...
[ "You could try:\nimport pandas as pd\nimport numpy as np\n\ndf = (pd.melt(df, id_vars=['Name'], value_vars=df.columns[1:])\n .drop(columns=['variable'])\n .sort_values(by='Name')\n .pipe(lambda g: g.set_axis(np.arange(0, len(g.index)), axis=0)))\n\ndf\n\n Name value\n0 Jack object 1\n1 Jack object 2...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074396589_dataframe_pandas_python.txt
Q: Connect ZKTECO device from hosted django Site gives an error I have created a site that connect ZKTECO K40 device. The connection Method is pretty simple: from zk import ZK, const zk = ZK('192.168.1.13', port=4370, timeout=5) conn = zk.connect() This makes a connection while running from a local host connecting i...
Connect ZKTECO device from hosted django Site gives an error
I have created a site that connect ZKTECO K40 device. The connection Method is pretty simple: from zk import ZK, const zk = ZK('192.168.1.13', port=4370, timeout=5) conn = zk.connect() This makes a connection while running from a local host connecting in the same network. But after hosting the site, the site is not ab...
[ "From the server, a machine which is connected to some local network can not be connected. You have to use cams biometric api for communicating your biometric device from the remotely hosted application.\n", "You can use https://www.zerotier.com/ - to expose the device over the internet and then connect it. It's...
[ 0, 0 ]
[]
[]
[ "connect", "django", "hosting", "python", "zkteco" ]
stackoverflow_0069438782_connect_django_hosting_python_zkteco.txt
Q: Python Program Doesn't Show Any Output/Result in Visual Studio Code (No Errors) I have a python program that displays no errors when I run it but doesn't give any kind of output. It only displays: "Dash is running on http://127.0.0.1:8050/ Serving Flask app 'Editable_Table' Debug mode: on" No other output is gi...
Python Program Doesn't Show Any Output/Result in Visual Studio Code (No Errors)
I have a python program that displays no errors when I run it but doesn't give any kind of output. It only displays: "Dash is running on http://127.0.0.1:8050/ Serving Flask app 'Editable_Table' Debug mode: on" No other output is given. It gives the same result when I run it directly from the command line. I tried ...
[ "The output will actual display in your browser. Copy/paste http://127.0.0.1:8050/ into your browser window and your app will pop up.\nIn your current code, you don't have anything printing to the console, so nothing should be expected there.\n" ]
[ 0 ]
[]
[]
[ "program_entry_point", "python" ]
stackoverflow_0074396611_program_entry_point_python.txt
Q: python pandas AttributeError: 'dict' object has no attribute 'head' df = pd.read_excel(download_path, sheet_name=None) l = df.values.tolist() on this I am getting error uiltin_function_or_method' object has no attribute 'tolist' when I do something like this print(df.head()) I get error like AttributeError: '...
python pandas AttributeError: 'dict' object has no attribute 'head'
df = pd.read_excel(download_path, sheet_name=None) l = df.values.tolist() on this I am getting error uiltin_function_or_method' object has no attribute 'tolist' when I do something like this print(df.head()) I get error like AttributeError: 'dict' object has no attribute 'head' what thing I am doing wrong here ? v...
[ "When reading an excel file with pandas, if you set sheet_name=None as a parameter for pd.read_excel you will get a dictionary mapping between sheet names in the excel file and their corresponding DataFrames (as hinted in the documentation).\nYou can use the following template to extract the relevant DataFrames\nma...
[ 1 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074396402_pandas_python_python_3.x.txt
Q: How to replace existing file name in google drive using python I have a script to copy csv files to google drive but I want if an existing filename in the drive exists, when I run the script again, it should replace the existing filename. Currently, a duplicate file is created i.e duplicate test.csv. Below is the ...
How to replace existing file name in google drive using python
I have a script to copy csv files to google drive but I want if an existing filename in the drive exists, when I run the script again, it should replace the existing filename. Currently, a duplicate file is created i.e duplicate test.csv. Below is the code # create drive api client service = build('drive', 'v3'...
[ "In Google Drive, the files are managed by the unique ID instead of the filename. By this, the files with the same filename can be created in the same folder. I think that this is the reason for your issue. So, in this case, first, it is required to check whether the files with the same filename are existing in the...
[ 2 ]
[]
[]
[ "google_drive_api", "python" ]
stackoverflow_0074394868_google_drive_api_python.txt
Q: How to pass an argument to the subprocess that expects input I would like to execute a "git push" command using Python script. I was hoping to achieve this by using python's subprocess.Popen() method. However when I invoke the "git push" command, the ssh agent asks me for my passphrase in order to be able to push ...
How to pass an argument to the subprocess that expects input
I would like to execute a "git push" command using Python script. I was hoping to achieve this by using python's subprocess.Popen() method. However when I invoke the "git push" command, the ssh agent asks me for my passphrase in order to be able to push any changes to the repository. And here is my question - is there ...
[ "Note that GitPython issue 559 mentioned in 2016:\n\nAs far as I know, it is not possible to use keys with passphrases with GitPython due to the way git is invoked by it.\nIt simply does not connect standard input, which usually would be required to read the passphrase. The preferred way to do it would be to use a ...
[ 0 ]
[]
[]
[ "git", "python", "ssh_agent", "stdin", "subprocess" ]
stackoverflow_0074396183_git_python_ssh_agent_stdin_subprocess.txt
Q: NameError: name 'fetch' is not defined in Selenium Console Hi I am trying to open Selenium, visit a URL then use driver.execute_script to send a fetch request via Console in Chrome Developer Tools within the Selenium window. However when I run it, the Selenium window opens up, visits the page, but when it gets to ...
NameError: name 'fetch' is not defined in Selenium Console
Hi I am trying to open Selenium, visit a URL then use driver.execute_script to send a fetch request via Console in Chrome Developer Tools within the Selenium window. However when I run it, the Selenium window opens up, visits the page, but when it gets to the execute_script section, it comes up with: 'NameError: name '...
[ "That's not how fetch works. first of all it runs in the browser, and second it's async so use execute_async_script.\nIt should look something like this:\nresponse = driver.execute_async_script(\"\"\"\n let [resolve] = arguments\n fetch(url, options).then(r => r.text()).then(resolve)\n\"\"\")\n\n" ]
[ 0 ]
[]
[]
[ "fetch", "javascript", "python", "selenium" ]
stackoverflow_0074392238_fetch_javascript_python_selenium.txt
Q: Format outlook email with Python win32 and allow for a class to be used within the HTMLbody I am trying to make a basic outlook email template for one of my tasks at work. The goal is to be able to run a script and provide a number to the program such that I can generate repetitive blocks of code for releasing mat...
Format outlook email with Python win32 and allow for a class to be used within the HTMLbody
I am trying to make a basic outlook email template for one of my tasks at work. The goal is to be able to run a script and provide a number to the program such that I can generate repetitive blocks of code for releasing materials in our warehouse. I have figured out how to draft the email (need manual inputs so using m...
[ "Sounds like you need to build an HTML string based on the data from an external source. The MailItem.HTMLBody property returns or sets a string representing the HTML body of the specified item. The HTMLBody property should be an HTML syntax string, that means the string should represent a well formed HTML document...
[ 0 ]
[]
[]
[ "html_email", "office_automation", "outlook", "python", "win32com" ]
stackoverflow_0074395444_html_email_office_automation_outlook_python_win32com.txt
Q: Fill Matrix Rows in Python Let's say we have a nested list in Python. AKA a matrix, and we have a list consisting of elements, lets say li = [1, 2, 3, 4, 5, 6]. I want to insert two elements in matrix rows, resulting matrix = [ [1,2] [3,4], [5,6] ]. How can this be done ? Thanks! b = [[]] c = [1, 2, 3, 4, 5, 6] f...
Fill Matrix Rows in Python
Let's say we have a nested list in Python. AKA a matrix, and we have a list consisting of elements, lets say li = [1, 2, 3, 4, 5, 6]. I want to insert two elements in matrix rows, resulting matrix = [ [1,2] [3,4], [5,6] ]. How can this be done ? Thanks! b = [[]] c = [1, 2, 3, 4, 5, 6] for i in range(len(c)): for j...
[ "\nHow can this be done ?\n\n\nsplit the list with slices\na[0:2],a[2:4],a[4:6]\nappend each of those to an empty list\nor construct a list with those slices as the items\n\n", "You can do it just like this:\nc = [1, 2, 3, 4, 5, 6]\nb = []\nfixed_c = []\nfor i in range(len(c) + 1):\n if len(b) < 2 :\n b...
[ 1, 1 ]
[]
[]
[ "for_loop", "matrix", "nested_lists", "python" ]
stackoverflow_0074396584_for_loop_matrix_nested_lists_python.txt
Q: Unable to load new images from a directory in a bucket in google cloud storage in python? Previously, I have been loading images (blobs) from a bucket: # connect to storage storage_client = storage.Client(project_id) bucket = storage_client.get_bucket(bucket_name) blobs = bucket.list_blobs(prefix=img_dir) # Get l...
Unable to load new images from a directory in a bucket in google cloud storage in python?
Previously, I have been loading images (blobs) from a bucket: # connect to storage storage_client = storage.Client(project_id) bucket = storage_client.get_bucket(bucket_name) blobs = bucket.list_blobs(prefix=img_dir) # Get list of files images = np.zeros((len(list(blobs)), height, width)) print(images.shape) When I ...
[ "Found the problem. For some reason\nblobs = bucket.list_blobs(prefix=img_dir)\n\nreturns a list where the first element is the directory path, instead of the first file in the directory:\n/path/images/\n/path/images/file1.jpg\n/path/images/file2.jpg\n...\n\nso to solve this, I just check that the blobs don't have ...
[ 2 ]
[]
[]
[ "google_cloud_platform", "google_cloud_storage", "python" ]
stackoverflow_0074393584_google_cloud_platform_google_cloud_storage_python.txt
Q: Create a sentence-term matrix using CountVectorizer() I am trying to create a document-term matrix in Python based on the following list of sentences with the help of CountVectorizer(): tokens_sents = [ 'go local restaraunt yesterday evening try pasta .', 'expect delicious , eatable .', 'smell really b...
Create a sentence-term matrix using CountVectorizer()
I am trying to create a document-term matrix in Python based on the following list of sentences with the help of CountVectorizer(): tokens_sents = [ 'go local restaraunt yesterday evening try pasta .', 'expect delicious , eatable .', 'smell really bad delicious .', 'never eat pasta restaraunt taste past...
[ "The term \"sentence-term matrix\" isn't used despite the fact you are working with sentences in your example. In most NLP tasks, each independent instance of text is referred to as a \"document\", even though it may only contain one sentence.\nBased on this, and the content of your question, I presume you want to ...
[ 0 ]
[]
[]
[ "nlp", "python", "scikit_learn", "sparse_matrix" ]
stackoverflow_0074389817_nlp_python_scikit_learn_sparse_matrix.txt
Q: Cannot upload the files into AWS S3 bucket with ACL pubic-read using python I am trying to upload the file into s3 bucket but I am getting access denied error when I am trying to upload the files with ACL public-read It is working fine with ACL private class S3: def __init__(self): self.__s3_bucket = a...
Cannot upload the files into AWS S3 bucket with ACL pubic-read using python
I am trying to upload the file into s3 bucket but I am getting access denied error when I am trying to upload the files with ACL public-read It is working fine with ACL private class S3: def __init__(self): self.__s3_bucket = app.config['aws_bucket'] self.__s3_client = boto3.client( "...
[ "You will need to deactivate Block S3 Public Access.\nIf you wish to use ACLs, you will need to turn OFF these options:\n\nBlock public access to buckets and objects granted through new access control lists (ACLs)\nBloack public access to buckets and objects granted through any access control lists (ACLs)\n\n\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto", "python" ]
stackoverflow_0074389999_amazon_s3_amazon_web_services_boto_python.txt
Q: How to pass a variable to create and HtmlBody with python and win32 what im tryng to do is send a birthday notification, everything is working fine, But i want to pass the name of the Birthday Person to show it in the HTML, Per example in Subject what i have is: Happy Birthday test1 (Where test1 is the result of a...
How to pass a variable to create and HtmlBody with python and win32
what im tryng to do is send a birthday notification, everything is working fine, But i want to pass the name of the Birthday Person to show it in the HTML, Per example in Subject what i have is: Happy Birthday test1 (Where test1 is the result of a loop in the database) i want to use test1 (name) again in the HTML. To s...
[ "You can write the HTML in a string, then concatenate in any variables you want to add. You can use parentheses to make the strings multiline\ndef email_func(subject, birthday_receiver, name):\n mailItem = olApp.CreateItem(0)\n mailItem.BodyFormat = 1\n mailItem.To = 'receiver@magmia.com'\n mailItem.Cc ...
[ 0 ]
[]
[]
[ "html", "html_email", "python", "string", "win32com" ]
stackoverflow_0074396241_html_html_email_python_string_win32com.txt
Q: "A value is trying to be set on a copy of a slice from a DataFrame." Use .loc[row_indexer,col_indexer] = value instead I have a dataframe, df, where I want to filter based on criteria, change values in a few columns and then append/concat that new dataframe to the original dataframe. I can do this successfully wit...
"A value is trying to be set on a copy of a slice from a DataFrame." Use .loc[row_indexer,col_indexer] = value instead
I have a dataframe, df, where I want to filter based on criteria, change values in a few columns and then append/concat that new dataframe to the original dataframe. I can do this successfully with the following code: end_previous_month = EndDate.replace(day=1) - timedelta(days=1) end_previous_month = end_previous_mont...
[ "Nevermind, I worked it out.\nend_previous_month = EndDate.replace(day=1) - timedelta(days=1)\nend_previous_month = end_previous_month.strftime(\"%Y/%m/%d\")\n\ndf1 = df[(df['Account.DisplayID'] == \"1-1110\") &\n (df['CompanyKey'] != 4) &\n (df['DateOccurred'] <= end_previous_month)].copy()\n\ndf1.loc[:, [...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074396768_pandas_python.txt
Q: pyplot drawing on an angle I'm trying to draw a couple of vectors with pyplot. My approach is to define first the plot size (or axis values), as this will change depending on the job run. pretty much what i need to do is to draw a straight, upwards-facing vector. So for the test i am using the same values for x-ax...
pyplot drawing on an angle
I'm trying to draw a couple of vectors with pyplot. My approach is to define first the plot size (or axis values), as this will change depending on the job run. pretty much what i need to do is to draw a straight, upwards-facing vector. So for the test i am using the same values for x-axis, and two different ones for Y...
[ "Hope this would help!\nimport matplotlib.pyplot as plt\nimport math\n\nstart = (162305,299400,162890,299400) #define coordinates for vector\n\n#define plot axis values\ntop = 163440\nbottom = 161910\nleft = 299595\nright = 300510\n\nfig, ax = plt.subplots()\n\nax.quiver(start[0],start[1],1,0)\n#ax.quiver(x_pos, y_...
[ 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074396592_matplotlib_python.txt
Q: How to transform pandas column values to dict with column name I need help on how to properly transform my df from this: df = pd.DataFrame({'ID': ['ID no1', "ID no2", "ID no3"], 'ValueM2': ["11998","11076", "12025"], 'ValueSqFt': [129145.39718,119221.07178, 129.43600276]}) to this: -...
How to transform pandas column values to dict with column name
I need help on how to properly transform my df from this: df = pd.DataFrame({'ID': ['ID no1', "ID no2", "ID no3"], 'ValueM2': ["11998","11076", "12025"], 'ValueSqFt': [129145.39718,119221.07178, 129.43600276]}) to this: --> also i need it to be outputted as double quote (") instead of sin...
[ "If there are only 2 columns to be manipulated, it is best to adopt a manual approach as follows:\ndf['ValueM2'] = [{'ValueM2': x} for x in df['ValueM2'].values]\ndf['ValueSqFt'] = [{\"ValueSqFt\": x} for x in df['ValueSqFt'].values]\ndf = df.rename(columns={'ValueM2': 'DataMetric', 'ValueSqFt': 'DataImperial'})\n\...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074396688_dataframe_pandas_python.txt
Q: How can I combine Asyncio and Websockets such that data keeps comming in while other functions run concurrently? I have a stream of data comming in which I want to use while it's comming in. Besides that I want to run another function every 30 seconds. Thus, while I am using the data stream to compute things I wou...
How can I combine Asyncio and Websockets such that data keeps comming in while other functions run concurrently?
I have a stream of data comming in which I want to use while it's comming in. Besides that I want to run another function every 30 seconds. Thus, while I am using the data stream to compute things I would like to run another function every 30 seconds. The code I have now: import asyncio import websockets async def oth...
[ "You can use asyncio.create_task() to create background task. For example:\nimport asyncio\nimport websockets\n\n\nasync def other_function():\n while True:\n print(\"Do stuff\")\n await asyncio.sleep(3)\n\n\nasync def main():\n bg_task = asyncio.create_task(other_function())\n\n async with w...
[ 0, 0 ]
[]
[]
[ "python", "python_asyncio", "websocket" ]
stackoverflow_0074396790_python_python_asyncio_websocket.txt
Q: How to find the position of a word in a Dataframe I have the problem that I cannot get the position of the row, from a text of a dataframe column. I have a .dat data file where it contains a data table, I opened it with pandas so it reads as a dataframe (header = None). Example: filesday = pd.read_table("date_days...
How to find the position of a word in a Dataframe
I have the problem that I cannot get the position of the row, from a text of a dataframe column. I have a .dat data file where it contains a data table, I opened it with pandas so it reads as a dataframe (header = None). Example: filesday = pd.read_table("date_days.dat", header = None) Result: 0 1 ...
[ "# contains returns true/false when searching for a string like 'today-4'\n# use the boolean to return the row\n\ninfo_day[info_day.str.contains('today-4')].index[0]\n\n3\n\n# if multiple index are returned, you can get the list of all the indexes\ninfo_day[info_day.str.contains('today')].index.tolist()\n\ninfo_day...
[ 0 ]
[]
[]
[ "dataframe", "indexing", "pandas", "python" ]
stackoverflow_0074396917_dataframe_indexing_pandas_python.txt
Q: Python psycopg2 syntax error I am new to python and working on using the psycopg2 to insert data in postgres database. I am trying to insert items but get the error message "Psycopg2.ProgrammingError: syntax error at or near "cup" LINE 1: INSERT INTO store VALUES(7,10.5,coffee cup) with the ^ next to coffee cup....
Python psycopg2 syntax error
I am new to python and working on using the psycopg2 to insert data in postgres database. I am trying to insert items but get the error message "Psycopg2.ProgrammingError: syntax error at or near "cup" LINE 1: INSERT INTO store VALUES(7,10.5,coffee cup) with the ^ next to coffee cup. I am assuming the order is wrong ...
[ "Remember to always use the second argument of the execute command to pass the variables, as stated here.\nAlso, use the name of the fields in your syntax:\ncur.execute(\"INSERT INTO store (item, quantity, price) VALUES (%s, %s, %s);\", (item, quantity, price))\n\nThat should do the trick.\n", "Problem in your ca...
[ 6, 1, 0 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0044836551_postgresql_python.txt
Q: Stacked pie chart - how to set inner piechart labels dependent on outer piechart I have a stacked pie chart with labels in percentage. The outer pie chart has labels as I want them to be; however, the labels for the inner chart should be based on where it falls under the outer pie chart. For example, in the image ...
Stacked pie chart - how to set inner piechart labels dependent on outer piechart
I have a stacked pie chart with labels in percentage. The outer pie chart has labels as I want them to be; however, the labels for the inner chart should be based on where it falls under the outer pie chart. For example, in the image below, the percentage labels of the inner pie chart should sum up to 100% for each col...
[ "An approach you can take is to calculate the percentage of the inner wedge relative to the outer wedge and make new labels to then pass when you do ax.pie. For example:\n# Construct inner labels\n inner_str_label = [] # new labels storage\n n_inside = 3 # number of inner wedges per outer wedge\n for idx...
[ 1 ]
[]
[]
[ "charts", "matplotlib", "pandas", "pie_chart", "python" ]
stackoverflow_0074395980_charts_matplotlib_pandas_pie_chart_python.txt
Q: How to use python virtual environments in VS Code jupyter notebooks integration? I have created a virtual environment with venv as follows from VS Code integrated terminal: python3 -m venv <name> after cd in the directory, I activated it by doing source <name>/bin/activate How can I make it available for the kern...
How to use python virtual environments in VS Code jupyter notebooks integration?
I have created a virtual environment with venv as follows from VS Code integrated terminal: python3 -m venv <name> after cd in the directory, I activated it by doing source <name>/bin/activate How can I make it available for the kernel of my VS Code integration of jupyter notebook? I only see the default python instal...
[ "Create a new python environment via the console, then from a notebook try and select it as a kernel it doesn't appear in the list of python environments. This phenomenon also occurs in my VS Code.\nThere's an issue in github, Python extension team will see if there's enough upvotes, then they will consider this fe...
[ 2, 1, 0 ]
[]
[]
[ "jupyter_notebook", "python", "python_venv", "visual_studio_code" ]
stackoverflow_0069233895_jupyter_notebook_python_python_venv_visual_studio_code.txt
Q: Code completion similar to intelliJ for python I recently started working with Java and I really like to auto-correction / completion features in IntelliJ. Does it exist something similar and as powerful for python? A: I presume you are using JetBrains IDE so you could try out their PyCharm for python. It's from...
Code completion similar to intelliJ for python
I recently started working with Java and I really like to auto-correction / completion features in IntelliJ. Does it exist something similar and as powerful for python?
[ "I presume you are using JetBrains IDE so you could try out their PyCharm for python. It's from the same company so I presume that PyCharm's autocomplete features are on par with that of IntelliJ\nAs I never used IntelliJ, the recommendations below are based on the autocomplete features of PyCharm.\nI was using tab...
[ 0 ]
[]
[]
[ "autocomplete", "autocorrect", "ide", "intellij_idea", "python" ]
stackoverflow_0074396836_autocomplete_autocorrect_ide_intellij_idea_python.txt
Q: Strange behavior with contextmanager Take a look at the following example: from contextlib import AbstractContextManager, contextmanager class MyClass(AbstractContextManager): _values = {} @contextmanager def using(self, name, value): print(f'Allocating {name} = {value}') self._values...
Strange behavior with contextmanager
Take a look at the following example: from contextlib import AbstractContextManager, contextmanager class MyClass(AbstractContextManager): _values = {} @contextmanager def using(self, name, value): print(f'Allocating {name} = {value}') self._values[name] = value try: y...
[ "You're creating two context managers here. Only one of those context managers is actually implemented correctly.\nYour using context manager is fine, but you've also implemented the context manager protocol on MyClass itself, and the implementation on MyClass is broken. MyClass.__enter__ creates a using context ma...
[ 3 ]
[]
[]
[ "contextmanager", "python", "python_3.x" ]
stackoverflow_0074396909_contextmanager_python_python_3.x.txt
Q: How to replace full words versus substrings I am working on a problem where I am using a dictionary to replace certain words in a string. This is my code for a minimal example: dictionary = {"happy": 'YAY!', "happybday": "PARTY!"} string = "There were so many happy people exclaiming happybday!" for old_word, new...
How to replace full words versus substrings
I am working on a problem where I am using a dictionary to replace certain words in a string. This is my code for a minimal example: dictionary = {"happy": 'YAY!', "happybday": "PARTY!"} string = "There were so many happy people exclaiming happybday!" for old_word, new_word in dictionary.items(): string = string....
[ "You may build a regex alternation of search keys, sorted descending by length such that longer, more specific terms, will be searched first.\ndictionary = {\"happy\": 'YAY!', \"happybday\": \"PARTY!\"}\nstring = \"There were so many happy people exclaiming happybday!\"\n\nregex = r'\\b(?:' + r'|'.join(sorted(dicti...
[ 1, 0 ]
[]
[]
[ "dictionary", "python", "python_3.x", "string" ]
stackoverflow_0074396935_dictionary_python_python_3.x_string.txt
Q: Why python code accepts '.' and '-' as numbers? Use case: ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. If the function is passed a valid PIN string, return true, else return false. My code is working for all the randomly generated pins ex...
Why python code accepts '.' and '-' as numbers?
Use case: ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. If the function is passed a valid PIN string, return true, else return false. My code is working for all the randomly generated pins except for: '12.0' '1234.0' '111-' '44444-' def validat...
[ "As kaya3 suggested, the best way to solve issues like this is to step through with a debugger. You can do this in VS code by hitting \"Run and Debug\" on the debug tab shown below:\n\nBasically your code is checking if the first character is in numbers or not. If it is a number, the for loop breaks, if it isn't, t...
[ 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074396942_python_python_3.x.txt
Q: How to print a dictionary with multiple values in the same key, without brackets? (Python) Need to obtain marks for three subjects for several students and store them in a dictionary. Student name and marks will be the key and value respectively. Display the students name and their marks as follows, student1 : mar...
How to print a dictionary with multiple values in the same key, without brackets? (Python)
Need to obtain marks for three subjects for several students and store them in a dictionary. Student name and marks will be the key and value respectively. Display the students name and their marks as follows, student1 : mark1, mark2, mark3 student2 : mark1, mark2, mark3 I have tried this... data = {} while True: ...
[ "Replace str(v) with \", \".join(v) to convert the list to a comma-delimited string.\n" ]
[ 0 ]
[]
[]
[ "dictionary", "nested", "python" ]
stackoverflow_0074397051_dictionary_nested_python.txt
Q: python - how do I specify allowed patterns for **kwargs? As the title suggests, I want to accept if the arguments fit a certain pattern, otherwise return an error message. The order of arguments doesn't matter, as I am using (forcing to use) keyword arguments anyway. for example, let's say I have the following pat...
python - how do I specify allowed patterns for **kwargs?
As the title suggests, I want to accept if the arguments fit a certain pattern, otherwise return an error message. The order of arguments doesn't matter, as I am using (forcing to use) keyword arguments anyway. for example, let's say I have the following patterns: hex_list int_list int_list, size hex_list, size from_f...
[ "Lots of possibilities here - you could do something like this\n allowed_keys = (\n {\"hex_list\", \"size\"},\n {\"int_list\", \"size\"}, \n {\"hex_list\"},\n {\"int_list\"},\n {\"from_file\"},\n )\n \n if set(kwargs.keys()) not in allowed_keys: ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074397012_python.txt
Q: returning two integers using functions in python Still new to python and this problem is driving me crazy I know I'm missing something really obvious but I just can't figure it out :/ Here is the problem: Write a function called main that prompts/asks the user to enter two integer values. Write a value returning...
returning two integers using functions in python
Still new to python and this problem is driving me crazy I know I'm missing something really obvious but I just can't figure it out :/ Here is the problem: Write a function called main that prompts/asks the user to enter two integer values. Write a value returning function named max that accepts two integer values as...
[ "When you call a the max function you need to read the returned value. What you're printing at the end of main is the max function itself. The issue would be clearer if you renamed the max function \"getMax\".\nA second issue is that no code is executed after return in a function. So the main function stops on the ...
[ 0, 0, 0 ]
[]
[]
[ "function", "input", "max", "python", "return_value" ]
stackoverflow_0074397044_function_input_max_python_return_value.txt
Q: How to make inputs not strings (python) I am making a quick problem solver, it takes the speed (input) and time (also input) than multiplies them to get the distance... the problem is that python thinks the inputs are strings, how do i make them numbers??? my code so far is: py import random time = input("What is...
How to make inputs not strings (python)
I am making a quick problem solver, it takes the speed (input) and time (also input) than multiplies them to get the distance... the problem is that python thinks the inputs are strings, how do i make them numbers??? my code so far is: py import random time = input("What is the time it took? (no label :: ") speed = in...
[ "You should be able to simply cast the String input to an Integer. Doing as follows will give you the desired output.\ns = int(speed)\nt = int(time)\n\n" ]
[ 0 ]
[]
[]
[ "input", "python", "string" ]
stackoverflow_0074397074_input_python_string.txt
Q: When should I use *args? When writing Python 3.x functions, I've often stumbled upon the problem of writing code that accepts both a single value and a number of values. Take this trivial function: def capitalize(word): return word.capitalize() This function works well with a single string as input, but will ...
When should I use *args?
When writing Python 3.x functions, I've often stumbled upon the problem of writing code that accepts both a single value and a number of values. Take this trivial function: def capitalize(word): return word.capitalize() This function works well with a single string as input, but will fail if provided with multiple...
[ "In addition to the accepted answer (which raises some good points), you also have to consider how your function is going to be used. Using os.path.join as an example, it makes sense for this function to accept *args because one is going to often be dealing with a set number of path elements, where each one might h...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "arguments", "function", "python" ]
stackoverflow_0045462105_arguments_function_python.txt
Q: Generate combinations by systematically selecting rows from groups (using pandas) I have a pandas dataframe df which appears as following: (toy version below but the real df contains many more columns and groups) group sub fruit a 1 apple a 2 banana a 3 orange b 1 pear b 2 ...
Generate combinations by systematically selecting rows from groups (using pandas)
I have a pandas dataframe df which appears as following: (toy version below but the real df contains many more columns and groups) group sub fruit a 1 apple a 2 banana a 3 orange b 1 pear b 2 strawberry b 3 cherry c 1 kiwi c 2 tomato c 3 lemon A...
[ "A solution could be:\nimport pandas as pd\nimport numpy as np\nfrom itertools import permutations\n\ndf = pd.DataFrame({\"group\":{\"0\":\"a\",\"1\":\"a\",\"2\":\"a\",\"3\":\"b\",\"4\":\"b\",\"5\":\"b\",\"6\":\"c\",\"7\":\"c\",\"8\":\"c\"},\n \"sub\":{\"0\":1,\"1\":2,\"2\":3,\"3\":1,\"4\":2,\"5\"...
[ 1 ]
[]
[]
[ "combinations", "pandas", "python" ]
stackoverflow_0074396796_combinations_pandas_python.txt
Q: How to display a function using streamlit I'm new to streamlit and trying to display a function using st.write, however, something is not working properly. This is the code that I have: def ecc_display(ecc_duration_percentage): if ecc_duration_percentage < 5: return str(ecc_duration_percentage) + "good" e...
How to display a function using streamlit
I'm new to streamlit and trying to display a function using st.write, however, something is not working properly. This is the code that I have: def ecc_display(ecc_duration_percentage): if ecc_duration_percentage < 5: return str(ecc_duration_percentage) + "good" else: return str(ecc_duration_percentage) + ...
[ "def ecc_display(ecc_duration_percentage): \n if ecc_duration_percentage < 5:\n return str(ecc_duration_percentage) + \" good\"\n else:\n return str(ecc_duration_percentage) + \" not good.\"\n\n# start\necc_duration_percentage = 1.0\nvalue = ecc_display(ecc_duration_percentage)\nst.write(value)\n\n" ]
[ 1 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0074392079_python_streamlit.txt
Q: Add missing rows per group to fill a series I have the following df: Name Time Elapsed Amount A 2 $2 A 5 $1 A 7 $6 B 3 $3 B 5 $5 I would like to expand this per group so that I get all the times in between the min and max, and then fill downwards (assuming it's sorted by name then by time elapsed) to produc...
Add missing rows per group to fill a series
I have the following df: Name Time Elapsed Amount A 2 $2 A 5 $1 A 7 $6 B 3 $3 B 5 $5 I would like to expand this per group so that I get all the times in between the min and max, and then fill downwards (assuming it's sorted by name then by time elapsed) to produce the following output Name Time...
[ "try this:\ndef func(g: pd.DataFrame):\n tmp = g.set_index('Time Elapsed')\n res = tmp.reindex(\n np.arange(tmp.index.min(), tmp.index.max()+1),\n method='ffill')\n return res\n\ngrouped = df.groupby('Name', as_index=False)\nresult = grouped.apply(func).reset_index().reindex(columns=df.column...
[ 3, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074396608_dataframe_pandas_python.txt
Q: add values from another column from next row to update values I have a dataframe like the one below: a b 0 420 50 1 380 40 2 390 45 The problem is that I want to update column 'a' by using the first value (420) and adding the value from column 'b' ...
add values from another column from next row to update values
I have a dataframe like the one below: a b 0 420 50 1 380 40 2 390 45 The problem is that I want to update column 'a' by using the first value (420) and adding the value from column 'b' but the next row and update as it goes through so the final data fr...
[ "df.assign(a=df['b'].cumsum() + 420 - 50)\n\noutput:\n a b\n0 420 50\n1 460 40\n2 505 45\n\ndf.loc[0, 'a'] can replace 420 , df.loc[0, 'b'] can replace 50\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074397118_pandas_python.txt
Q: Metadata-generation-failed when trying to install pygame Trying to install pygame on python 3.11 using the following command "pip install pygame" and I am getting the following error: note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encounter...
Metadata-generation-failed when trying to install pygame
Trying to install pygame on python 3.11 using the following command "pip install pygame" and I am getting the following error: note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. Please help, thank...
[ "Pygame isn't updated for python 3.11, but you can still install a pre-version with pip install pygame --pre\n" ]
[ 3 ]
[]
[]
[ "pygame", "python", "visual_studio_code" ]
stackoverflow_0074397049_pygame_python_visual_studio_code.txt
Q: Add a custom image to my digital clock as background im 100% new to coding and just started to follow some guides a few days ago. I am now making a digital clock for my desktop and i want to change my background to a custom image that i have. Can someone explain to me where i can change it so that the background b...
Add a custom image to my digital clock as background
im 100% new to coding and just started to follow some guides a few days ago. I am now making a digital clock for my desktop and i want to change my background to a custom image that i have. Can someone explain to me where i can change it so that the background becomes my image that i have? BR from tkinter import Tk fro...
[ "you can try image path and background image concept. First you have to choose image, then it's size and it's position.\nIMAGE_PATH = 'PicNameHere.png'\nWIDTH, HEIGTH = 200, 50\nbkrgframe = BkgrFrame(root, IMAGE_PATH, WIDTH, HEIGTH)\nbkrgframe.pack()\nCode sample is below.\nfrom tkinter import Tk\nfrom tkinter impo...
[ 0, 0 ]
[ "from tkinter import Tk\nfrom tkinter import Label\nimport time\nfrom PIL import Image, ImageTk\n\n\n\nroot = Tk()\nroot.title(\"Klocka\")\nroot.attributes(\"-topmost\", 1)\nroot.attributes('-alpha', 1)\nroot.iconbitmap('klocka.ico (1).ico')\nroot.geometry('600x400+50+50')\n\nbg = PhotoImage(file = \"Your_img.png\"...
[ -1 ]
[ "background", "image", "python", "tkinter" ]
stackoverflow_0074369849_background_image_python_tkinter.txt
Q: Terminate all running threads at specific time i made a downloader based on a scheduler. So I wanted to download files at starting at a time of and stop before 6 am. I managed to achieve this using apscheduler that starts at 12 am, but i am not sure how to terminate all the task at 6 am. I am doing multi threading...
Terminate all running threads at specific time
i made a downloader based on a scheduler. So I wanted to download files at starting at a time of and stop before 6 am. I managed to achieve this using apscheduler that starts at 12 am, but i am not sure how to terminate all the task at 6 am. I am doing multi threading as i need to download as many things as possible by...
[ "The best solution might be using os._exit(n). exit, quit, and even sys.exit raises SystemExit which only terminates current thread and can be caught by handlers. Where as os._exit(n) exits the code without calling cleanup handlers, flushing stdio buffers. So your solution might just be using os._exit(n) But be war...
[ 1 ]
[]
[]
[ "apscheduler", "exit", "multithreading", "python", "threadpool" ]
stackoverflow_0074388308_apscheduler_exit_multithreading_python_threadpool.txt
Q: metadata generation failed in pygame installation when I try to install pygame from command line why does it show metadata generation failed and setup.py not found I have tried using pip install pygame pip3 install pygame I have tried almost all the codes but still stuck A: Pygame isn't updated for new versi...
metadata generation failed in pygame installation
when I try to install pygame from command line why does it show metadata generation failed and setup.py not found I have tried using pip install pygame pip3 install pygame I have tried almost all the codes but still stuck
[ "Pygame isn't updated for new versions of python, but you can still install a pre-version with pip install pygame --pre\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074308149_python.txt
Q: Why copying lists (which are called by functions) with [:] doesn't work? I have two lists like: prelist = [0, 0, 0, 0, 0] postlist = [50.0, 25.0, 12.5, 6.25, 3.125] I tried copying the list like so: prelist = postlist[:] but the surrounding code didn't work. When I copy the list this way instead, I get the desi...
Why copying lists (which are called by functions) with [:] doesn't work?
I have two lists like: prelist = [0, 0, 0, 0, 0] postlist = [50.0, 25.0, 12.5, 6.25, 3.125] I tried copying the list like so: prelist = postlist[:] but the surrounding code didn't work. When I copy the list this way instead, I get the desired results: for i in range(5): prelist[i] = postlist[i] What is wrong wi...
[ "When A and B refer to two lists, B = A[:] means make a copy of the list A refers to, then make B refer to the new copy of A instead of the list it used to refer to. The list B used to refer to is completely unaffected. That list exists independently of the B variable, and is not involved in this operation at all.\...
[ 0 ]
[]
[]
[ "arrays", "copy", "list", "pass_by_reference", "python" ]
stackoverflow_0074397209_arrays_copy_list_pass_by_reference_python.txt
Q: Create a cloud run job which shares code with a cloud run service I see google cloud run now has jobs which is amazing! What I would like to achieve is to have a main container serving web traffic and also a job container which can be activated based on some business logic from the primary web service. The part I ...
Create a cloud run job which shares code with a cloud run service
I see google cloud run now has jobs which is amazing! What I would like to achieve is to have a main container serving web traffic and also a job container which can be activated based on some business logic from the primary web service. The part I am unsure of how to implement is to have shared code between the two co...
[]
[]
[ "Python code\nTo share code in Python between the two services, there are a few approaches you can take. Obviously Python's main code sharing mechanism is packages. You can make a package pretty easily by adding an __init__.py file to a folder (you probably know all of this).\nSo, getting the code to easily exist i...
[ -1 ]
[ "docker", "google_cloud_platform", "google_cloud_run", "jobs", "python" ]
stackoverflow_0073197835_docker_google_cloud_platform_google_cloud_run_jobs_python.txt
Q: python vlc, how to change a radio channel when button is pressed? im trying to build a program (using pysimplegui) which contains a few buttons (play, stop, pause, next, previous) as you can see. and when i press "next" its stopping for some time and then the same music continues (i dont press "previous" because i...
python vlc, how to change a radio channel when button is pressed?
im trying to build a program (using pysimplegui) which contains a few buttons (play, stop, pause, next, previous) as you can see. and when i press "next" its stopping for some time and then the same music continues (i dont press "previous" because i know that will cause problem 0 - 1 = -1). ` global n n = 0 media_playe...
[ "Demo Code\nimport vlc\nimport PySimpleGUI as sg\n\nplaylist_url = [\n 'http://cast.radiogroup.com.ua:8000/avtoradio',\n 'http://listen.rpfm.ru:9000/premium128',\n 'http://cast.loungefm.com.ua/terrace128',\n]\nn, m = 0, len(playlist_url)\n\nplayer = vlc.MediaPlayer()\nplayer.set_mrl(playlist_url[n])\nplaye...
[ 0 ]
[]
[]
[ "libvlc", "pysimplegui", "python", "python_vlc", "vlc" ]
stackoverflow_0074390437_libvlc_pysimplegui_python_python_vlc_vlc.txt
Q: EnvironmentError [Errno 39] "Directory not empty" while pip installing or updating a package in python3 Posting both Q & A here as there wasn't a post on SO for this kind of error yet, and other links on web-search led to unresolved gihub issues. Here is me just updating a package in my virtual python environment:...
EnvironmentError [Errno 39] "Directory not empty" while pip installing or updating a package in python3
Posting both Q & A here as there wasn't a post on SO for this kind of error yet, and other links on web-search led to unresolved gihub issues. Here is me just updating a package in my virtual python environment: (py36) $ pip install tornado -U Collecting tornado Downloading https://files.pythonhosted.org/packages/03/...
[ "Checking the actual folder highlighted in the error message:\n/mnt/STUFF/py36/lib/python3.6/site-packages/~ornado\n\nI found that there was another one of those .fuse-hidden... files sitting there which is typically while I'm using Geany (text editor) in my folders during its runtime, which then disappear after I'...
[ 1, 0, 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0055789261_pip_python.txt
Q: How to add restriction to Users in Odoo I have boolean validation field in a module called billing_notice. I only want some users to modify this field. Let's say, I have user1 user2 and user3 I only want user1 to have the power to modify this field. How can I do this restriction with python code or xml code? If yo...
How to add restriction to Users in Odoo
I have boolean validation field in a module called billing_notice. I only want some users to modify this field. Let's say, I have user1 user2 and user3 I only want user1 to have the power to modify this field. How can I do this restriction with python code or xml code? If you can provide some example I would love it. T...
[ "You can simply specify the rules inside ir.model.access.csv\nFor reference you can go to Odoo Technical Training repo and search for the file mentioned above.\nThere you will notice that some groups will have all access (notice the trailing 1,1,1,1 at the end of the row ) and some will have less ( 1,0,1,1 or 1,0,1...
[ 0 ]
[]
[]
[ "odoo", "odoo_8", "python", "xml" ]
stackoverflow_0074396343_odoo_odoo_8_python_xml.txt
Q: Removing Null Square Brackets from Pandas Dataframe I have a pandas dataframe in which some column contain empty sqaure brackets like below Code data = pd.DataFrame(dict(A=[5,3,5,6], C=[['man','talk'],['bar'],[],['bat','cat','mat']])) DataFrame A C 0 5 [man, talk] 1 3 [bar] 2 5 [] 3 6 [bat, ...
Removing Null Square Brackets from Pandas Dataframe
I have a pandas dataframe in which some column contain empty sqaure brackets like below Code data = pd.DataFrame(dict(A=[5,3,5,6], C=[['man','talk'],['bar'],[],['bat','cat','mat']])) DataFrame A C 0 5 [man, talk] 1 3 [bar] 2 5 [] 3 6 [bat, cat, mat] I need to remove the rows containing empty squ...
[ "You can check the length of the lists with str.len and slice using a boolean array when it is greater than 0:\ndata[data['C'].str.len().gt(0)]\n\nor, convert to boolean (which seems to be the fastest approach):\ndata[data['C'].astype(bool)]\n\noutput:\n A C\n0 5 [man, talk]\n1 3 ...
[ 3, 1, 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0071155792_pandas_python.txt
Q: React mapping not running the array Need some help here with React, I'm trying to fetch the data from my API, who has 3 records, but I can only manage to bring only one (though index or not). There's no problem with pagination or token, I just can't figure it out what's happening! If I call .map() in console.log I...
React mapping not running the array
Need some help here with React, I'm trying to fetch the data from my API, who has 3 records, but I can only manage to bring only one (though index or not). There's no problem with pagination or token, I just can't figure it out what's happening! If I call .map() in console.log I receive the records just fine. Probably ...
[ "Thanks to @pilchard in the comments, now its working!\n...\n let getAllVideos = async () => {\n if (validateToken(token)) {\n let response = await fetch(`${config.URL}videos/`,{\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer...
[ 0 ]
[]
[]
[ "api", "django_rest_framework", "javascript", "python", "reactjs" ]
stackoverflow_0074396936_api_django_rest_framework_javascript_python_reactjs.txt
Q: How would I write this function in 1 return statement? So I'm having trouble with writing this Cipher Function in one line. I've tried using the result methods with the if and else statements. For instance I know that the I need to do the else statement first before the if statement buts I could be wrong. So I'm t...
How would I write this function in 1 return statement?
So I'm having trouble with writing this Cipher Function in one line. I've tried using the result methods with the if and else statements. For instance I know that the I need to do the else statement first before the if statement buts I could be wrong. So I'm trying to figure this out. How would I write this function in...
[ "with all the caveats of Barmar's super valid comment (and this seems very Code Golf-y, which you might enjoy), but here we go:\nIn [7]: string = \"hello my #1 person!\"\n\nIn [8]: ''.join([(chr((ord(i) - (65 if i.isupper() else 97) + len(string)) % (26) + (65 if i.isupper() else 97)) if i.isalpha() else i) for i i...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074397270_python_python_3.x.txt
Q: Scikit Learn _ufuncs error in Jupyter notebooks Scikit learn has had _ufuncs errors for the past week and I can't figure out why. I'm using python on anaconda and a Dell computer, while using Jupyter notebooks. It was previously fine until last week when I got these issues I've looked on other stack overflow ques...
Scikit Learn _ufuncs error in Jupyter notebooks
Scikit learn has had _ufuncs errors for the past week and I can't figure out why. I'm using python on anaconda and a Dell computer, while using Jupyter notebooks. It was previously fine until last week when I got these issues I've looked on other stack overflow questions and tried them. I've tried uninstalling and rei...
[ "You are reporting that this fails:\nfrom scipy.spatial.distance import euclidean\n\nAfter executing $ conda install -c conda-forge scipy\nI obtain \"scipy 1.9.3 py310h240c617_2 conda-forge\"\nfor the 3.10.6 interpreter.\nHaving installed it,\nthe import happens without a hitch.\nConsider installing the package int...
[ 0 ]
[]
[]
[ "anaconda", "data_science", "jupyter_notebook", "python", "scikit_learn" ]
stackoverflow_0074394252_anaconda_data_science_jupyter_notebook_python_scikit_learn.txt
Q: Flask session object does not persist between requests despite hardcoded secret key I am currently running into an issue deploying a Flask app on Amazon's EB2 service. The Flask app works locally. When it is deployed, however, it only works for the first person who clicks the link. After that it throws the followi...
Flask session object does not persist between requests despite hardcoded secret key
I am currently running into an issue deploying a Flask app on Amazon's EB2 service. The Flask app works locally. When it is deployed, however, it only works for the first person who clicks the link. After that it throws the following error: Internal Server Error The server encountered an internal error and was unable ...
[ "I managed to solve it.\nThe error was that @before_first_request wrapper actually only ran once before first request ever made to the app. Hence, the session was actually only created and populated once.\nI fixed that error by adding the call to before_first_request function at the top of the main function.\n" ]
[ 0 ]
[]
[]
[ "amazon_ec2", "flask", "python", "session" ]
stackoverflow_0074289612_amazon_ec2_flask_python_session.txt
Q: Python - Rolling Function (Step - Pandas 1.5.0) I updated all the relevant libraries to the latest version, hence I thought that I could now use the new feature (step) in the rolling-function: print(df['600028.SS'].rolling(window=125, step=20).corr(df['600121.SS'])) However, when executing the commande, I always g...
Python - Rolling Function (Step - Pandas 1.5.0)
I updated all the relevant libraries to the latest version, hence I thought that I could now use the new feature (step) in the rolling-function: print(df['600028.SS'].rolling(window=125, step=20).corr(df['600121.SS'])) However, when executing the commande, I always get the following error message: NotImplementedError: ...
[ "The symptom is easily reproduced:\n>>> df = pd.DataFrame([dict(a=1, b=2)])\n>>> df.a.rolling(window=125, step=20).corr(df.b)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/Users/jhanley/miniconda3/envs/problems/lib/python3.10/site-packages/pandas/core/window/rolling.py\", l...
[ 1 ]
[]
[]
[ "pandas", "python", "rolling_computation" ]
stackoverflow_0074397365_pandas_python_rolling_computation.txt
Q: Python catch any exception, and print or log traceback with variable values When I catch unexpected error with sys.excepthook import sys import traceback def handleException(excType, excValue, trace): print 'error' traceback.print_exception(excType, excValue, trace) sys.excepthook = handleException h =...
Python catch any exception, and print or log traceback with variable values
When I catch unexpected error with sys.excepthook import sys import traceback def handleException(excType, excValue, trace): print 'error' traceback.print_exception(excType, excValue, trace) sys.excepthook = handleException h = 1 k = 0 print h/k This is output I get error Traceback (most recent call last)...
[ "By looking at the source of cgitb.py, you should be able to use something like this:\nimport sys\nimport traceback\nimport cgitb\n\ndef handleException(excType, excValue, trace):\n print 'error'\n cgitb.Hook(format=\"text\")(excType, excValue, trace)\n\nsys.excepthook = handleException\n\nh = 1\nk = 0\n\npri...
[ 9, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008702230_python.txt
Q: Error PyQT5 plainTextEdit, AttributeError, how to fix? Function in object: file ParserWindow.py: class Parser(object): def setupUi(self, ParserWindow): # code.... self.plainTextEdit = QtWidgets.QPlainTextEdit(self.layoutWidget_6) self.plainTextEdit.setStyleSheet("font-family: \'Roboto...
Error PyQT5 plainTextEdit, AttributeError, how to fix?
Function in object: file ParserWindow.py: class Parser(object): def setupUi(self, ParserWindow): # code.... self.plainTextEdit = QtWidgets.QPlainTextEdit(self.layoutWidget_6) self.plainTextEdit.setStyleSheet("font-family: \'Roboto Mono\';\n" "font-weight: 600;\n" "f...
[ "Try subcalssing QMainWindow directly. Then leave your log.py the way you have it in your question. I am assuming you also have already created the QApplication somewhere in your code prior to calling Parser().\nclass ParserWindow(QtWidgets.QMainWindow):\n def __init__(self, *args, obj=None, **kwargs):\n ...
[ 0 ]
[]
[]
[ "pyqt", "pyqt5", "python" ]
stackoverflow_0074375124_pyqt_pyqt5_python.txt
Q: Change Column Names in Dataframe via list of Column Names I have a dataframe with a ton of columns. I would like to change a list of a sub set of the column names to all uppercase. The code below doesn't change the column names and the other code I've tried produces errors: df[cols_to_cap].columns = df[cols_to_cap...
Change Column Names in Dataframe via list of Column Names
I have a dataframe with a ton of columns. I would like to change a list of a sub set of the column names to all uppercase. The code below doesn't change the column names and the other code I've tried produces errors: df[cols_to_cap].columns = df[cols_to_cap].columns.str.upper() What am I missing?
[ "Try the below code, this uses the rename function.\nrename_dict = {} \nfor each_column in list_of_cols_in_lower_case:\n rename_dict[each_column] = each_column.upper()\ndf.rename(columns = rename_dict , inplace = True ) #inplace to True if you want the change to be applied to the dataframe\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074397404_pandas_python.txt
Q: How to map multiple datasets based on the same row values of one column? I have three datasets, df1 name A B C D 0 Jeffrey Ray 0.171130 0.307791 -0.031378 0.366607 1 Crystal Roberts 0.429614 1.674201 0.176098 -1.289623 2 Paul Choute 0.396332 0.879003 ...
How to map multiple datasets based on the same row values of one column?
I have three datasets, df1 name A B C D 0 Jeffrey Ray 0.171130 0.307791 -0.031378 0.366607 1 Crystal Roberts 0.429614 1.674201 0.176098 -1.289623 2 Paul Choute 0.396332 0.879003 1.889926 0.745100 3 Amy Clements 1.452253 0.724694 -0.830645 -0.342138...
[ "How about:\ndfs = pd.concat([df1,df2,df3])\nout = dfs.groupby('name')['D'].sum()[dfs['name'].value_counts()==3]\n\nOutput:\n name\nAmy Clements -1.026414\nJeffrey Ray 2.155609\nStanley Coston 0.538049\nName: D, dtype: float64\n\n", "You can concat only the D column, using the names as index. Use dro...
[ 3, 3, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0070340453_pandas_python.txt
Q: ValueError: invalid literal for int() with base 10: '(?)' Dash Plotly Pandas I am creating a dashbaoard and using xlsx file as data source. Dashbaord has two inputs and one output. Inputs are Dropdown Radio Button Output is Treemap The output works fine for some of the dropdown options and raises following err...
ValueError: invalid literal for int() with base 10: '(?)' Dash Plotly Pandas
I am creating a dashbaoard and using xlsx file as data source. Dashbaord has two inputs and one output. Inputs are Dropdown Radio Button Output is Treemap The output works fine for some of the dropdown options and raises following error for few options ValueError: invalid literal for int() with base 10: '(?)' my c...
[ "For future reference: I saw the same error with a Sunburst chart, it turns out that I forgot to set the values parameter which should be numeric.\n", "I encountered this exception when plotting a Plotly Treemap within a Streamlit app, which uses a drop-down to filter what to display. Selecting some values worked...
[ 0, 0 ]
[]
[]
[ "pandas", "plotly_dash", "python" ]
stackoverflow_0067239587_pandas_plotly_dash_python.txt
Q: Measuring the radial intensity distribution of equally spaced regions of circular-like shapes Hi I'm currently stuck on a problem that I'm hoping someone may be able to help me with. I've tried looking around for a solution but haven't had too much luck. I am a biologist starting to integrate automated image-analy...
Measuring the radial intensity distribution of equally spaced regions of circular-like shapes
Hi I'm currently stuck on a problem that I'm hoping someone may be able to help me with. I've tried looking around for a solution but haven't had too much luck. I am a biologist starting to integrate automated image-analysis into my workflow so forgive me if this isn't the right place to ask this question. I have perfo...
[ "Let's say we have the coordinates of the object-center (x0, y0) along with the set of M coordinates of the object-edge H={(hx1, hy1), (hx2, hy2), ..., (hxM, hyM)}.\nIn this context, our aim is to find the coordinates of N rings or closed curves that equally segment the object. All the rings have the same center as...
[ 0 ]
[]
[]
[ "image_segmentation", "python", "scikit_image" ]
stackoverflow_0074397315_image_segmentation_python_scikit_image.txt
Q: how to group list and print them out in python I need to make a function named f3Groups() that accepts one argument. As well as a list named cgList to represent the whole class, containing 3 lists representing the 3 groups. cgList can be an empty list but there cannot be any empty group, for example cgList = [] wh...
how to group list and print them out in python
I need to make a function named f3Groups() that accepts one argument. As well as a list named cgList to represent the whole class, containing 3 lists representing the 3 groups. cgList can be an empty list but there cannot be any empty group, for example cgList = [] when there is no student in this class. Return the cgL...
[ "\nI want 7 user inputs.\n\nThen you don't need a while True loop you just need to iterate until you reach 7. For that you can use a while i < 8 loop. And set i = 1\n\nUser input 1, 4 and 7 in one list group. User input 2 and 5 in one group. User input 3 and 6 in one group.\n\nIn your for loop you can use the i v...
[ 0, 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074397418_list_python_python_3.x.txt
Q: If substring in string, replace string with number I have the following mapping mapping = {'sum12':2, 'sum6':1, 'avg12':2, 'avg6':1, 'diff':3, 'mean':4} and I have a dataframe with variables like var1 var2 0 abc_sum12 mean_jkl 1 pqr_sum6 pqr_avg6 2 diff_xyz qwerty I...
If substring in string, replace string with number
I have the following mapping mapping = {'sum12':2, 'sum6':1, 'avg12':2, 'avg6':1, 'diff':3, 'mean':4} and I have a dataframe with variables like var1 var2 0 abc_sum12 mean_jkl 1 pqr_sum6 pqr_avg6 2 diff_xyz qwerty If any of the substrings are present in the strings in th...
[ "I believe if you replace using regex, it will partial match and give you the result you want. The only exception is the qwerty value which will remain unchanged. If you then coerce the entire df to numeric, it will return NaN for that value or any other non-numeric.\nimport pandas as pd\nmapping = {'sum12':2, 's...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074397430_python.txt
Q: How to change filename of csv file to yesterday's date Currently I'm adding a feature on my python script that can rename the converted file with yesterday date format right now my script is working with current date my plan is to adjust it to yesterday. can someone help me what I need to modify with my script I ...
How to change filename of csv file to yesterday's date
Currently I'm adding a feature on my python script that can rename the converted file with yesterday date format right now my script is working with current date my plan is to adjust it to yesterday. can someone help me what I need to modify with my script I already test some script but still not working :( my current...
[ "You can subtract a day. Use the datetime module to make it a bit easier.\nimport datetime as dt\nf\"myfile{(dt.date.today()-dt.timedelta(days=1)).strftime('%Y%m%d')}.csv\"\n\nYou may want to use dt.datetime.utcnow(), depending on how you deal with time zones.\n" ]
[ 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074397506_dataframe_datetime_pandas_python.txt
Q: trying to make a calculator but my first function(addition) isnt working as intended This is my first time messing around with functions and I'm trying to make a calculator. I have made 4 functions - each set for add, subtract, multiply and divide. I have 2 inputs for x and y and an operations variable for the cal...
trying to make a calculator but my first function(addition) isnt working as intended
This is my first time messing around with functions and I'm trying to make a calculator. I have made 4 functions - each set for add, subtract, multiply and divide. I have 2 inputs for x and y and an operations variable for the calculator to take in. you can see the code I got so far below. when I enter the two numbers ...
[ "The input you receive from the user is in the form of a string - '5'. When you add two strings together, they simply concatenate - '5' + '5' results in '55.\nIf you want the inputs to be converted to numbers, you need to make that conversion explicit using int or float. You can then add them up and have it behave ...
[ 0 ]
[]
[]
[ "calc", "python" ]
stackoverflow_0074397612_calc_python.txt