content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How can I replace blank values after doing str.findall to create a new column? This is the relevant line of code: dfc['Category'] = dfc['Description'].str.findall('Split|Transfer|REF', flags=re.IGNORECASE) It looks in the column description for Split, Transfer or REF and returns them if they appear. For the ones ...
How can I replace blank values after doing str.findall to create a new column?
This is the relevant line of code: dfc['Category'] = dfc['Description'].str.findall('Split|Transfer|REF', flags=re.IGNORECASE) It looks in the column description for Split, Transfer or REF and returns them if they appear. For the ones with none of those words in the description, it leaves the column blank and I am rea...
[ "A proposition using pandas.Series.str.join to flatten the list of the matches then pandas.DataFrame.replace to replace empty strings (0 match) with NaN values.\ndff['Category'] = (\n dff['Description'].str.findall('(Ref|BCA|Fund|Transfer)', flags=re.IGNORECASE)\n ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074414025_pandas_python.txt
Q: How can I print the cyclical manner of an array in counter-clockwise order? For example I have an array of: array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } Is it possible if I can make it go counter-clockwise starting from 9 to 5, then the output should look like: 9 6 3 2 1 4 7 8 5 I want it in plain python wi...
How can I print the cyclical manner of an array in counter-clockwise order?
For example I have an array of: array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } Is it possible if I can make it go counter-clockwise starting from 9 to 5, then the output should look like: 9 6 3 2 1 4 7 8 5 I want it in plain python with no imported modules, Thank you in advance! This is what i tried but it just re...
[]
[]
[ "Ok here's a recursive function that will spiral an array of any dimensions (square or rectangular); note that is empties the original array, so if you want to keep it, you'll have to first make a deepcopy of it:\narray = [\n [1,2,3,4,5,6],\n [7,8,9,10,11,12],\n [13,14,15,16,17,18],\n [19,20,21,22,23,24...
[ -1 ]
[ "cycle", "python" ]
stackoverflow_0074412448_cycle_python.txt
Q: Creating a histogram to display the frequency of vowels (a-e-i-o-u) from an input in Python with (*) So I've currently made a progress so far that I can get how many times letters (a-e-i-o-u) have been written in the sentence which was taken as an input. Also if there's any "the" in the sentence we should count th...
Creating a histogram to display the frequency of vowels (a-e-i-o-u) from an input in Python with (*)
So I've currently made a progress so far that I can get how many times letters (a-e-i-o-u) have been written in the sentence which was taken as an input. Also if there's any "the" in the sentence we should count them too. and at the end we should get something like this: e.g: input: Why little Dora herself came crying ...
[ "Your code can be simplified with a collections.Counter:\nimport collections\n\nallowed_chars = set(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ \")\ntext = input().lower()\n\nif not set(text).issubset(allowed_chars):\n print(\"Invalid input\")\n exit(1)\n\ncount = collections.Counter(text)\ncount['...
[ 0, 0 ]
[]
[]
[ "count", "histogram", "python" ]
stackoverflow_0074413840_count_histogram_python.txt
Q: Convert list of dictionaries into list of sets? I have dictionaries within a list like this: [{'market': 'singapore', 'abbreviation': 'sg', 'indexId': 'STI', 'indexName': 'STRAITS TIMES INDEX'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET100', 'indexName': 'SET100 INDEX'}, {'market': 'turkey', 'ab...
Convert list of dictionaries into list of sets?
I have dictionaries within a list like this: [{'market': 'singapore', 'abbreviation': 'sg', 'indexId': 'STI', 'indexName': 'STRAITS TIMES INDEX'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET100', 'indexName': 'SET100 INDEX'}, {'market': 'turkey', 'abbreviation': 'tr', 'indexId': 'XUTEK', 'indexName': '...
[ "Not a good idea. You might be able to do it using re.sub() (by converting your data to its string representation) but lets say \"nobody does that\". Regex is powerful tool to deal with other problems. Here better not using it.\nYou can do the following:\nres = [{*d.keys(), *d.values()} for d in lst]\nprint(res)\n\...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074414013_python_python_3.x.txt
Q: python program for finding greater number among of 4 numbers, using nested if WHAT IS WRONG IN THIS CODE? MY PC SHOWS NO OUTPUT WHEN C and D ARE LARGER NUMBERS? a=int(input("ent a no.")) b=int(input("ent a no.")) c=int(input("ent a no.")) d=int(input("ent a no.")) if a>b: if a>c: if a>d: p...
python program for finding greater number among of 4 numbers, using nested if
WHAT IS WRONG IN THIS CODE? MY PC SHOWS NO OUTPUT WHEN C and D ARE LARGER NUMBERS? a=int(input("ent a no.")) b=int(input("ent a no.")) c=int(input("ent a no.")) d=int(input("ent a no.")) if a>b: if a>c: if a>d: print(" a is greater") elif b>a: if b>c: if b>...
[ "Your final else won't get called if c > a but also wont print if c < d. This is also in pretty bad form, you may to structure it like this:\nif a > b and a > c and a > d:\n print(\"a is greater\"\n\n .\n .\n .\n\n", "Let's say the numbers you enter are 1, 2, 3, 2. In that case b is greater than a so ...
[ 0, 0 ]
[]
[]
[ "if_statement", "nested_if", "python" ]
stackoverflow_0074414096_if_statement_nested_if_python.txt
Q: Activating a conda env inside a Docker container when using docker-compose to start Jupyter notebook I have the following Dockerfile. FROM continuumio/miniconda3:4.5.11 # create a new user (defaults to 'al-khawarizmi') USER root ARG username=al-khawarizmi RUN useradd --create-home --home-dir /home/${username} ${u...
Activating a conda env inside a Docker container when using docker-compose to start Jupyter notebook
I have the following Dockerfile. FROM continuumio/miniconda3:4.5.11 # create a new user (defaults to 'al-khawarizmi') USER root ARG username=al-khawarizmi RUN useradd --create-home --home-dir /home/${username} ${username} ENV HOME /home/${username} # switch to newly created user to avoid running container as root USE...
[ "What happens is consequence of:\n\nIn the docker-compose.yml you've a typo in ip=0.0.0.0 which should be --ip=0.0.0.0 instead\nBinding the host's folder into the container is overriding .bashrc. An easy change would be mounting into a subdirectory\nYou need to run bash in interactive mode (-i) so that .bashrc is p...
[ 3, 0 ]
[]
[]
[ "conda", "docker", "docker_compose", "python" ]
stackoverflow_0053261888_conda_docker_docker_compose_python.txt
Q: Is there a structure in Python similar to C++ STL map? Is there a structure in Python which supports similar operations to C++ STL map and complexity of operations correspond to C++ STL map? A: dict is usually close enough - what do you want that it doesn't do? If the answer is "provide order", then what's actua...
Is there a structure in Python similar to C++ STL map?
Is there a structure in Python which supports similar operations to C++ STL map and complexity of operations correspond to C++ STL map?
[ "dict is usually close enough - what do you want that it doesn't do?\nIf the answer is \"provide order\", then what's actually wrong with for k in sorted(d.keys())? Uses too much memory, maybe? If you're doing lots of ordered traversals interspersed with inserts then OK, point taken, you really do want a tree.\ndic...
[ 18, 17, 9, 1, 1, 1, 0 ]
[ "use this : from sortedcontainers import SortedDict\ndon't use this: from collections import OrderedDict\n" ]
[ -2 ]
[ "c++", "python" ]
stackoverflow_0003654770_c++_python.txt
Q: Activate conda environment in docker I need to activate environment in docker and run a command in this environment. I create the environment, but then I try to activate this environment and run the command in this way: CMD [ "source activate mro_env && ipython kernel install --user --name=mro_env" ] but when I r...
Activate conda environment in docker
I need to activate environment in docker and run a command in this environment. I create the environment, but then I try to activate this environment and run the command in this way: CMD [ "source activate mro_env && ipython kernel install --user --name=mro_env" ] but when I ran docker I get an error: [FATAL tini (8)]...
[ "Followed this tutorial and it worked. Example Dockerfile:\nFROM continuumio/miniconda\nWORKDIR /usr/src/app\nCOPY ./ ./\nRUN conda env create -f environment.yml\n\n# Make RUN commands use the new environment:\nSHELL [\"conda\", \"run\", \"-n\", \"myenv\", \"/bin/bash\", \"-c\"]\n\nEXPOSE 5003\n# The code to run wh...
[ 33, 10, 9, 6, 5, 4, 3, 1, 1, 0, 0, 0 ]
[ "If you don't need to change environments away from the base you could also do this:\nCOPY conda.yaml /\nRUN { echo \"name: base\"; tail +2 /conda.yaml; } > /base.yaml\nRUN conda env update --file /base.yaml --prune\n\nThe environment in conda.yaml could have any name since we replace it with base.\n", "Since, co...
[ -1, -1 ]
[ "anaconda", "conda", "docker", "python" ]
stackoverflow_0055123637_anaconda_conda_docker_python.txt
Q: Working with ProcessPoolExecutor.(Windows) Where do all the classes and functions go, that have nothing to do with multiprocessing? +++ I EDITED MY QUESTION, TO REFLECT WHAT I THINK IS THE CORRECT STRUCTURE NOW, so that not necessary things don't get loaded in the child workers.. with the help of @booboo +++ THX W...
Working with ProcessPoolExecutor.(Windows) Where do all the classes and functions go, that have nothing to do with multiprocessing?
+++ I EDITED MY QUESTION, TO REFLECT WHAT I THINK IS THE CORRECT STRUCTURE NOW, so that not necessary things don't get loaded in the child workers.. with the help of @booboo +++ THX Where do all my classes and functions go(that have nothing to do with multiprocessing), so they are not loaded into every single process,....
[ "You haven't stated your platform as the guidelines for Python multiprocessing request. I will assume you are running under a platforms such as Windows that uses the spawn method to create new processes.\nIn that case every new process is initialized by starting off with essentially uninitialized memory into which ...
[ 1 ]
[]
[]
[ "multiprocessing", "process_pool", "python" ]
stackoverflow_0074412895_multiprocessing_process_pool_python.txt
Q: How to import folders in python? I have 3 folders of excel data and was asked to create a Machine Learning model using that data. But the problem is that the data does not have headers. How to import all those folders of data in Python. A: Python won't tell you the name of the columns. What python can do is help...
How to import folders in python?
I have 3 folders of excel data and was asked to create a Machine Learning model using that data. But the problem is that the data does not have headers. How to import all those folders of data in Python.
[ "Python won't tell you the name of the columns. What python can do is help you import and/or concatenate easily all of the excels.\nIn order to import them massively:\nimport os\nimport pandas as pd\n\n# List files in an specific folder\nos.listdir(source_directory)\n\n# Set source and destination directories\nsour...
[ 0 ]
[]
[]
[ "directory", "python", "subdirectory" ]
stackoverflow_0074414113_directory_python_subdirectory.txt
Q: Kivy screen manager only accepts screen widget This is my main code: from kivy.clock import Clock from kivy.uix.screenmanager import ScreenManager from kivymd.app import MDApp from kivy.lang import Builder from kivy.core.window import Window Window.size = (350,580) class LoginPage(MDApp): def build(self): ...
Kivy screen manager only accepts screen widget
This is my main code: from kivy.clock import Clock from kivy.uix.screenmanager import ScreenManager from kivymd.app import MDApp from kivy.lang import Builder from kivy.core.window import Window Window.size = (350,580) class LoginPage(MDApp): def build(self): global screen_manager screen_manager =...
[ "Yeah. ScreenManager only manages screen widgets. ScreenManager will not manage anything other than Screen widget and custom widgets made by Screen.\nAnd there is no point in adding splash screen to your kivy app. Because you have the flexibility to add the splash screen and all that stuff in buildozer.spec file .\...
[ 0 ]
[]
[]
[ "kivy", "python" ]
stackoverflow_0074407341_kivy_python.txt
Q: Upgrade version of Pandas I am running Python on a Windows machine at the following path: C:\WinPython-64bit-3.4.4.1 I am trying to upgrade to the latest version of pandas (currently running '0.17.1') but am having problems. I have looked at previous posts and have tried on the command line using : c:/>pip instal...
Upgrade version of Pandas
I am running Python on a Windows machine at the following path: C:\WinPython-64bit-3.4.4.1 I am trying to upgrade to the latest version of pandas (currently running '0.17.1') but am having problems. I have looked at previous posts and have tried on the command line using : c:/>pip install --upgrade pandas but just go...
[ "try \npip3 install --upgrade pandas\n\n", "Simple Solution, just type the below:\nconda update pandas \n\nType this in your preferred shell (on Windows, use Anaconda Prompt as administrator).\n", "Add your C:\\WinPython-64bit-3.4.4.1\\python_***\\Scripts folder to your system PATH variable by doing the followi...
[ 130, 43, 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0037954195_pandas_python.txt
Q: Your shell has not been properly configured to use 'conda activate' on dockerfile I am making anaconda3 environment with docker. However it shows the error like this below. I guess it is related with some shell problem.. but I can't fixed yet. CommandNotFoundError: Your shell has not been properly configured to us...
Your shell has not been properly configured to use 'conda activate' on dockerfile
I am making anaconda3 environment with docker. However it shows the error like this below. I guess it is related with some shell problem.. but I can't fixed yet. CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'. To initialize your shell, run $ conda init <SHELL_NAME> Curre...
[ "I believe your issue may be that you are sourcing your .bashrc on a separate line from the commands that rely on it. From the Dockerfile documentation:\n\nThe RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for ...
[ 5, 0 ]
[]
[]
[ "anaconda", "docker", "python" ]
stackoverflow_0060855061_anaconda_docker_python.txt
Q: TKinter start python button (first time using tkinter) I have a script, and woult like to have some imputs, outputs (as in the terminal) and a start running script. How can I do this? this is what I have for now: class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) ...
TKinter start python button (first time using tkinter)
I have a script, and woult like to have some imputs, outputs (as in the terminal) and a start running script. How can I do this? this is what I have for now: class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master exitButton = Button(self, tex...
[ "You have to place your app in the root, for example with pack(). You also have to change the name of the function, because it doesn't match the one you give to the button command.\nfrom tkinter import *\n\nclass Window(Frame):\n def __init__(self, master=None):\n Frame.__init__(self, master)\n sel...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074413403_python_tkinter.txt
Q: TypeError: Input 'e' of 'SelectV2' Op has type int64 that does not match type int32 of argument 't' I'm trying to follow this with another model called AraBART and another Arabic dataset called xlsum. I get an error while execution this instraction: model.fit( train_dataset, validation_data=validation_dataset,...
TypeError: Input 'e' of 'SelectV2' Op has type int64 that does not match type int32 of argument 't'
I'm trying to follow this with another model called AraBART and another Arabic dataset called xlsum. I get an error while execution this instraction: model.fit( train_dataset, validation_data=validation_dataset, epochs=1 ) Error: TypeError: in user code: /opt/conda/lib/python3.7/site-packages/keras/engine/tra...
[ "As the errors says, it seems that the variable 't' is supposed to have a dtype of 'int32', but your data samples are of type 'int64', so just need to convert your data samples to dtype 'int32' by using tf.cast(..., int32) or by setting variable 't' dtype to int64.\n" ]
[ 1 ]
[]
[]
[ "python", "training_data" ]
stackoverflow_0072587521_python_training_data.txt
Q: Dictionary to Pandas Dataframe without un-nesting some values I have the below dictionary, and I only want the columns to be key, metric and collectionperiod. These columns can have nested values which I would leave for now and un-nest later. But for some reason the values in the dataframe look off. {'key': {'form...
Dictionary to Pandas Dataframe without un-nesting some values
I have the below dictionary, and I only want the columns to be key, metric and collectionperiod. These columns can have nested values which I would leave for now and un-nest later. But for some reason the values in the dataframe look off. {'key': {'formFactor': 'PHONE', 'origin': 'https://www.sample'}, 'metrics': {'cu...
[ "Given the format of the data, consider using pd.DataFrame.from_dict() which outputs the desired format:\ndf = pd.DataFrame.from_dict([res])\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074414370_pandas_python.txt
Q: How to retain 2 decimals without rounding in python/pandas? How can I retrain only 2 decimals for each values in a Pandas series? (I'm working with latitudes and longitudes). dtype is float64. series = [-74.002568, -74.003085, -74.003546] I tried using the round function but as the name suggests, it rounds. I ...
How to retain 2 decimals without rounding in python/pandas?
How can I retrain only 2 decimals for each values in a Pandas series? (I'm working with latitudes and longitudes). dtype is float64. series = [-74.002568, -74.003085, -74.003546] I tried using the round function but as the name suggests, it rounds. I looked into trunc() but this can only remove all decimals. Then I...
[ "here is one way to do it\nassuming you meant pandas.Series, and if its true then\n# you indicated its a series but defined only a list\n# assuming you meant pandas.Series, and if its true then\n\nseries = [-74.002568, -74.003085, -74.003546] \ns=pd.Series(series)\n\n# use regex extract to pick the number until fi...
[ 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074414349_pandas_python.txt
Q: Why does my IDFT Computation differ from the value np.fft.ifft? I am trying to validate a simple IDFT routine I wrote - ############################################################### #My IDFT Routines ############################################################### def simple_idft(data_f): data_t_r = [] da...
Why does my IDFT Computation differ from the value np.fft.ifft?
I am trying to validate a simple IDFT routine I wrote - ############################################################### #My IDFT Routines ############################################################### def simple_idft(data_f): data_t_r = [] data_t_i = [] for ii in range(0,len(data_f)): tmp_r=0.00 ...
[ "Okay I found the problem... The plotting of the Numpy IDFT routine output is wrong, rather it should be -\n################################################################\n#Transform OFDM Data to time domain\n################################################################\ndef IDFT(OFDM_data):\n return np.fft...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074409694_numpy_python.txt
Q: Converting a list of lists to Json with hard coded format using python Consider i have a list of lists like below mylist = [(1, "Laprovitola", "Italy")] Imagine i have 1000 sublists. I'd like to make a format of mydict = [{ "ID": "1", "Name": "Laprovitola", "CountryOfReside...
Converting a list of lists to Json with hard coded format using python
Consider i have a list of lists like below mylist = [(1, "Laprovitola", "Italy")] Imagine i have 1000 sublists. I'd like to make a format of mydict = [{ "ID": "1", "Name": "Laprovitola", "CountryOfResidence": "Italy"} ] etc... The dict should have 8 values in total ID name ...
[ "One way of doing it is having a tuple of column names and zip it with each sub list:\nimport json\n\nmylist = [(1, \"Laprovitola\", \"Italy\")]\ncolumns = (\"ID\", \"name\", \"country\")\n\nlist_of_dicts = [dict(zip(columns, item)) for item in mylist]\n\nprint(json.dumps(list_of_dicts))\n\n", "You can unpack the...
[ 1, 1 ]
[]
[]
[ "dictionary", "json", "python" ]
stackoverflow_0074414001_dictionary_json_python.txt
Q: How to automatically download the files that have a download button on a webpage without BeautifulSoup? I have created a streamlit app that has a download button to download a csv file. I want to automatically download the content using "GET" or "POST" requests. is there anyway to do that? Here is my app URL: http...
How to automatically download the files that have a download button on a webpage without BeautifulSoup?
I have created a streamlit app that has a download button to download a csv file. I want to automatically download the content using "GET" or "POST" requests. is there anyway to do that? Here is my app URL: https://maalaei97-test2.hf.space/?__theme=light I tried to use urllib2.Request("GET", URL) but I receive None. I ...
[ "I've checked your website, it uses the JavaScript on that button to open a new window and download your CSV. The actual URL in your case is:\nhttps://maalaei97-test2.hf.space/media/c721b14394345aab14989004e9ce8a3bae6fbb02a8e8d6a41a4f5401.csv?title=app%20%C2%B7%20Streamlit\n\nI think you can download this with urll...
[ 0 ]
[]
[]
[ "html", "python", "python_requests", "url", "web_scraping" ]
stackoverflow_0074414388_html_python_python_requests_url_web_scraping.txt
Q: slash commands not working with openai with discod bot I have this command on my personnal bot that generates a image based on a discord users prompt but when i make it into a slash command, there is an error, i have done tests and the image is fine but it never sends the image back working code @client.command(al...
slash commands not working with openai with discod bot
I have this command on my personnal bot that generates a image based on a discord users prompt but when i make it into a slash command, there is an error, i have done tests and the image is fine but it never sends the image back working code @client.command(aliases=['gen']) async def genimage(ctx, *, ideel): print(...
[ "You have to respond to an interaction within 3 seconds, or the command will fail. If it takes longer to respond because you're doing something slow/intensive - like you generating images using AI, or API calls - you can defer. Deferring tells Discord \"I've received the interaction, but I'll respond later\".\nNote...
[ 1, 0 ]
[]
[]
[ "discord", "discord.py", "openai", "python" ]
stackoverflow_0074414236_discord_discord.py_openai_python.txt
Q: Show only words in their superlative form (ends in -est) in the word list; getting all character with est from nltk.corpus import shakespeare words = shakespeare.words('hamlet.xml') words = [word.lower() for word in words] def est(list): #Words in their superlative form (ends in -est) result = [] for wor...
Show only words in their superlative form (ends in -est) in the word list; getting all character with est
from nltk.corpus import shakespeare words = shakespeare.words('hamlet.xml') words = [word.lower() for word in words] def est(list): #Words in their superlative form (ends in -est) result = [] for word in list: if word.endswith("est"): result.append(word) return result pri...
[ "\nif 'est' in list[i]:\n\nYou're filtering based on if \"est\" is in the word, not if it ends. Use something like\nlist[i].endswith(\"est\")\n\ninstead.\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "nltk", "python" ]
stackoverflow_0074414540_jupyter_notebook_nltk_python.txt
Q: discord.py how do i list all the channels id's? Hello this my simple python code to get all channels in discord server . # IMPORT DISCORD.PY. ALLOWS ACCESS TO DISCORD'S API. import discord bot = discord.Client(intents=discord.Intents.default()) @bot.event async def on_ready(): text_channel_list = [] for g...
discord.py how do i list all the channels id's?
Hello this my simple python code to get all channels in discord server . # IMPORT DISCORD.PY. ALLOWS ACCESS TO DISCORD'S API. import discord bot = discord.Client(intents=discord.Intents.default()) @bot.event async def on_ready(): text_channel_list = [] for guild in bot.guilds: for channel in guild.text...
[ "Try this:\n@bot.event\nasync def on_ready():\n text_channel_list = []\n for guild in bot.guilds:\n for channel in guild.text_channels:\n text_channel_list.append(channel)\n print(channel.id, channel, guild.name)\n\n" ]
[ 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python", "python_3.x" ]
stackoverflow_0074414549_bots_discord_discord.py_python_python_3.x.txt
Q: ModuleNotFoundError: No module named 'flask_cors' on python anywhere To state from the get go this is no criticism of pythonanywhere, but I want to run a script that used to work using the line: from flask_cors import CORS But I get the following error mesage: ModuleNotFoundError: No module named 'flask_cors' T...
ModuleNotFoundError: No module named 'flask_cors' on python anywhere
To state from the get go this is no criticism of pythonanywhere, but I want to run a script that used to work using the line: from flask_cors import CORS But I get the following error mesage: ModuleNotFoundError: No module named 'flask_cors' Then tried to install in my version of python: pip3.9 install Flask-Cors T...
[]
[]
[ "I think you should try the following:\n\nGo to your Bash Console in \"Consoles\" menu.\nOpen the bash control\nSelect your virtualenv:\nFor example my virtualenv name is flaskapp, I would wirte \"workon\nflaskapp\" in the bash console.\nNow type in your desired command\npip3.9 install flask-cors in your case (try ...
[ -1 ]
[ "flask", "flask_cors", "python" ]
stackoverflow_0074414391_flask_flask_cors_python.txt
Q: Engines in Python Pandas read_csv In the document for pd.read_csv() method in pandas in python while describing the "sep" parameter there is a mention of engines such as C engine and Python engine. The document link is : https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html What are these en...
Engines in Python Pandas read_csv
In the document for pd.read_csv() method in pandas in python while describing the "sep" parameter there is a mention of engines such as C engine and Python engine. The document link is : https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html What are these engines? What is the role of each engine?...
[ "The pd.read_csv documentation notes specific differences between 'c' (default) and 'python' engines. The names indicate the language in which the parsers are written. Specifically, the docs note:\n\nWhere possible pandas uses the C parser (specified as engine='c'), but\n may fall back to Python if C-unsupported o...
[ 13, 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0052774459_csv_dataframe_pandas_python_python_3.x.txt
Q: Type casting a part of a Pandas dataframe (multiple columns) and assigning back does not preserve the dtype I'm relatively new to Pandas so this may be trivial. As this should be a common problem I already searched for similar problems to this but couldn't find anything (there are some resembling this but they per...
Type casting a part of a Pandas dataframe (multiple columns) and assigning back does not preserve the dtype
I'm relatively new to Pandas so this may be trivial. As this should be a common problem I already searched for similar problems to this but couldn't find anything (there are some resembling this but they pertain to columns with mixed dtypes). Sorry if this is a duplicate, kind TIA for pointers. Problem: A part of a dat...
[ "To my understanding, by performing the iloc[:,1:] reassignemnt, you are essentially performing:\ndf.iloc.__setitem__((i, slice(None)), value)\n\nIn which case you are setting the new values within the corresponding index locations for the dataframe you are overwriting, but not modifying the pre-existing properties...
[ 1 ]
[]
[]
[ "dtype", "pandas", "python" ]
stackoverflow_0074414521_dtype_pandas_python.txt
Q: Python: Get unbound class method How can you get a not bound class method? class Foo: @classmethod def bar(cls): pass >>> Foo.bar <bound method type.bar of <class '__main__.Foo'>> Edit: This is python 3. Sorry for the confusion. A: Python 3 does not have unbound methods. Forget about classmethods for ...
Python: Get unbound class method
How can you get a not bound class method? class Foo: @classmethod def bar(cls): pass >>> Foo.bar <bound method type.bar of <class '__main__.Foo'>> Edit: This is python 3. Sorry for the confusion.
[ "Python 3 does not have unbound methods. Forget about classmethods for a moment, and look at this:\n>>> class Foo:\n... def baz(self): pass\n>>> Foo.baz\n<function __main__.baz>\n\nIn 2.x, this would be <unbound method Foo.baz>, but 3.x does not have unbound methods.\nIf you want to get the function out of a bo...
[ 27, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0014574641_python_python_3.x.txt
Q: How to replace values in a column in pandas for values from a dictionary? I have a dataframe with two columns called df['job_title'], df['job_industry_category'], I have a dictonary_of_jobs where there's for every job_title appended a value that's a list of every job category where the job title appears, as follow...
How to replace values in a column in pandas for values from a dictionary?
I have a dataframe with two columns called df['job_title'], df['job_industry_category'], I have a dictonary_of_jobs where there's for every job_title appended a value that's a list of every job category where the job title appears, as follows: dictonary_of_jobs = {'Tax Accountant' : ['Health', 'Financial Services', 'P...
[ "You can do\ndf['job_category'] = df['job_category'].astype(str)\nfor v, w, z in zip(df.index, df['job_title'], df['job_category']):\n for x, y in dictonary_of_jobs.items():\n if w == x:\n df.at[v,'job_category'] = random.choice(y)\n\nprint(df)\n\n job_title job_categor...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074414003_dataframe_pandas_python.txt
Q: Calculating nth Roots of Unity in Python So, I'm trying to write an algorithm croot(k, n), that returns the kth root of unity with n == n. I'm getting mostly the right answer, however it's giving me really weird representations that seem wrong for certain numbers. Here is an example. import cmath def croot(k, n):...
Calculating nth Roots of Unity in Python
So, I'm trying to write an algorithm croot(k, n), that returns the kth root of unity with n == n. I'm getting mostly the right answer, however it's giving me really weird representations that seem wrong for certain numbers. Here is an example. import cmath def croot(k, n): if n<=0: return None return c...
[ "Here's cube roots of unity and 4th roots for a usage example. The input array should be interpreted as polynomial coefficients.\n>>> import numpy as np\n>>> np.roots([1, 0, 0, -1])\narray([-0.5+0.8660254j, -0.5-0.8660254j, 1.0+0.j ])\n>>> np.roots([1, 0, 0, 0, -1])\narray([ -1.00000000e+00+0.j, 5.5511151...
[ 7, 6, 2, 0 ]
[]
[]
[ "complex_numbers", "dft", "fft", "python" ]
stackoverflow_0015424449_complex_numbers_dft_fft_python.txt
Q: Getting rid of keys in nested dictionary that contain None values I have the following dict: dict_2 = { 'key1': {'subkey1': 2, 'subkey2': 7, 'subkey3': 5}, 'key2': {'subkey1': None, 'subkey2': None, 'subkey3': None}, } I am looking forward to clean dict_2 from those None values in the subkeys, by removing...
Getting rid of keys in nested dictionary that contain None values
I have the following dict: dict_2 = { 'key1': {'subkey1': 2, 'subkey2': 7, 'subkey3': 5}, 'key2': {'subkey1': None, 'subkey2': None, 'subkey3': None}, } I am looking forward to clean dict_2 from those None values in the subkeys, by removing the entire key with its nested dict: In short my output should be: dic...
[ "A recursive solution to remove all None, and subsequent empty dicts, can look this:\nCode:\ndef remove_empties_from_dict(a_dict):\n new_dict = {}\n for k, v in a_dict.items():\n if isinstance(v, dict):\n v = remove_empties_from_dict(v)\n if v is not None:\n new_dict[k] = v...
[ 6, 1, 0, 0 ]
[]
[]
[ "dictionary", "nested", "python" ]
stackoverflow_0048151953_dictionary_nested_python.txt
Q: Placing a label in another label tkinter im making a machine for Geometric volumes but i have a problem: my problem is When the user enters a number to perform calculations, a label shows the result, but what happens if the user wants to get the volume of the cylinder? Exactly >>23 >>34 It gives two numbers, one f...
Placing a label in another label tkinter
im making a machine for Geometric volumes but i have a problem: my problem is When the user enters a number to perform calculations, a label shows the result, but what happens if the user wants to get the volume of the cylinder? Exactly >>23 >>34 It gives two numbers, one for the previous volume and one for the current...
[ "its fixed!\nstep 1:first you need to create a Label then do this:\nlabel = Label(.......)\nlabel.pack_forget()\n\nstep 2: create a def and do what do you want then do this:\nlabel.pack()\nlabel.config(text = *what you have done*)\n\nnow its fixed!\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074401701_python_tkinter.txt
Q: two's complement of numbers in python I am writing code that will have negative and positive numbers all 16 bits long with the MSB being the sign aka two's complement. This means the smallest number I can have is -32768 which is 1000 0000 0000 0000 in two's complement form. The largest number I can have is 32767 w...
two's complement of numbers in python
I am writing code that will have negative and positive numbers all 16 bits long with the MSB being the sign aka two's complement. This means the smallest number I can have is -32768 which is 1000 0000 0000 0000 in two's complement form. The largest number I can have is 32767 which is 0111 1111 1111 1111. The issue I am...
[ "If you're doing something like\nformat(num, '016b')\n\nto convert your numbers to a two's complement string representation, you'll want to actually take the two's complement of a negative number before stringifying it:\nformat(num if num >= 0 else (1 << 16) + num, '016b')\n\nor take it mod 65536:\nformat(num % (1 ...
[ 11, 2, 0, 0 ]
[ "Since you haven't given any code examples, I can't be sure what's going on. Based on the numbers in your example, I don't think you're using bin(yourint) because you're output doesn't contain 0b. Maybe you're already slicing that off in your examples.\nIf you are storing your binary data as strings, you could do...
[ -1, -1 ]
[ "python", "twos_complement" ]
stackoverflow_0021871829_python_twos_complement.txt
Q: How to group lists according to at least one element in common in Python? I have a list of lists and I want to group them according to at least one element in common for at least two sublists of a group. Therefore, each sublist in a specific group doesn't need to have an element in common with every sublist in its...
How to group lists according to at least one element in common in Python?
I have a list of lists and I want to group them according to at least one element in common for at least two sublists of a group. Therefore, each sublist in a specific group doesn't need to have an element in common with every sublist in its group, but it is enough that each sublist has at least one element in common w...
[ "This implementation has been tested on the example provided. Efficiency and brevity have both been sacrificed for the sake of readability.\nThe general plan is this: we start with each list in a separate group, and then combine groups with overlapping elements. We continue until no two groups overlap, and then we ...
[ 2 ]
[]
[]
[ "group", "list", "python" ]
stackoverflow_0074414287_group_list_python.txt
Q: How to get week number between two months? I am running sql query in python, I have a requirement to dynamically generate dates and append it to my sql query.This script runs on every Monday. If the week of Monday falls between two months then I have to restrict the date range till last of the previous month (i.e...
How to get week number between two months?
I am running sql query in python, I have a requirement to dynamically generate dates and append it to my sql query.This script runs on every Monday. If the week of Monday falls between two months then I have to restrict the date range till last of the previous month (i.e 30th or 31st). Any Ideas on how to achieve this...
[ "You can use the following code to get the week number between two months:\nimport datetime\n\ndef get_weeks_between_dates(start_date, end_date):\n start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')\n end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n week_number = (end_date - start...
[ 0, 0 ]
[]
[]
[ "date", "datetime", "python", "python_3.x", "week_number" ]
stackoverflow_0074414248_date_datetime_python_python_3.x_week_number.txt
Q: TypeError: intents parameter must be Intents, not from disnake.ext import commands intents=discord.Intents.all() bot = commands.Bot( command_prefix=".", intents=intents, test_guilds=[1040948288054112316], ) @bot.slash_command(name="test", description="test") async def test(inter): await inte...
TypeError: intents parameter must be Intents, not
from disnake.ext import commands intents=discord.Intents.all() bot = commands.Bot( command_prefix=".", intents=intents, test_guilds=[1040948288054112316], ) @bot.slash_command(name="test", description="test") async def test(inter): await inter.response.send_message("test") Error: TypeError: inten...
[ "Are you using disnake? then try this:\nimport disnake\nfrom disnake.ext import commands\n\nintents=disnake.Intents.all()\n\n" ]
[ 0 ]
[]
[]
[ "android_intent", "command", "discord", "python", "slash" ]
stackoverflow_0074413276_android_intent_command_discord_python_slash.txt
Q: Merge Dataframes using List of Columns (Pandas Vlookup) I'd like to lookup several columns from another dataframe that I have in a list to bring them over to my main dataframe, essentially doing a "v-lookup" of ~30 columns using ID as the key or lookup value for all columns. However, for the columns that are the s...
Merge Dataframes using List of Columns (Pandas Vlookup)
I'd like to lookup several columns from another dataframe that I have in a list to bring them over to my main dataframe, essentially doing a "v-lookup" of ~30 columns using ID as the key or lookup value for all columns. However, for the columns that are the same between the two dataframes, I don't want to bring over th...
[ "You should be able to do something like the following:\ndf = pd.merge(df,df2[look_up_cols + ['ID']] ,\n on ='ID', \n how ='left')\n\nThis just adds the ID column to the look_up_cols list and thereby allows it to be used in the merge function\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074414728_dataframe_pandas_python.txt
Q: Create empty dictionaries from a list of strings If I have a list of strings like variations = ['color','size','quantity'] Is it someway possible to convert the strings in a list to empty dictionaries? The result I want is color = {} size = {} quantity = {} A: It is a bit tricky but you can use locals(). First...
Create empty dictionaries from a list of strings
If I have a list of strings like variations = ['color','size','quantity'] Is it someway possible to convert the strings in a list to empty dictionaries? The result I want is color = {} size = {} quantity = {}
[ "It is a bit tricky but you can use locals(). First you need to create a dictionary that includes key value pairs as your variable name and its value.\n1st way\nvariations = ['color','size','quantity']\n\nd = {} #temporary dictionary\nfor var in variations:\n d[var] = {}\n\nlocals().update(d) # update your local...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074414657_django_python.txt
Q: How do I specify a how a python class is called by another python class? I have two classes, for the example I will call them "Point" and "Vector" (like in math). I want one of the classes be called by the other to "convert" for example a point into the according vector ((1,2,1) -> (1,2,1)T). argsintfloat = lambda...
How do I specify a how a python class is called by another python class?
I have two classes, for the example I will call them "Point" and "Vector" (like in math). I want one of the classes be called by the other to "convert" for example a point into the according vector ((1,2,1) -> (1,2,1)T). argsintfloat = lambda l: all(isinstance(i, (int,float,complex)) for i in l) class Point: def ...
[ "While you could examine the arguments to Vector.__init__ to see if you got multiple numbers or a single Point, it would be better to use a class method to decompose the Point into values that can be passed to __init__.\nclass Vector:\n def __init__(self, *args):\n if not argsintfloat(args):\n ...
[ 2 ]
[]
[]
[ "class", "python" ]
stackoverflow_0074414735_class_python.txt
Q: Serial communication from arduino to Linux terminal I have been trying to print the serial output from the Arduino to the Linux terminal but the output sent to the terminal seems to be empty with string as shown in the figure below void setup() { Serial.begin(9600); void loop() { float zby = 4.54; Serial.println...
Serial communication from arduino to Linux terminal
I have been trying to print the serial output from the Arduino to the Linux terminal but the output sent to the terminal seems to be empty with string as shown in the figure below void setup() { Serial.begin(9600); void loop() { float zby = 4.54; Serial.println(zby); delay(1000); } I have tried using Raspberry Pi s...
[ "I think you havent set the baudrate properly. On arduino you set it to 9600 but on pc its 115200. The baud rate needs to be the same on the sending and the recieving side.\n" ]
[ 0 ]
[]
[]
[ "arduino", "linux", "python" ]
stackoverflow_0074414719_arduino_linux_python.txt
Q: How to set leverage for Kucoin futures using ccxt in Python? I am trying to place a market order with the leverage of 20 but when the order is placed I am getting the leverage of 1. I placed the market order like this: exchange = ccxt.kucoinfutures({ 'adjustForTimeDifference': True, "apiKey": '...', # Api ...
How to set leverage for Kucoin futures using ccxt in Python?
I am trying to place a market order with the leverage of 20 but when the order is placed I am getting the leverage of 1. I placed the market order like this: exchange = ccxt.kucoinfutures({ 'adjustForTimeDifference': True, "apiKey": '...', # Api key here "secret": '...', # Api Secret here 'password': '....
[ "Just resolved this issue you are not sending the leverage for the market in correct format. Giving leverage like this would work only for limit orders as the 'price' is NONE ccxt kucoin futures library. So the correct way to call this function for market orders will be\norder_response = exchange.createOrder('DOGEU...
[ 0 ]
[]
[]
[ "ccxt", "kucoin", "python" ]
stackoverflow_0074404770_ccxt_kucoin_python.txt
Q: python rename image in a folder I'm trying to rename all files in a folder (suppose the name is already sorted from 0 - 20), I want to rename them starting at a specified number. It really changes all images' names but the order is messed up. Right after it changes the name of 1st image, it jumps to the 10th image...
python rename image in a folder
I'm trying to rename all files in a folder (suppose the name is already sorted from 0 - 20), I want to rename them starting at a specified number. It really changes all images' names but the order is messed up. Right after it changes the name of 1st image, it jumps to the 10th image before going back to 2nd image. Is t...
[ "From the listdir documentation:\n\nThe list is in arbitrary order\n\nYou'll want to apply a natural sort to that returned list to get it in the order you expect. See for example Is there a built in function for string natural sort?\n" ]
[ 1 ]
[]
[]
[ "python", "rename" ]
stackoverflow_0074414770_python_rename.txt
Q: WTForms SelectField not properly coercing for booleans Here is my code: class ChangeOfficialForm(Form): is_official = SelectField( 'Officially Approved', choices=[(True, 'Yes'), (False, 'No')], validators=[DataRequired()], coerce=bool ) submit = SubmitField('Update statu...
WTForms SelectField not properly coercing for booleans
Here is my code: class ChangeOfficialForm(Form): is_official = SelectField( 'Officially Approved', choices=[(True, 'Yes'), (False, 'No')], validators=[DataRequired()], coerce=bool ) submit = SubmitField('Update status') For some reason, is_official.data is always True. I sus...
[ "While you've passed bools to the choices, only strings are used in HTML values. So you'll have the choice values 'True' and 'False'. Both of these are non-empty strings, so when the value is coerced with bool, they both evaluate to True. You'll need to use a different callable that does the right thing for the ...
[ 12, 0 ]
[]
[]
[ "flask", "flask_wtforms", "python", "wtforms" ]
stackoverflow_0033429510_flask_flask_wtforms_python_wtforms.txt
Q: PyObj-C/Objective-C: instance methods for my IBOutlet objects are not returning the objects values, dateValue: etc Currently I am trying to access really any of my object's in my XIBs object values. For example getting the NSData object or value from the current Date Picker in my preferences window (to see what da...
PyObj-C/Objective-C: instance methods for my IBOutlet objects are not returning the objects values, dateValue: etc
Currently I am trying to access really any of my object's in my XIBs object values. For example getting the NSData object or value from the current Date Picker in my preferences window (to see what date is currently selected). I have the following code in a IBAction from a button I've been pressing to get the current v...
[ "So it turns out I was using the wrong IBOutlet for the wrong button. I was referring to a NSPopUpBotton outlet which was self.weekSelectButton, when I was actually needing to refer to the self.datePicker variable in my code.\nSo to summarize the following code changes were made. If your have a problem that I had p...
[ 0 ]
[]
[]
[ "cocoa", "objective_c", "pyobjc", "python", "xib" ]
stackoverflow_0074409758_cocoa_objective_c_pyobjc_python_xib.txt
Q: Python, Copy Subfolders with its Contents into newly created Parent folders I have code with this logic: Make the directory from column "Folder_Name_to_create" if it exists. I am trying to add to this newly created directories a STATIC set of subfolders with its contents. Getting subfolders to be copied to the new...
Python, Copy Subfolders with its Contents into newly created Parent folders
I have code with this logic: Make the directory from column "Folder_Name_to_create" if it exists. I am trying to add to this newly created directories a STATIC set of subfolders with its contents. Getting subfolders to be copied to the newly created folder: subfolders_to_create = [] for entry in pl_Template_Dir.glob('*...
[ "You are calling mkdir on DataFrame, which has no such method. Although pl_dest / sd appends subdirectories to all parent folders in df, the call still returns a dataframe. You should make individual call on every element of the new df. It would look something like this:\nfor subfolder in subfolders_to_create:\n ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074414669_python.txt
Q: AttributeError: 'str' object has no attribute 'write' fix? def separate (gpsTrackPoints,gpsTrackPointsReorg): trackPoints = open (gpsTrackPoints,"r") trackPointsReorg = open (gpsTrackPointsReorg,"w") trackPoints.readline() lines = trackPoints.readlines() for line in lines: parts = line....
AttributeError: 'str' object has no attribute 'write' fix?
def separate (gpsTrackPoints,gpsTrackPointsReorg): trackPoints = open (gpsTrackPoints,"r") trackPointsReorg = open (gpsTrackPointsReorg,"w") trackPoints.readline() lines = trackPoints.readlines() for line in lines: parts = line.split(",") pointID = parts[0] long = parts[1] ...
[ "You should write to trackPointsReorg, not gpsTrackPointsReorg, which is the string.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074414818_python.txt
Q: attributeError:DecisionTreeClassifier object has no attribute And this is my code: from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier (random_state=5,criterion=‘gini’, splutter=‘random’) clf = clf.fit(train_X,train_Y) prediction = clf.prediction_proba(test_X)[:,1] Output is that: Deci...
attributeError:DecisionTreeClassifier object has no attribute
And this is my code: from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier (random_state=5,criterion=‘gini’, splutter=‘random’) clf = clf.fit(train_X,train_Y) prediction = clf.prediction_proba(test_X)[:,1] Output is that: DecisionTreeClassifier object has no attribute prediction_proba Can an...
[ "what you are looking for is predict_proba not prediction_proba\n" ]
[ 0 ]
[]
[]
[ "jupyter", "jupyter_notebook", "python" ]
stackoverflow_0074414801_jupyter_jupyter_notebook_python.txt
Q: Cartesian product of nested dictionaries of lists I have some code that generates all the combinations for a dictionary of lists import itertools import collections def gen_combinations(d): keys, values = d.keys(), d.values() combinations = itertools.product(*values) for c in combinations: yi...
Cartesian product of nested dictionaries of lists
I have some code that generates all the combinations for a dictionary of lists import itertools import collections def gen_combinations(d): keys, values = d.keys(), d.values() combinations = itertools.product(*values) for c in combinations: yield dict(zip(keys, c)) Let's say I have a dictionary A...
[ "Just create the product of the output of gen_combinations() for each key in the outer dictionary:\ndef gen_dict_combinations(d):\n keys, values = d.keys(), d.values()\n for c in itertools.product(*(gen_combinations(v) for v in values)):\n yield dict(zip(keys, c))\n\nThis is basically the same pattern,...
[ 3, 3, 1 ]
[]
[]
[ "cartesian_product", "combinations", "python", "python_3.x", "python_itertools" ]
stackoverflow_0050606454_cartesian_product_combinations_python_python_3.x_python_itertools.txt
Q: How does a Siamese neural network calculate distance between outputs with triplet loss? I am using a Siamese neural network to learn similarity between text. Here is a SNN network I created for this task: it feeds two inputs into a Bidirectional LSTM, which shares/updates weights, and then produces two outputs. Th...
How does a Siamese neural network calculate distance between outputs with triplet loss?
I am using a Siamese neural network to learn similarity between text. Here is a SNN network I created for this task: it feeds two inputs into a Bidirectional LSTM, which shares/updates weights, and then produces two outputs. The distance between these two outputs is then calculated. input_1 = Input(shape=(max_len,)...
[ "I'm not quite sure why you concatenated the three embedding vectors in the output. I suggest you peruse the document at https://keras.io/examples/vision/siamese_network/.\nThere, you'll find the below code snippet:\nclass DistanceLayer(layers.Layer):\n \"\"\"\n This layer is responsible for computing the dis...
[ 0 ]
[]
[]
[ "deep_learning", "neural_network", "python", "siamese_network" ]
stackoverflow_0071943687_deep_learning_neural_network_python_siamese_network.txt
Q: Python subprocess cannot process len(env["PATH"]) > 8191 I am writing tool that use subprocess.call and subprocess.Popen, but faced with an issue on Windows 10 that when env["PATH"] variable exceed size 8191~8192 characters subprocess cannot find program located in env["PATH"]: `cmake` is not recognized as an inte...
Python subprocess cannot process len(env["PATH"]) > 8191
I am writing tool that use subprocess.call and subprocess.Popen, but faced with an issue on Windows 10 that when env["PATH"] variable exceed size 8191~8192 characters subprocess cannot find program located in env["PATH"]: `cmake` is not recognized as an internal or external command, operable program or batch file. Loo...
[ "I don't use Windows, so these suggestions are just a shot in the dark. The first suggestion is to use the absolute path to cmake as I stated in the comment.\nThe second is to use shutil.which() to locate the path to cmake and use that:\nimport shutil\n\ncmake_path = shutil.which(\"cmake\")\nassert cmake_path is no...
[ 0 ]
[]
[]
[ "popen", "python", "python_3.x", "subprocess", "windows" ]
stackoverflow_0074412943_popen_python_python_3.x_subprocess_windows.txt
Q: Selenium Python .click() not working on one element So, I am trying to make a simple project that simply just auto clicks all the details to fill out a form to get ready to post. It works perfectly up until just one element. There are 2 very similar elements; ones a category and the other is a sub-category. It ...
Selenium Python .click() not working on one element
So, I am trying to make a simple project that simply just auto clicks all the details to fill out a form to get ready to post. It works perfectly up until just one element. There are 2 very similar elements; ones a category and the other is a sub-category. It states its unable to find the element, I'm fairly new to ...
[ "I've modified your code as below, try this:\ndriver.find_element('xpath', '//*[@id=\"app\"]/div[7]/div/div/div/div[2]/div/div/p[2]/a').click()\ntime.sleep(2)\ndriver.find_element('xpath', '//*[@id=\"app\"]/div[7]/div/div/div/div[2]/div/div/button[4]').click()\ngoogle_email = driver.find_element('xpath', '//*[@id=\...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074408441_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: How to move through files in python Does anyone know how to move through one file to the other if they are in the same directory? Example: in file "A.txt" is written the name of the next file, meaning "B.txt," then in "B.txt", is written the name of the next file - "C.txt," and the content of "C.txt" is "A.txt,"...
How to move through files in python
Does anyone know how to move through one file to the other if they are in the same directory? Example: in file "A.txt" is written the name of the next file, meaning "B.txt," then in "B.txt", is written the name of the next file - "C.txt," and the content of "C.txt" is "A.txt," forming the chain "A.txt"-"B.txt"-"C.tx...
[ "You can loop and at each iteration, read the content of the current file and then try to open a file using that content.\nCheck this example:\nfile = \"a.txt\"\n\nwhile True:\n try:\n print(f\"Opening file {file}\")\n\n with open(file) as f:\n file = f.read()\n except IOError:\n ...
[ 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0074414838_file_python.txt
Q: How to split/sort the dataframe into multiple ones in pandas? I have a text file containing some observational data where the daily observations are separated by rows starting from #. How can I group the data by day/month? I am attaching the text file here. Data Link import pandas as pd import glob import numpy as...
How to split/sort the dataframe into multiple ones in pandas?
I have a text file containing some observational data where the daily observations are separated by rows starting from #. How can I group the data by day/month? I am attaching the text file here. Data Link import pandas as pd import glob import numpy as np import matplotlib.dates as mdates from datetime import datetime...
[ "With the following toy file.txt extracted from yours:\n#INM00043333 2016 02 06 06 9999 7 ncdc-gts 116667 927167\n10 -9999 92500 -9999 -9999 -9999 -9999 50 41 \n10 -9999 85000 -9999 -9999 -9999 -9999 60 36 \n01 -9999 -9999 -9999 -9999 -9999 -9999 45 31 \n30 -9999 -9999 300 -9999 -9999...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "split" ]
stackoverflow_0074373046_dataframe_pandas_python_split.txt
Q: PySimpleGUI - can't update text fields This is my first try with PySimpleGUI. I've written a simple window with three output fields: Text Output Multiline The window paints fine, and the default values display. But I can't get any of the fields to update. Am I doing something stupid (almost certainly!)? Here is ...
PySimpleGUI - can't update text fields
This is my first try with PySimpleGUI. I've written a simple window with three output fields: Text Output Multiline The window paints fine, and the default values display. But I can't get any of the fields to update. Am I doing something stupid (almost certainly!)? Here is the code and result: Code Display Thanks in ...
[ "Something wrong\n\nsg.Window(...).read() not return window, but event, values. It also block the execution until an event happened. It looks the only event is to close the window, then the GUI cannot be updated after window destroyed.\nwindow[key].update(...) return None, None don't have method read to call. Metho...
[ 0 ]
[]
[]
[ "pysimplegui", "python" ]
stackoverflow_0074414237_pysimplegui_python.txt
Q: How to retrieve ORM object(s) instead of Row object(s)? I want to use imperative dataclass mapping to map my dataclasses to columns following tutorial i would define model: @dataclass class User: id: int = field(init=False) name: str = None fullname: str = None nickname: str = None addresses: L...
How to retrieve ORM object(s) instead of Row object(s)?
I want to use imperative dataclass mapping to map my dataclasses to columns following tutorial i would define model: @dataclass class User: id: int = field(init=False) name: str = None fullname: str = None nickname: str = None addresses: List[Address] = field(default_factory=list) and then map it t...
[ "As noted in the comments to the question:\n\nSession.execute() is used to return ORM objects.\nengine.execute() is considered legacy (deprecated) in SQLAlchemy 1.4 and will be removed in 2.0.\n\nSo if we do\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import select\nwith Session(engine) as sess:\n resul...
[ 0 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0074413736_orm_python_sqlalchemy.txt
Q: How to properly install qpsolvers for Python on Windows? I am trying to install qpsolvers using pip. The installation goes without errors, and the module imports properly afterwards. However, qpsolvers has no available solvers for it to use : import qpsolvers print(qpsolvers.available_solvers) returns []. Of cou...
How to properly install qpsolvers for Python on Windows?
I am trying to install qpsolvers using pip. The installation goes without errors, and the module imports properly afterwards. However, qpsolvers has no available solvers for it to use : import qpsolvers print(qpsolvers.available_solvers) returns []. Of course, trying to do anything results in an error: SolverNotFound...
[ "I install qpsolvers using pip install qpsolvers.\nthe link is here: https://pypi.org/project/qpsolvers/\nI run the test code to check it works:\nfrom numpy import array, dot\nfrom qpsolvers import solve_qp\nimport qpsolvers\n\nM = array([[1., 2., 0.], [-8., 3., 2.], [0., 1., 1.]])\nP = dot(M.T, M) # this is a pos...
[ 0, 0, 0 ]
[]
[]
[ "cvxpy", "python", "quadprog" ]
stackoverflow_0071517464_cvxpy_python_quadprog.txt
Q: Snakemake expand() arguments I inherited a complicated Snakemake setup. It uses a configfile that contains { "sub": [ 1234, ], "ses": [ "1" ], "task": [ "fake" ], "run": [ "1" ], "acq": [ "mb" ], "bids_dir": "../../bids" In the all recipe, it uses for input calls to exp...
Snakemake expand() arguments
I inherited a complicated Snakemake setup. It uses a configfile that contains { "sub": [ 1234, ], "ses": [ "1" ], "task": [ "fake" ], "run": [ "1" ], "acq": [ "mb" ], "bids_dir": "../../bids" In the all recipe, it uses for input calls to expand() that look like this. expand(...
[ "In general expand function requires the template and keyword arguments to use when filling in the template, like so:\nexpand('{a}_{b}', a='some', b='test')\n# this will return 'some_test'\n\nNow, in Python one can do dictionary unpacking by placing two asterisks before the dictionary '**some_dict'. What this does ...
[ 0 ]
[]
[]
[ "dictionary", "python", "python_3.x", "snakemake" ]
stackoverflow_0074414935_dictionary_python_python_3.x_snakemake.txt
Q: How to write data into a file I have two problems that are giving me issues. First issue: import requests import json name = 'Poe' poem = 'Raven' URL = f'https://poetrydb.org/author,title/{name};{poem}' json_object = json.loads(requests.get(URL).text) text=str(json_object) with open("choice_1.json", "w") as out...
How to write data into a file
I have two problems that are giving me issues. First issue: import requests import json name = 'Poe' poem = 'Raven' URL = f'https://poetrydb.org/author,title/{name};{poem}' json_object = json.loads(requests.get(URL).text) text=str(json_object) with open("choice_1.json", "w") as outfile: outfile.write(json_object...
[]
[]
[ "\nrunning the code gives me: TypeError: write() argument must be str, not list\n\nYou are attempting to write\noutfile.write(json_object)\n\n.write takes a string. json_object appears to be a dictionary. You tried to convert it to a string text but you aren't writing text.\n\nI want the saved file to read the same...
[ -1, -1, -1 ]
[ "python" ]
stackoverflow_0074414944_python.txt
Q: TypeError: argument of type 'ValueError' is not iterable in qpsolvers in python I am new to python optimization using qpsolvers and I have problem with running the following code: import numpy as np from qpsolvers import solve_qp P = np.array([4.,5.,5.,8.]).reshape(2,2) q = np.array([-3.,2.]).reshape(1,2)[0] G = ...
TypeError: argument of type 'ValueError' is not iterable in qpsolvers in python
I am new to python optimization using qpsolvers and I have problem with running the following code: import numpy as np from qpsolvers import solve_qp P = np.array([4.,5.,5.,8.]).reshape(2,2) q = np.array([-3.,2.]).reshape(1,2)[0] G = np.array([1,1,-2,-3,1,0,0,1,-1,0,0,-1]).reshape(6,2) h = np.array([2400.,-1100.,1200....
[ "Hi I think this is an issue both with the qpsolvers code and your example.\nThe qpsolvers error is that it has if \"matrix G is not positive definite\" in e: instead of if \"matrix G is not positive definite\" in str(e):.\nIf you correct this then the error ValueError: Buffer dtype mismatch, expected 'double' but ...
[ 1, 0 ]
[]
[]
[ "mathematical_optimization", "numpy", "python", "quadratic_programming" ]
stackoverflow_0064843700_mathematical_optimization_numpy_python_quadratic_programming.txt
Q: How to save and open string and float together in the same np.savetxt? I have a list, in python, which is given by: inputs = ['eos', 5, 10, 20, 30] The first element is a string and the others are int. I want to save this in a file and then open it in another python notebook, in a way that i can call input[0] and ...
How to save and open string and float together in the same np.savetxt?
I have a list, in python, which is given by: inputs = ['eos', 5, 10, 20, 30] The first element is a string and the others are int. I want to save this in a file and then open it in another python notebook, in a way that i can call input[0] and get as output the string "eos" and call the others elements, for exemple, as...
[ "I'd use pickle in this case.. It's super easy\n# data can be anything... \ndata0 = ['eos', 5, 10, 20, 30]\n# write data into file \nwith open('datafile.txt', 'wb') as f:\n pickle.dump(mylist, f)\n# read back and check\nf = open (\"datafile.txt\", \"rb\")\ndata1 = pickle.load(f)\n# [bonus] check data is same\ntr...
[ 0 ]
[]
[]
[ "database", "list", "numpy", "python" ]
stackoverflow_0074414695_database_list_numpy_python.txt
Q: How to run bashrc in screen detached mode linux for scheduling purpose I wrote a bash script called testingb.sh which runs bashrc file to activate created myenv environment python script. My bash script (testingb.sh) saved under /home/susan/Newfolder/ looks like below: #!/bin/bash source ~/.bashrc python /home/s...
How to run bashrc in screen detached mode linux for scheduling purpose
I wrote a bash script called testingb.sh which runs bashrc file to activate created myenv environment python script. My bash script (testingb.sh) saved under /home/susan/Newfolder/ looks like below: #!/bin/bash source ~/.bashrc python /home/susan/Newfolder/test.py My bashrc looks like below: export http_proxy=http:/...
[ "can you test below example and check can help you .\nYou can use the \"screen\" command to launch a bash process in a detached state. For example:\nscreen -d -m bash -c \"bashrc; while true; do echo 'Hello, world!'; sleep 1; done\"\n\nThis will launch a new screen session, run the bashrc command in it, and then ex...
[ 0 ]
[]
[]
[ "anaconda", "bash", "linux", "python", "shell" ]
stackoverflow_0074413937_anaconda_bash_linux_python_shell.txt
Q: How to implement pd.sort_values(ascending=False) with np.argsort? I have an Array which I need the indices of, that would sort it. The previous implementation used pd.sort_values() in a loop which I want to refactor. In order to do so I need to implement it with argsort. Here is what I tried: array = np.array([1.,...
How to implement pd.sort_values(ascending=False) with np.argsort?
I have an Array which I need the indices of, that would sort it. The previous implementation used pd.sort_values() in a loop which I want to refactor. In order to do so I need to implement it with argsort. Here is what I tried: array = np.array([1., 2., 0., 0., 9., 3., 7., 13., 4., 5., 15., 5., 12., 6., 3., ...
[ "One must revert the array before and then correct the indices:\narray = np.array([1., 2., 0., 0., 9., 3., 7., 13., 4., 5., 15., 5., 12., 6., 3.,\n 1., 1., 5., 1., 9., 15., 2., 4., 7., 16., 7., 8., 11., 15., 13., 4., 16., 11.])\nN = len(array)\nprint(list(np.abs(array[::-1].argsort...
[ 0 ]
[]
[]
[ "arrays", "matrix", "numpy", "pandas", "python" ]
stackoverflow_0074415052_arrays_matrix_numpy_pandas_python.txt
Q: How to get innerHTML of find_elements (not find_element) with Selenium My goal is to get this price text (2078--as shown in the pic), it works with find_element but the values in the output would be the same across the loop. heres my code: #Extracting the information from the results for entry in entries: #Empty ...
How to get innerHTML of find_elements (not find_element) with Selenium
My goal is to get this price text (2078--as shown in the pic), it works with find_element but the values in the output would be the same across the loop. heres my code: #Extracting the information from the results for entry in entries: #Empty list labels=[] #Extracting the Name, adress, Phone, and website: name= entr...
[ "To print all the texts of all the elements found by find_elements you need to do the following:\nphones = entry.find_elements(By.CLASS_NAME, 'xwpmRb.qisNDe')\nfor phone in phones:\n print(phone.text)\n\nOr you can create a variable that holds elements' texts using this list comprehension:\nphones = entry.find_e...
[ 0 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074410415_python_selenium_web_scraping.txt
Q: I cannot access a C++ class attribute using ctypes I am using ctypes to develop a kind of Python API for a C++ library. So far, everything has been working fine. However, I upgraded my OS from Ubuntu 20.4 LTS to 22.04 (now with Python3.10.6 and g++ 11.3.0, but even with g++ 9.x.x, the following problem occurs). Th...
I cannot access a C++ class attribute using ctypes
I am using ctypes to develop a kind of Python API for a C++ library. So far, everything has been working fine. However, I upgraded my OS from Ubuntu 20.4 LTS to 22.04 (now with Python3.10.6 and g++ 11.3.0, but even with g++ 9.x.x, the following problem occurs). The problem I have now is that I get a core dumped error w...
[ "Set .argtypes and .restype for the functions called by ctypes. The 64-bit pointer returned by CreateTest is being truncated due to the return value defaulting to a c_int (a 32-bit integer).\nWorking code:\ntest.cpp\n#include <stdio.h>\n\n#ifdef _WIN32\n# define API __declspec(dllexport)\n#else\n# define API\n#...
[ 3 ]
[]
[]
[ "c++", "ctypes", "python" ]
stackoverflow_0074414406_c++_ctypes_python.txt
Q: find duplicate count in a list I came up with this logic to count the duplicate 1 take input for list length 2 take input of list 3 search in list for the values from zero to last index increment the counter. I am getting error can anyone help to fix it, I know my this not accurate way to do this can someone help ...
find duplicate count in a list
I came up with this logic to count the duplicate 1 take input for list length 2 take input of list 3 search in list for the values from zero to last index increment the counter. I am getting error can anyone help to fix it, I know my this not accurate way to do this can someone help me out n = int(input()) l1=[] for i ...
[ "Simply use set() to remove the duplicates from the original list, then take the length of the original list minus the length of the new set:\ns = set(l1)\ncount = len(l1) - len(s)\n\nI don't think this is the optimal way to do it, but it is the shortest and most intuitive way.\n" ]
[ 1 ]
[ "There is a pre built function in list to count the elements\ndata = [1,2,3,4,1,4]\nprint(\"Count of 1 =\", data.count(1))\nprint(\"Count of 2 =\", data.count(2))\nprint(\"Count of 3 =\", data.count(3))\nprint(\"Count of 4 =\", data.count(4))\n\nBut if the number of duplicate elements is what is expected then count...
[ -2 ]
[ "linear_search", "list", "python" ]
stackoverflow_0074414987_linear_search_list_python.txt
Q: Verifying SendGrid's Signed Event Webhook in Django I am trying to get signed from sengrid Webhook: https://docs.sendgrid.com/for-developers/tracking-events/getting-started-event-webhook-security-features from sendgrid.helpers.eventwebhook import EventWebhook, EventWebhookHeader def is_valid_signature(request): ...
Verifying SendGrid's Signed Event Webhook in Django
I am trying to get signed from sengrid Webhook: https://docs.sendgrid.com/for-developers/tracking-events/getting-started-event-webhook-security-features from sendgrid.helpers.eventwebhook import EventWebhook, EventWebhookHeader def is_valid_signature(request): #event_webhook_signature=request.META['HTTP_X_TWILIO_EMAI...
[ "I think the issue is that you are calling:\ntext = json.dumps(str(request.body))\n\njson.dumps serializes an object to a JSON formatted string, but str(request.body) is already a string.\nTry just\ntext = str(request.body)\n\n", "I found the solution, my function is now like this:\ndef is_valid_signature(request...
[ 1, 0, 0 ]
[]
[]
[ "django", "python", "sendgrid" ]
stackoverflow_0071663988_django_python_sendgrid.txt
Q: How to compare each row of a column to all the other row of the same column of a large dataset in python? I have a dataframe which have two columns - unique_id and id_string.The dataframe looks likes: | unique_id| id_string | | -------- | --------- | | 123 | abc | | 456 | pqr | | 789 | x...
How to compare each row of a column to all the other row of the same column of a large dataset in python?
I have a dataframe which have two columns - unique_id and id_string.The dataframe looks likes: | unique_id| id_string | | -------- | --------- | | 123 | abc | | 456 | pqr | | 789 | xyz | | 000 | lmn | I want to compare the id_string of each unique_id with the all the other i...
[ "You should use sorting. Sort by id_string column and iterate over all rows - whenever the next value in id_string column is equal to the current one - you have a duplicate. You can also look back (which might be easier) with the last value of id_string:\ninput_df = pd.DataFrame()\nprev_id_string = None # or some ...
[ 0 ]
[]
[]
[ "iteration", "pandas", "python", "string" ]
stackoverflow_0074411918_iteration_pandas_python_string.txt
Q: check element in list and return a value and store in another list I am trying to identify few IP accordingly, the requirement as below: There is a list of IP called ip_addresses. There is a list of registered IP called registered_list. There is a list of banned IP called banned_list. If the element in ip_addres...
check element in list and return a value and store in another list
I am trying to identify few IP accordingly, the requirement as below: There is a list of IP called ip_addresses. There is a list of registered IP called registered_list. There is a list of banned IP called banned_list. If the element in ip_addresses in registered_list, return 1 and store in another list. If the elem...
[ "That's happening because you are using check variable in loop and don't reset it. So after first iteration your check variable already have value equal 1, because of logic of your code and first from ip_addresses list in registered_list list.\nTo fix this, set check to 0 in the beginning of every iteration:\nfor i...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074414890_python.txt
Q: What does it mean an installed application must be "visible" to a directory in linux? I'm trying deploy openstack using Kolla-ansible approach with this guide using a virtual environment. while I write the command: kolla-ansible -i ./all-in-one bootstrap-servers I get this error: TASK [openstack.kolla.packages : ...
What does it mean an installed application must be "visible" to a directory in linux?
I'm trying deploy openstack using Kolla-ansible approach with this guide using a virtual environment. while I write the command: kolla-ansible -i ./all-in-one bootstrap-servers I get this error: TASK [openstack.kolla.packages : Install packages] ***************************************************** [WARNING]: Updating...
[ "A python package can be installed in a number of locations. Different virtual environments are configured to search different sets of such locations, so some of these virtual environments may be able to find a package and others may not.\nA virtual environment created in the default way will not be able to find gl...
[ 1, 0 ]
[]
[]
[ "ansible", "linux", "openstack", "python" ]
stackoverflow_0074412463_ansible_linux_openstack_python.txt
Q: AttributeError: 'str' object has no attribute 'cursor' This Python class is supposed to query an SQLite database: import sqlite3 class Database: def __init__(self): self.connection = sqlite3.connect('devel.db') self.cursor = self.connection.cursor() self.connection.commit() de...
AttributeError: 'str' object has no attribute 'cursor'
This Python class is supposed to query an SQLite database: import sqlite3 class Database: def __init__(self): self.connection = sqlite3.connect('devel.db') self.cursor = self.connection.cursor() self.connection.commit() def query(self, query, params=()): if params == (): ...
[ "To call the query method, you need to first create an instance of the Database class.\nBasically, by calling the query method without an object, you are passing the query string as the self parameter, so it tries to access the cursor() method in a string and not the class itself.\nSo instead of executing this code...
[ 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074414993_python_sqlite.txt
Q: Tensorflow.keras.layers "unresolved reference" in pycharm I just installed tensorflow, and am trying to get the basics to work. However, the import statement is underlined in red, with message "unresolved reference 'layers' ". The code does run correctly though. I've tried some of the suggestions in this question:...
Tensorflow.keras.layers "unresolved reference" in pycharm
I just installed tensorflow, and am trying to get the basics to work. However, the import statement is underlined in red, with message "unresolved reference 'layers' ". The code does run correctly though. I've tried some of the suggestions in this question: PyCharm shows unresolved references error for valid code. Howe...
[ "Pycharm may just recognize the sub-package\n\n(1) package tensorflow's structure :\n ├── tensorflow\n ├── _api\n ├── compiler\n ├── contrib\n ├── core\n ├── examples\n ├── include\n ├── python\n ├── tools\n └── __init__.py\n\nyou can import the layer ...
[ 5, 5, 3, 0 ]
[]
[]
[ "pycharm", "python", "tensorflow" ]
stackoverflow_0054686336_pycharm_python_tensorflow.txt
Q: How to read one single line of csv data in Python? There is a lot of examples of reading csv data using python, like this one: import csv with open('some.csv', newline='') as f: reader = csv.reader(f) for row in reader: print(row) I only want to read one line of data and enter it into various variables. H...
How to read one single line of csv data in Python?
There is a lot of examples of reading csv data using python, like this one: import csv with open('some.csv', newline='') as f: reader = csv.reader(f) for row in reader: print(row) I only want to read one line of data and enter it into various variables. How do I do that? I've looked everywhere for a working ex...
[ "To read only the first row of the csv file use next() on the reader object.\nwith open('some.csv', newline='') as f:\n reader = csv.reader(f)\n row1 = next(reader) # gets the first line\n # now do something here \n # if first row is the header, then you can do one more next() to get the next row:\n # row2 = ...
[ 162, 44, 28, 16, 15, 8, 6, 0 ]
[]
[]
[ "csv", "file", "iterator", "next", "python" ]
stackoverflow_0017262256_csv_file_iterator_next_python.txt
Q: delete only 1 instance of a string from a file I have a file that looks like this: 1234:AnneShirly:anneshirley@seneca.ca:4:5\[SRT111,OPS105,OPS110,SPR100,ENG100\] 3217:Illyas:illay@seneca.ca:2:4\[SRT211,OPS225,SPR200,ENG200\] 1127:john Marcus:johnmarcus@seneca.ca:1:4\[SRT111,OPS105,SPR100,ENG100\] 0001:Amin Malik:...
delete only 1 instance of a string from a file
I have a file that looks like this: 1234:AnneShirly:anneshirley@seneca.ca:4:5\[SRT111,OPS105,OPS110,SPR100,ENG100\] 3217:Illyas:illay@seneca.ca:2:4\[SRT211,OPS225,SPR200,ENG200\] 1127:john Marcus:johnmarcus@seneca.ca:1:4\[SRT111,OPS105,SPR100,ENG100\] 0001:Amin Malik:amin_malik@seneca.ca:1:3\[OPS105,SPR100,ENG100\] I ...
[ "Welcome to the site. You have a little ways to go to make this work. It would be good if you put some additional effort in to this before asking somebody to code this up. Let me suggest a structure for you that perhaps you can work on/augment and then you can re-post if you get stuck by editing your question ab...
[ 2, 1 ]
[]
[]
[ "file", "python" ]
stackoverflow_0074414914_file_python.txt
Q: Asus Aura Sync Python Script Not Running Correctly As Windows Scheduled Task I've made a Python script to turn on and off my Asus Aura Sync RGB components and everything works fine in an interactive scripting terminal. But when I try to run it as a Windows scheduled task the lights turn off and once the task ends ...
Asus Aura Sync Python Script Not Running Correctly As Windows Scheduled Task
I've made a Python script to turn on and off my Asus Aura Sync RGB components and everything works fine in an interactive scripting terminal. But when I try to run it as a Windows scheduled task the lights turn off and once the task ends the lights turn back on. This is the code I'm using. import win32com.client auraSd...
[ "\nTurn on the RGB by \"Armoury-Crate\"\n\nChange below:\n\n\nfor dev in devices:\n for i in range(dev.Lights.Count):\n dev.Lights(i).color = 0x00000000\n dev.Apply() #<--- Change to this level\n\n" ]
[ 0 ]
[]
[]
[ "asus", "python" ]
stackoverflow_0071475169_asus_python.txt
Q: Do an operation only if values from same column of two dataframes are the same I have a func_df with 4 functions: x y1 y2 y3 y4 0 -20.0 -0.839071 10.0 0.816164 -8795.000 1 -19.9 -0.865213 9.9 0.994372 -8667.619 2 -19.8 -0.889191 9.8 1.162644 -8541.472 3 -19.7 -0.910947 ...
Do an operation only if values from same column of two dataframes are the same
I have a func_df with 4 functions: x y1 y2 y3 y4 0 -20.0 -0.839071 10.0 0.816164 -8795.000 1 -19.9 -0.865213 9.9 0.994372 -8667.619 2 -19.8 -0.889191 9.8 1.162644 -8541.472 3 -19.7 -0.910947 9.7 1.319299 -8416.553 4 -19.6 -0.930426 9.6 1.462772 -8292.856 .. ... ...
[ "If the values of 'x' in test_df are unique you could merge the two dataframes on 'x'\nmerged_df = pandas.merge(test_df, func_df, on='x')\nabs_delta_y1 = (merged_df['y'] - merged_df['y1']).abs()\n\netc...\n\n", "create sample data:\nfunc_df=pd.DataFrame(data={'x':[-20.9,-20.8,-20.7,-20.6],'y1':[-0.12,-0.021,-0.04...
[ 2, 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074412645_dataframe_pandas_python.txt
Q: Python: How can I send files from a remote server to a local client I want to send files from my remote server to (a cloud linux machine) a local client (my machine). I have tried to use paramiko, but I just don't find it to have enough functionality. Please, if you have anything could help me then I would love to...
Python: How can I send files from a remote server to a local client
I want to send files from my remote server to (a cloud linux machine) a local client (my machine). I have tried to use paramiko, but I just don't find it to have enough functionality. Please, if you have anything could help me then I would love to here it.
[ "There are a few ways to do this, but the easiest way is to use the scp command.\nHere is an example:\nscp user@remote.server.com:/path/to/file /local/path/to/save/file\nYou will need to replace the user@remote.server.com and /path/to/file with the appropriate values for your situation.\n" ]
[ 0 ]
[]
[]
[ "client", "file", "linux", "python", "server" ]
stackoverflow_0074410026_client_file_linux_python_server.txt
Q: How to plot a 3D grid with a list of xmin, xmax, ymin, ymax, and z values in Python? I am just getting into Python and have run into a small problem that I am having trouble solving. I have five lists, each list contains a list of minimum x values, minimum y values, maximum x values, maximum y values and a list o...
How to plot a 3D grid with a list of xmin, xmax, ymin, ymax, and z values in Python?
I am just getting into Python and have run into a small problem that I am having trouble solving. I have five lists, each list contains a list of minimum x values, minimum y values, maximum x values, maximum y values and a list of z values. I am not sure how to turn these lists into a 3D surface plot and would welcome...
[ "you should probably familiarize yourself with matplotlib voxels\nthis is a simple unoptimized example of how to do it based on your input lists.\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx_min_list = [0, 5, 10, 15]\nx_max_list = [5, 10, 15, 20]\ny_min_list = [0, 5, 10, 15]\ny_max_list = [5, 10, 15, 2...
[ 0 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0074415030_matplotlib_plot_python.txt
Q: TypeError: __call__() missing 1 required positional argument: 'context' I want to create a program to send an email with a discord bot but when i laucnh my program i have this error. My code to send an email works fine in a separate file but when i put in in my python discord bot program there are a problem my pro...
TypeError: __call__() missing 1 required positional argument: 'context'
I want to create a program to send an email with a discord bot but when i laucnh my program i have this error. My code to send an email works fine in a separate file but when i put in in my python discord bot program there are a problem my programm : ` import smtplib from email.mime.text import MIMEText from email.mime...
[ "I invite you to read the docs. All bot.command() need to have one mandatory parameter: context. It gives you all the info about the command used, but you can just ignore it if you don't need it.\nAlso you don't need to check the command message with on_message(), the command does it automatically.\nYour code shoul...
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python", "python_3.9" ]
stackoverflow_0074415194_discord_discord.py_python_python_3.9.txt
Q: Need to print the first occurrence of k-size subsequence, but my code prints the last You are given a string my_string and a positive integer k. Write code that prints the first substring of my_string of length k all of whose characters are identical (lowercase and uppercase are different). If none such exists, pr...
Need to print the first occurrence of k-size subsequence, but my code prints the last
You are given a string my_string and a positive integer k. Write code that prints the first substring of my_string of length k all of whose characters are identical (lowercase and uppercase are different). If none such exists, print an appropriate error message (see Example 4 below). In particular, the latter holds whe...
[ "You need break. When you find the first occurrence you need to exit from the for-loop. You can do this with break. If you don't break you continue and maybe find the last occurrence if exists.\nmy_string = 'abaadddefggg'\nk = 3\ns=''\n\nfor i in range(len(my_string) - k + 1):\n if my_string[i:i+k] == my_string[...
[ 1, 1 ]
[]
[]
[ "for_loop", "if_statement", "list", "python" ]
stackoverflow_0074415166_for_loop_if_statement_list_python.txt
Q: Program doesn't work due to global variables Python program doesn't work due to global variables. It says global is used and cannot be used. I'm not sure how to fix this as global would be a good use. #!/usr/bin/python import sys, multiprocessing, time, socket, paramiko, warnings, re, os, select from os import sys...
Program doesn't work due to global variables
Python program doesn't work due to global variables. It says global is used and cannot be used. I'm not sure how to fix this as global would be a good use. #!/usr/bin/python import sys, multiprocessing, time, socket, paramiko, warnings, re, os, select from os import system from multiprocessing import Value from Queue i...
[ "This program is written using python2, but now it's out of support and you have python3. You can try using 2to3.py script to transform it. This will at least fix the parenthesis missing error. And you can update your question and post the error text, than I can help you fix the other problems.\n" ]
[ 1 ]
[]
[]
[ "brute_force", "python", "ssh" ]
stackoverflow_0074413645_brute_force_python_ssh.txt
Q: How to update python to the latest version on ArchLinux? How to install the latest python version 3.11.0 on ArchLinux through pacman? ArchLinux wiki says current version is 3.10, although python 3.11 has been officially released. When running sudo pacman -Syyu p I'm welcomed with warning: python-3.10.8-3 is up to ...
How to update python to the latest version on ArchLinux?
How to install the latest python version 3.11.0 on ArchLinux through pacman? ArchLinux wiki says current version is 3.10, although python 3.11 has been officially released. When running sudo pacman -Syyu p I'm welcomed with warning: python-3.10.8-3 is up to date. Am I doing something wrong?
[ "Use AUR like \"yay\" to get the new python3.11.\nIf you haven't installed yay on your system, setup yay by following these instructions\nRun this command after setting up yay in your system:\nyay -S python311\n\n" ]
[ 1 ]
[ "You can update python to the latest version on ArchLinux using the following command:\npacman -Syu python\n" ]
[ -2 ]
[ "archlinux", "linux", "pacman_package_manager", "python" ]
stackoverflow_0074405574_archlinux_linux_pacman_package_manager_python.txt
Q: Why is Visual Studio Code not showing mypy errors when I have my package installed in editable mode in a venv? I have a Python project which uses mypy for type checking. The root of my project contains a setup.py and the package folder rise, along with a virtual environment folder venv. Both my shells and VSCode a...
Why is Visual Studio Code not showing mypy errors when I have my package installed in editable mode in a venv?
I have a Python project which uses mypy for type checking. The root of my project contains a setup.py and the package folder rise, along with a virtual environment folder venv. Both my shells and VSCode are set to use this virtual environment. Most of the time, this setup works great: VSCode runs mypy every time I save...
[ "I ended up installing the Mypy extension for Visual Studio Code and removing mypy from my linters configuration. The extension doesn't suffer from this bug (or misconfiguration, or whatever it is), and it runs faster to boot.\n" ]
[ 0 ]
[]
[]
[ "mypy", "python", "visual_studio_code", "vscode_python" ]
stackoverflow_0074409601_mypy_python_visual_studio_code_vscode_python.txt
Q: How to convert price column to integer in Jupyter Notebook I've tried so hard to convert the price column to integer. I keep seeing the error message. A: Please follow the guidelines for posting good examples. However, I suggest using lambda function for this: car_sales["Price"] = car_sales["Price"].apply(lambda...
How to convert price column to integer in Jupyter Notebook
I've tried so hard to convert the price column to integer. I keep seeing the error message.
[ "Please follow the guidelines for posting good examples.\nHowever, I suggest using lambda function for this:\ncar_sales[\"Price\"] = car_sales[\"Price\"].apply(lambda x: int(x.replace('$','').replace(',','')))\n\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074413700_jupyter_notebook_pandas_python.txt
Q: Read Linux Path and append all data I want to read all csv files present in a Linux path and store it in a single data frame using Python. I am able to read the files but while storing, each file is getting created as dictionary object ex: df['file1'],df['file2'] and so on. Please let me know how can I store each ...
Read Linux Path and append all data
I want to read all csv files present in a Linux path and store it in a single data frame using Python. I am able to read the files but while storing, each file is getting created as dictionary object ex: df['file1'],df['file2'] and so on. Please let me know how can I store each csv file into separate data frame dynamic...
[ "from pathlib import Path\nimport pandas as pd\n\ndataframes = []\nfor p in Path(\"path/to/data\").iterdir():\n if p.suffix == \".csv\":\n dataframes.append(pd.read_csv(p))\n \ndf = pd.concat(dataframes)\n\nOr if you want to include subdirectories\nfrom pathlib import Path\nimport pandas as pd\npat...
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074415252_dataframe_python.txt
Q: Generate a PointCloud object in Open3D from RealSense data I'm trying to convert data captured from an Intel RealSense device into an Open3D PointCloud object that I then need to process. For the moment I only have the rosbag sample files to work with, but I think a similar procedure should be used with the direct...
Generate a PointCloud object in Open3D from RealSense data
I'm trying to convert data captured from an Intel RealSense device into an Open3D PointCloud object that I then need to process. For the moment I only have the rosbag sample files to work with, but I think a similar procedure should be used with the direct stream from the device. So far I managed to read and display th...
[ "For those who encounter the same problem: The point is that functions from different branches are used here, one from Legacy, the other from Tensor. In this case used o3d**.t.**io + o3d.geometry. You need to use either o3d.io + o3d.geometry, or o3d.t.io + o3d.t.geometry. Another option is using to_legacy()/from_le...
[ 0 ]
[]
[]
[ "open3d", "python", "realsense", "rosbag" ]
stackoverflow_0069771059_open3d_python_realsense_rosbag.txt
Q: Leetcode 792: number of matching subsequences, wrong answer I'm experiencing an issue with Leetcode #792, what I understand from the description is that abc possible subsequences are a, b, c, ab, ac, bc, abc. Impossible subsequences would be f, gh, bb, cc, ca ... If this understanding is correct, a simple solution...
Leetcode 792: number of matching subsequences, wrong answer
I'm experiencing an issue with Leetcode #792, what I understand from the description is that abc possible subsequences are a, b, c, ab, ac, bc, abc. Impossible subsequences would be f, gh, bb, cc, ca ... If this understanding is correct, a simple solution would be keeping count of all letters and where we are in a give...
[ "Your function does not take into account that although a character might be available, it only occurs before the characters you have already used, and so it actually is not available.\ncounts does not give any clue where a letter occurs, so counts would be the same whether s is \"ab\" or \"ba\", yet it is clear th...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074414718_python.txt
Q: Custom Mixin to get verbose name not rendering when called in Django DetailView I have created a custom mixin GetVerboseNameMixin in order to get the verbose name of model fields, and then display these in my html template using a DetailView. However, whenever I try and render the list of verbose names nothing is ...
Custom Mixin to get verbose name not rendering when called in Django DetailView
I have created a custom mixin GetVerboseNameMixin in order to get the verbose name of model fields, and then display these in my html template using a DetailView. However, whenever I try and render the list of verbose names nothing is returned, and I cannot work out why. Mixin.py: class GetVerboseNameMixin: def get...
[ "I do not get how verbose_model_fields is getting passed to the template from the view, and also, I did not find any reference in DetailView documentation. I assume you want to have this custom implementation, if so, then you need to pass along this parameter via context:\nclass ShowProfileView(GetVerboseNameMixin,...
[ 2 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0074415215_django_django_models_django_templates_django_views_python.txt
Q: How to loop through 4 lists in and identify common elements in python? I have extracted the first two lists called station1 ad station2 from a csv file, which contains the connections between two stations, time and the line. however, it just contains the id numbers of the stations and not the name. The IDs of the ...
How to loop through 4 lists in and identify common elements in python?
I have extracted the first two lists called station1 ad station2 from a csv file, which contains the connections between two stations, time and the line. however, it just contains the id numbers of the stations and not the name. The IDs of the stations are not in order. The other two lists called stationId and stationN...
[]
[]
[ "try this:\nfor i in zip(station1,station2):\nprint(i) #('11', '163') p.s. (station1[0],station2[0])\n #('11', '12') (station1[1],station2[1])\n\n" ]
[ -3 ]
[ "arrays", "for_loop", "list", "loops", "python" ]
stackoverflow_0074415408_arrays_for_loop_list_loops_python.txt
Q: How to import tensorflow and keras from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam from tensorflow.keras import layers model = Sequential([layers.Input((3, 1)), layers.LSTM(64), layers.Dense(32, activation='relu'), ...
How to import tensorflow and keras
from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam from tensorflow.keras import layers model = Sequential([layers.Input((3, 1)), layers.LSTM(64), layers.Dense(32, activation='relu'), layers.Dense(32, activation='relu')...
[ "It seems tensorflow has not installed in your system properly. Please follow the step by steps mentioned in this link to install tensorflow. Attached the same issue here for your reference,\nYou can run the .py file in jupyter notebook as command %run <filaname.py> after uploading the file in the same environment ...
[ 0 ]
[]
[]
[ "jupyter_notebook", "python", "tensorflow", "tensorflow2.0", "tf.keras" ]
stackoverflow_0074212539_jupyter_notebook_python_tensorflow_tensorflow2.0_tf.keras.txt
Q: simplify (a + b*(c+d)) / (c+d) in sympy Given an expression like a + b⋅(c + d) ───────────── c + d I would like to use sympy to simplify it to: a ───── + b c + d It works when I substitute (c+d) to e and back: import sympy as sp a,b,c,d,e = sp.symbols('a b c d e') expr = (a + b*(c+d)) / (c+d)...
simplify (a + b*(c+d)) / (c+d) in sympy
Given an expression like a + b⋅(c + d) ───────────── c + d I would like to use sympy to simplify it to: a ───── + b c + d It works when I substitute (c+d) to e and back: import sympy as sp a,b,c,d,e = sp.symbols('a b c d e') expr = (a + b*(c+d)) / (c+d) expr = expr.subs({(c+d):e}).simplify().subs(...
[ "Using apart helps simplifying fractions :\nexpr = sp.apart((a + b*(c + d))/(c + d), a)\n\nOutput is:\n a \n ───── + b\n c + d \n\n" ]
[ 3 ]
[]
[]
[ "python", "sympy" ]
stackoverflow_0074415310_python_sympy.txt
Q: How to find all permutations in a list of sets except permutations from own set? Note: I'm using Python 3. I have a list of sets of varying length, e.g.: list_1 = [{(3, 4), (3, 1), (3, 3), (3, 2), (3, 5)}, {(9, 10), (9, 7), (9, 8), (9, 9)}, {(2, 9), (3, 9), (1, 9)}, {(6, 2), (5, 2)}, {(8, 3)}] I want to find each...
How to find all permutations in a list of sets except permutations from own set?
Note: I'm using Python 3. I have a list of sets of varying length, e.g.: list_1 = [{(3, 4), (3, 1), (3, 3), (3, 2), (3, 5)}, {(9, 10), (9, 7), (9, 8), (9, 9)}, {(2, 9), (3, 9), (1, 9)}, {(6, 2), (5, 2)}, {(8, 3)}] I want to find each tuple pair permutation, except where the pair is of two tuples in the same set. For e...
[ "You can first permute the sets and then apply itertools.product to get the pairs from the sets.\nfrom itertools import permutations, product\n\nlist_1 = [{(3, 4), (3, 1), (3, 3), (3, 2), (3, 5)}, {(9, 10), (9, 7), (9, 8), (9, 9)}, {(2, 9), (3, 9), (1, 9)}, {(6, 2), (5, 2)}, {(8, 3)}]\n\npairs = [pair for ss in per...
[ 0 ]
[]
[]
[ "filter", "permutation", "python", "python_itertools" ]
stackoverflow_0074414916_filter_permutation_python_python_itertools.txt
Q: Unable to restore Visual Studio 2022 window (IDE itself) after minimizing I have Visual Studio 2022, newest version 17.1.0 running on Windows 10 Pro (up to date). This just started happening yesterday, so maybe it has something to do with the new update. I open a solution, everything is fine. If I minimize Visual ...
Unable to restore Visual Studio 2022 window (IDE itself) after minimizing
I have Visual Studio 2022, newest version 17.1.0 running on Windows 10 Pro (up to date). This just started happening yesterday, so maybe it has something to do with the new update. I open a solution, everything is fine. If I minimize Visual Studio, I can't get it back. It's running. I can see the toolbar icon looks lik...
[ "Have the same problem. Only awkward workaround I found so far was to use Process Explorer from Sysinternals, search for a process named devenv.exe, right click -> Window -> Bring To Front.\nUpdate - easier workaround: Click on the VS icon on the taskbar. Once it is selected, press Windows + Cursor Up.\n", "I do ...
[ 61, 28, 4, 3, 3, 0, 0, 0, 0 ]
[]
[]
[ "python", "visual_studio_2022", "windows" ]
stackoverflow_0071177450_python_visual_studio_2022_windows.txt
Q: Trying to switch different variables individually through Node Red I have code that is outputting an x value, a y value, a max value, a radius value, and a theta value within my Raspberry Pi that updates every second. An example output looks like this below: Highest Number: 31.9029 x: -15 y: 8 Radius: 17.0 Theta: ...
Trying to switch different variables individually through Node Red
I have code that is outputting an x value, a y value, a max value, a radius value, and a theta value within my Raspberry Pi that updates every second. An example output looks like this below: Highest Number: 31.9029 x: -15 y: 8 Radius: 17.0 Theta: -28.07 What I'm trying to do through Node Red on my Raspberry Pi is out...
[ "Add -u to the python arguments to get the python runtime to not buffer output to stdout so that Node-RED can parse it nicely.\n" ]
[ 0 ]
[]
[]
[ "node.js", "node_red", "output", "python", "raspberry_pi3" ]
stackoverflow_0074414940_node.js_node_red_output_python_raspberry_pi3.txt
Q: Python Regex to find CRLF I'm trying to write a regex that will find any CRLF in python. I am able to successfully open the file and use newlines to determine what newlines its using CRLF or LF. My numerous regex attempts have failed with open('test.txt', 'rU') as f: text = f.read() print repr(f.newlines) ...
Python Regex to find CRLF
I'm trying to write a regex that will find any CRLF in python. I am able to successfully open the file and use newlines to determine what newlines its using CRLF or LF. My numerous regex attempts have failed with open('test.txt', 'rU') as f: text = f.read() print repr(f.newlines) regex = re.compile(r"[^\r\n]+...
[ "You could try using the re library to search for the \\r & \\n patterns.\nimport re\n\nwith open(\"test.txt\", \"rU\") as f:\n for line in f:\n if re.search(r\"\\r\\n\", line):\n print(\"Found CRLF\")\n regex = re.compile(r\"\\r\\n\")\n line = regex.sub(\"\\n\", line)\n ...
[ 1, 0 ]
[]
[]
[ "newline", "python", "python_3.x", "regex" ]
stackoverflow_0074409566_newline_python_python_3.x_regex.txt
Q: Match 2 dataframes based on 3 columns, fill the column with matched values, Python I have df1 that looks like this: STATE YEAR EVENT_TYPE DAMAGE ALABAMA 1962 Tornado 27 ALABAMA 1962 Flood 7 ALABAMA 1963 Thunderstorm 12 ... and df2 that l...
Match 2 dataframes based on 3 columns, fill the column with matched values, Python
I have df1 that looks like this: STATE YEAR EVENT_TYPE DAMAGE ALABAMA 1962 Tornado 27 ALABAMA 1962 Flood 7 ALABAMA 1963 Thunderstorm 12 ... and df2 that looks like this: STATE YEAR TORNADO THUNDERSTORM FLOOD ALABAMA ...
[ "With the dataframes you provided:\nimport pandas as pd\n\ndf1 = pd.DataFrame(\n {\n \"STATE\": [\"ALABAMA\", \"ALABAMA\", \"ALABAMA\"],\n \"YEAR\": [1962, 1962, 1963],\n \"EVENT_TYPE\": [\"Tornado\", \"Flood\", \"Thunderstorm\"],\n \"DAMAGE\": [27, 7, 12],\n }\n)\n\ndf2 = pd.DataF...
[ 0 ]
[]
[]
[ "dataframe", "merge", "pandas", "python" ]
stackoverflow_0074367094_dataframe_merge_pandas_python.txt
Q: How to access variable generated in a 32 bit python process/thread from a main 64 bit process? main.py runs on an infinite loop, the Conda environment is called py39_64 it's python 3.9 64 Bit. data.py runs on periodically, the Conda environment is called py39_32 it's python 3.9 32 Bit. data.py has a variable calle...
How to access variable generated in a 32 bit python process/thread from a main 64 bit process?
main.py runs on an infinite loop, the Conda environment is called py39_64 it's python 3.9 64 Bit. data.py runs on periodically, the Conda environment is called py39_32 it's python 3.9 32 Bit. data.py has a variable called date which is a datetime object. I would like to access the date variable (format d/m/Y) from the ...
[ "a better approach would be to use a local socket between the two processes, which are sockets that are connected on your localhost.\n\nhave the 64 bit process as the server, and the 32 bit process as the client\nhave a thread in the 64 bit program. that will wait to be connected by the respective clients, using th...
[ 1 ]
[]
[]
[ "32bit_64bit", "64_bit", "multithreading", "python" ]
stackoverflow_0074405163_32bit_64bit_64_bit_multithreading_python.txt
Q: Difference in re.sub in Python between version 3.6 and 3.10 I just found strange (for me) difference in regular expression module in Python3. Is it some change between version 3.6.9 and 3.10.6 that I overlooked? In fact, it looks like regression to me. Code: import re RE_IP = re.compile(r'[0-9]*$') RE_IP.sub('0', ...
Difference in re.sub in Python between version 3.6 and 3.10
I just found strange (for me) difference in regular expression module in Python3. Is it some change between version 3.6.9 and 3.10.6 that I overlooked? In fact, it looks like regression to me. Code: import re RE_IP = re.compile(r'[0-9]*$') RE_IP.sub('0', '1.2.3.4') result in Python 3.10.6 is '1.2.3.00' and in Python 3...
[ "The problem is that your regular exception matches empty string. You can make it and it will work fine. I'll try to find documentation changes and update my answer.\nimport re\nRE_IP = re.compile(r'[0-9]+$')\nRE_IP.sub('0', '1.2.3.4')\n\nUPD:\nAccording to the comments by @j1-lee\nThis answer and this change\n\"Ch...
[ 1 ]
[]
[]
[ "python", "python_3.x", "python_re" ]
stackoverflow_0074415436_python_python_3.x_python_re.txt
Q: remove elements of one list from another list python Is there a pythonic way to remove elements from one list to another list? (Not removing all duplicates) For example, given [1, 2, 2, 3, 3, 3] (original list) and [1, 2, 3] (elements to be removed). It will return [2, 3, 3] We can assume that the two given lists ...
remove elements of one list from another list python
Is there a pythonic way to remove elements from one list to another list? (Not removing all duplicates) For example, given [1, 2, 2, 3, 3, 3] (original list) and [1, 2, 3] (elements to be removed). It will return [2, 3, 3] We can assume that the two given lists are always valid. Elements in the "to be removed" list wil...
[ "I would use a counter of the elements to be removed.\nSo, something like\nfrom collections import Counter \n\ndata = [1, 2, 2, 3, 3, 3]\nto_be_removed = [1, 2, 3, 3] # notice the extra 3\n\ncounts = Counter(to_be_removed)\n\nnew_data = []\nfor x in data:\n if counts[x]:\n counts[x] -= 1\n else:\n ...
[ 3, 0 ]
[ "This shoud work\n\noriginal = [1, 2, 2, 3, 3, 3] \nremove = [1, 2, 3] \n\nfor i, x in enumerate(original):\n if x in remove:\n original.pop(i)\n\nprint(original)\n\n" ]
[ -1 ]
[ "list", "list_comprehension", "python" ]
stackoverflow_0072587560_list_list_comprehension_python.txt
Q: return _get_backend_mod().show(*args, **kwargs) TypeError: _Backend.show() takes 1 positional argument but 3 were given How to fix these errors that are appearing again and again?????? A: You should check out matplotlib.pyplot.show() and .plot() documents to know how to use them correctly. You should use plt.plo...
return _get_backend_mod().show(*args, **kwargs) TypeError: _Backend.show() takes 1 positional argument but 3 were given
How to fix these errors that are appearing again and again??????
[ "You should check out matplotlib.pyplot.show() and .plot() documents to know how to use them correctly.\nYou should use plt.plot(x, y) instead of print(plt.show(x, y))\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(0, 10, 25)\ny = x * x + 2\nplt.plot(x, y)\nplt.show()\n\n" ]
[ 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074415356_python_visual_studio_code.txt
Q: Why my code fails to get the last item on a list while using a for loop? I wrote a program to compare numbers and get the minimum one of each couple. First number on input is count of couples and the other ones are the numbers just to be compared with each other 2 by 2. When i execute and give the input the last n...
Why my code fails to get the last item on a list while using a for loop?
I wrote a program to compare numbers and get the minimum one of each couple. First number on input is count of couples and the other ones are the numbers just to be compared with each other 2 by 2. When i execute and give the input the last number on the list is not included. I wanna know why and how to fix it. There i...
[ "Manual input isn't needed in sample code..\nthere is also no class-related issues, so skip both and just define your input as a list of integers:\ninp = [3, 5, 3, 2, 8, 100, 15]\n\nTry to keep functions simple, ideally only do \"one\" thing, e.g. return the list of miniums of pairs:\ndef min_of_two(length, pairs):...
[ 2, 0 ]
[ "I don't if this is true but my guess is that because the type if number are str python check digit by digit\nfor example:\n'100' & '15'\n\n1 is equal to 1\n\nmoves to the second digit\n\n5 is greater than 0\n\nso 15 is greater\nlike I said I don't if my theory is true or not but it makes sense\nhere is your code:\...
[ -1 ]
[ "for_loop", "python" ]
stackoverflow_0074415124_for_loop_python.txt
Q: How to fix NameError: name 'colors' is not defined Trying to plot this code but encountering this error and unable to find resolution of correcting: df = pd.read_csv("./train.csv") # Bar plot for exercise induced angina by heart disease. # Y: Yes, N: No fig, ax=plt.subplots(1, 3, figsize=(14, 5), sharey=True) l =...
How to fix NameError: name 'colors' is not defined
Trying to plot this code but encountering this error and unable to find resolution of correcting: df = pd.read_csv("./train.csv") # Bar plot for exercise induced angina by heart disease. # Y: Yes, N: No fig, ax=plt.subplots(1, 3, figsize=(14, 5), sharey=True) l = ['index', 'exercise angina'] df.groupby(by=['exercise a...
[ "You code suggests you have a list named colors, containing the color of elements you graph, but you don't have it. You can create it for examples like this:\ndf = pd.read_csv(\"./train.csv\")\ncolors = [\"red\", \"green\", \"blue\", \"grey\"]\n\n# Bar plot for exercise induced angina by heart disease.\n# Y: Yes, N...
[ 0 ]
[]
[]
[ "colors", "nameerror", "python" ]
stackoverflow_0074415609_colors_nameerror_python.txt