content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python Code to find the average number of trials in single dice Write a Pseudo code in Python ,to find the average number of trials to obtain all the six sides of a die atleast once. For Example, if you roll a 6-sided dice for the first time, you can get any of the 6 sides (1,2,3,4,5,6). Let us say you get 3. When...
Python Code to find the average number of trials in single dice
Write a Pseudo code in Python ,to find the average number of trials to obtain all the six sides of a die atleast once. For Example, if you roll a 6-sided dice for the first time, you can get any of the 6 sides (1,2,3,4,5,6). Let us say you get 3. When you roll it for the second time, you get 4. Now few rolls you got 5,...
[ "You must first understand and describe in natural language (plain English) how you are going to proceed.\nHere you have said:\n\nwe will conduct 10000 experiment\nan experiment consists in randomly rolling a die until the six sides have been found. The result of the experiment is the number of rolls\n\nFrom that p...
[ 0 ]
[]
[]
[ "dice", "for_loop", "python", "random", "while_loop" ]
stackoverflow_0074430414_dice_for_loop_python_random_while_loop.txt
Q: how to remove duplicates and leave one row containing value in another column pandas ID CAR TYPE 10 Audi1 F 20 BMW1 nan 50 BMW2 nan 10 Audi2 nan 30 Mazda F 10 Audi3 F 20 BMW3 Z 20 BMW4 F 20 BMW5 A 40 KIA G 10 Audi4 A 10 Audi5 G 10 Audi6 nan i would like deleate all duplicates(in cloumn ID), and leave...
how to remove duplicates and leave one row containing value in another column pandas
ID CAR TYPE 10 Audi1 F 20 BMW1 nan 50 BMW2 nan 10 Audi2 nan 30 Mazda F 10 Audi3 F 20 BMW3 Z 20 BMW4 F 20 BMW5 A 40 KIA G 10 Audi4 A 10 Audi5 G 10 Audi6 nan i would like deleate all duplicates(in cloumn ID), and leave only one row that has F in the TYPE column It should looks like: | ...
[ "Do step by step.\nRemove all the numbers from column CAR and filter based on Keyword\ndf[\"mask\"]=df[\"TYPE\"].str.contains(\"F\")\ndf=df.sort_values(\"mask\", ascending=False).drop_duplicates(subset=\"ID\", keep=\"first\").drop(columns=[\"mask\"])\n\nprint(df)\n\noutput # Tested\n ID CAR TYPE\n0 10 Audi1 ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074436811_pandas_python.txt
Q: Is there a maximum character limit to random seed? Is there a maximum number of characters (and therfore value) to the seed in Python? import random random.seed(13) # fine random.seed(1234567890) # also fine random.seed(31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421...
Is there a maximum character limit to random seed?
Is there a maximum number of characters (and therfore value) to the seed in Python? import random random.seed(13) # fine random.seed(1234567890) # also fine random.seed(3141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128...
[ "There is no max limit, but the input is eventually truncated to 20,000 bits.\nEven if you don't understand the algorithm (I don't), you can follow along in the source code.\nFirst, CPython splits the input into 32-bit chunks, and creates a bytearray out of them: https://github.com/python/cpython/blob/55edd0c185ad2...
[ 9, 3, 0 ]
[]
[]
[ "python", "python_2.7", "random", "seeding" ]
stackoverflow_0048503151_python_python_2.7_random_seeding.txt
Q: Cant open data base sqlalchemy Im using flask's sql alchemy and when i try to open the website it gives me this exception OperationalError sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file (Background on this error at: https://sqlalche.me/e/14/e3q8) Traceback (most recent ca...
Cant open data base sqlalchemy
Im using flask's sql alchemy and when i try to open the website it gives me this exception OperationalError sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file (Background on this error at: https://sqlalche.me/e/14/e3q8) Traceback (most recent call last) File "C:\Users\Nour\AppData...
[ "it worked magically again pretty sure it was the problem with the hosting\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074424499_python_sqlalchemy.txt
Q: How to use responses in neuralintents python library I created a voice assistant using python neuralintents module. but it didn't give a way to use responses in intents.json to give a feedback for user. Instead it is mapping response to a function. Is there any way to use responses in intents.json. I got this by w...
How to use responses in neuralintents python library
I created a voice assistant using python neuralintents module. but it didn't give a way to use responses in intents.json to give a feedback for user. Instead it is mapping response to a function. Is there any way to use responses in intents.json. I got this by watching this tutorial : https://youtu.be/SXsyLdKkKX0 Githu...
[ "if you want the assistant to speak the response you call the function talk and pass assistant.request(command) as parameter, but if you have bindings for adding todo ect. u first call the assistant.request(command) alone and after that you chec if the request has any response and if it does you pass the response t...
[ 0 ]
[]
[]
[ "json", "module", "python" ]
stackoverflow_0073346941_json_module_python.txt
Q: Why isn't my Operator Extra Link showing in Airflow? Using this as a reference: https://airflow.apache.org/docs/apache-airflow/stable/howto/define_extra_link.html I can not get links to show in the UI. I have tried adding the link within the operator itself and building the separate extra_link.py file to add it an...
Why isn't my Operator Extra Link showing in Airflow?
Using this as a reference: https://airflow.apache.org/docs/apache-airflow/stable/howto/define_extra_link.html I can not get links to show in the UI. I have tried adding the link within the operator itself and building the separate extra_link.py file to add it and the link doesn't show up when looking at the task in gra...
[ "The custom plugins should be defined in the plugins folder (by default $AIRFLOW_HOME/plugins) to be processed by the plugin manager.\nTry to create a new script in the plugins folder, and move AirflowExtraLinkPlugin class to this script, it should work.\n", "The issue turned out to be the inheritance. Attaching ...
[ 0, 0 ]
[]
[]
[ "airflow", "python" ]
stackoverflow_0074408366_airflow_python.txt
Q: text file to csv conversion how to get ride of split lines in input file I am trying to read a text file which has split lines randomly generated at column 28th from a third party. When I conver to csv it is fine but, when I feed the files to Athena, it is not able to read because of split. Is there a way to fine ...
text file to csv conversion how to get ride of split lines in input file
I am trying to read a text file which has split lines randomly generated at column 28th from a third party. When I conver to csv it is fine but, when I feed the files to Athena, it is not able to read because of split. Is there a way to fine the CR here and put it back as other lines are? Thanks, SM This is a code snip...
[]
[]
[ "If you are able to convert it successfully to CSV using pandas, you can try to save it as a CSV to feed into Athena.\n" ]
[ -1 ]
[ "dataframe", "python" ]
stackoverflow_0074436864_dataframe_python.txt
Q: Adding randomization to numpy function array_split Let's propose that we have an array arr and we want to divide the array into pieces saving the order of elements. It can be easily done using np.array_split: import numpy arr = np.array([0,1,2,3,4,5,6,7,8]) pieces = 3 np.array_split(arr,pieces) >>> [array([0, 1, 2...
Adding randomization to numpy function array_split
Let's propose that we have an array arr and we want to divide the array into pieces saving the order of elements. It can be easily done using np.array_split: import numpy arr = np.array([0,1,2,3,4,5,6,7,8]) pieces = 3 np.array_split(arr,pieces) >>> [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])] If arr.size % p...
[ "def random_arr_split(arr, n):\n # NumPy doc: For an array of length l that should be split into n sections,\n # it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n\n piece_lens = [arr.size // n + 1] * (arr.size % n) + [arr.size // n] * (n - arr.size % n)\n piece_lens_shuffled = np.ra...
[ 1 ]
[]
[]
[ "arrays", "numpy", "python", "random", "split" ]
stackoverflow_0074435351_arrays_numpy_python_random_split.txt
Q: Random sampling with replacement, increasing groupsize, sum and append in dataframe I have a dataframe which i'd like to repeatedly sample, with replacement. Everytime I sample the df, I would like to increase the size of the sample (n) by one, up to N. For example: id value_1 value_2 a 5 10 b 10 30 c 6 8 d 9...
Random sampling with replacement, increasing groupsize, sum and append in dataframe
I have a dataframe which i'd like to repeatedly sample, with replacement. Everytime I sample the df, I would like to increase the size of the sample (n) by one, up to N. For example: id value_1 value_2 a 5 10 b 10 30 c 6 8 d 9 12 Would result in something like id's sum_of_value_1 sum_of_value_2 ...
[ "you can use pandas.Dataframe.aggregate for summation of all columns and then use pandas.concat to concatinate the new single row dataframe at the end of a new dataframe that you can use as an accumulator of samples.\nmaybe something like this\nacc = df_groups.sample(1).aggregate('sum')\nfor n in range(2, df_group...
[ 0, 0 ]
[]
[]
[ "for_loop", "pandas", "python" ]
stackoverflow_0074436528_for_loop_pandas_python.txt
Q: One of methods doesn't work correctly when i call it I need to make two checks in log files and display the result. Separately methods work correctly, but when I run all code method hit_unique_check always return "PASS: All hits are unique.". For two of three .log files this result is incorrect. import os class R...
One of methods doesn't work correctly when i call it
I need to make two checks in log files and display the result. Separately methods work correctly, but when I run all code method hit_unique_check always return "PASS: All hits are unique.". For two of three .log files this result is incorrect. import os class ReadFiles: def __init__(self): self.current_f...
[ "Consider this organization. Each function has one task, to evaluate and return its result. It's up to the caller to decide what to do with the result. Also note that I'm using counters instead of lists, since you don't really care what the lists contain. Also note the use of defaultdict, to avoid having to do ...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074436892_python_python_3.x.txt
Q: starting container process caused: exec: "uvicorn": executable file not found in $PATH: unknown I'm trying to Dockerize my FastApi app, but it crashes with this error right after I run the command: docker-compose -f local.yml up -d Can anyone help me, please? Dockerfile: FROM python:3.6.11-alpine3.11 ARG MYSQL_SE...
starting container process caused: exec: "uvicorn": executable file not found in $PATH: unknown
I'm trying to Dockerize my FastApi app, but it crashes with this error right after I run the command: docker-compose -f local.yml up -d Can anyone help me, please? Dockerfile: FROM python:3.6.11-alpine3.11 ARG MYSQL_SERVER ARG POSTGRES_SERVER ENV ENVTYPE=local ENV PYTHONUNBUFFERED 1 ENV APP_HOME=/home/app/web RUN mkdi...
[ "Add to Dockerfile,\nENV PATH /home/${USERNAME}/.local/bin:${PATH}, \nbefore\nRUN pip install -r /home/app/web/$ENVTYPE.txt; mkdir /log;, \nby replacing ${USERNAME} with the container user.\nIf you don't know the current user, add RUN echo $(python3 -m site --user-base) somewhere in the Dockerfile. Then copy the ou...
[ 1, 0 ]
[]
[]
[ "docker", "docker_compose", "fastapi", "python", "uvicorn" ]
stackoverflow_0072235848_docker_docker_compose_fastapi_python_uvicorn.txt
Q: Python inner functions/decorators: When should I use parentheses when returning an inner function? I am learning about Python decorators and inner functions and have some questions about the lesson I'm learning via a YouTube video from codeacademy.com https://youtu.be/WOHsHaaJ8VQ. When using inner functions someti...
Python inner functions/decorators: When should I use parentheses when returning an inner function?
I am learning about Python decorators and inner functions and have some questions about the lesson I'm learning via a YouTube video from codeacademy.com https://youtu.be/WOHsHaaJ8VQ. When using inner functions sometimes I have to return the function with parenthesis, and sometimes without. If I call an inner function w...
[ "Let's break this down into two parts.\n1) Let's ignore decorators for now.\nYou should use parentheses when you want to call some function.\nWithout parentheses, a function is just its name.\nFor example:\nHere is a function, where we give it a number, and we get back that number plus 5.\ndef add_five(x):\n ret...
[ 3, 0 ]
[]
[]
[ "python", "python_decorators" ]
stackoverflow_0056450798_python_python_decorators.txt
Q: Getting Log file does not exist: when trying to run a dag on airflow locally I am running airflow locally on my ubuntu machine, my airflow.cfg file is in the directory: /home/airflow/airflow so I created a subdirectory for my dags i.e /home/airflow/airflow/dags/ and created a dag there. The dag I created to check ...
Getting Log file does not exist: when trying to run a dag on airflow locally
I am running airflow locally on my ubuntu machine, my airflow.cfg file is in the directory: /home/airflow/airflow so I created a subdirectory for my dags i.e /home/airflow/airflow/dags/ and created a dag there. The dag I created to check sample output is: from datetime import datetime, timedelta from airflow import DA...
[ "I changed the executor in airflow.cfg from CeleryExecutor to SequentialExecutor, and it worked for me. I'm not sure why celery executor isn't working, it is not ideal by any means but atleast the dags are now running.\n" ]
[ 0 ]
[]
[]
[ "airflow", "directed_acyclic_graphs", "python", "ubuntu" ]
stackoverflow_0074417923_airflow_directed_acyclic_graphs_python_ubuntu.txt
Q: How to Insert multiple rows into SQLServer2017 with Python Getting this in Python3.7 trying to insert a dictionary to SQL Server Out of ideas, does this thing actually work with SQL Server/ Is there another method to insert multiple lines using python The second parameter to executemany must be a sequence, iterato...
How to Insert multiple rows into SQLServer2017 with Python
Getting this in Python3.7 trying to insert a dictionary to SQL Server Out of ideas, does this thing actually work with SQL Server/ Is there another method to insert multiple lines using python The second parameter to executemany must be a sequence, iterator, or generator. Attempted to change 2nd parameter of excecutema...
[ "You can try doing this:\nsql = (\"INSERT INTO dbo.Tablename[remotecontrol_id], [device_id], [alias],[groupid], [online_state])) \n VALUES(%('remotecontrol_id')s, %('device_id')s, %('alias')s, %('groupid')s, %('online_state')s\")\n\n", "I have tested many methods but this is the fastest way to insert bulk ...
[ 0, 0 ]
[]
[]
[ "python", "sql_server" ]
stackoverflow_0055433941_python_sql_server.txt
Q: Discord 'Embed' object has no attribute '_files' Tryna send an embed message on the new discord.py 2.0 and isn't working for me. @Bot.command() async def agent(ctx): list = ["Neon", "Reyna"] await ctx.message.delete() emb = discord.Embed(title=f"Agent Picker") emb.set_footer(text=f"Used by: {ctx.au...
Discord 'Embed' object has no attribute '_files'
Tryna send an embed message on the new discord.py 2.0 and isn't working for me. @Bot.command() async def agent(ctx): list = ["Neon", "Reyna"] await ctx.message.delete() emb = discord.Embed(title=f"Agent Picker") emb.set_footer(text=f"Used by: {ctx.author.name}") emb.add_field(name=f"Agent:", value=f...
[ "\non the new discord.py 2.0\n\nThe error message suggests you're using disnake, not discord.py 2.0.\nFile \"/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/abc.py\", line 1564, \n# ^^^^^^^\n\nYou're mixing different versions/forks of the library...
[ 0 ]
[]
[]
[ "discord.py", "embed", "python" ]
stackoverflow_0074437041_discord.py_embed_python.txt
Q: MemoryError: Unable to allocate 32.2 GiB for an array with shape (28709, 224, 224, 3) and data type float64 I was trying to normalize FER dataset but it gives me memory error. How can I solve this? A: Since you probably don't want your original data either way you can just normalize in place x = preprocessing.no...
MemoryError: Unable to allocate 32.2 GiB for an array with shape (28709, 224, 224, 3) and data type float64
I was trying to normalize FER dataset but it gives me memory error. How can I solve this?
[ "Since you probably don't want your original data either way you can just normalize in place\nx = preprocessing.normalize(x, copy=False)\n\nwhich will avoid copying data.\nIf it is not enough you just need to think about your memory allocation, as you are clearly operating at the edge of wha tyour hardware can supp...
[ 0 ]
[]
[]
[ "machine_learning", "normalizing", "python" ]
stackoverflow_0074436086_machine_learning_normalizing_python.txt
Q: I can't run geckodriver, python selenium ; [WinError 216] I've got the win32 drivers from https://github.com/mozilla/geckodriver/release and placed the exe under the python38 folder I'm running windows 11 OSError: [WinError 216] This version of %1 is not compatible with the version of Windows you're running. Check...
I can't run geckodriver, python selenium ; [WinError 216]
I've got the win32 drivers from https://github.com/mozilla/geckodriver/release and placed the exe under the python38 folder I'm running windows 11 OSError: [WinError 216] This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the softwa...
[ "You can use webdriver_manager to get rid of driver problems. You can use webdriver_manager for firefox as you can see in the link as follows\nfor selenium 3\nfrom selenium import webdriver\nfrom webdriver_manager.firefox import GeckoDriverManager\n\ndriver = webdriver.Firefox(executable_path=GeckoDriverManager().i...
[ 0 ]
[]
[]
[ "geckodriver", "python", "selenium", "windows" ]
stackoverflow_0074435728_geckodriver_python_selenium_windows.txt
Q: How to load large json(multiple object) into pandas dataframes in chuncks to avoid high memory usage? I have a very large json file that is in the form of multiple objects, for small dataset, this works data=pd.read_json(file,lines=True) but on the same but larger dataset it would crash on 8gb ram computer, so i ...
How to load large json(multiple object) into pandas dataframes in chuncks to avoid high memory usage?
I have a very large json file that is in the form of multiple objects, for small dataset, this works data=pd.read_json(file,lines=True) but on the same but larger dataset it would crash on 8gb ram computer, so i tried to convert it to list first with below code data[] with open(file) as file: for i in file: ...
[ "There are several possible solution, depending on your specific case. Given we don't have a data example or information on the data structure, I could offer the following:\n\nIf the data in the json file is numeric, consider breaking it into chunks, reading each one and converting to the smallest type (float32/int...
[ 0, 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074431630_json_pandas_python.txt
Q: How to display a variable with tkinter I wanted if I can do like a create_variable to display a variable with Tkinter. player_score = 0 score = Canvas(window_game, width=300, height=40, bg="black") score.create_text(50, 20, text="SCORE :", fill="white", font=('Courrier')) score.grid(row=0,column=0) #x #y lives ...
How to display a variable with tkinter
I wanted if I can do like a create_variable to display a variable with Tkinter. player_score = 0 score = Canvas(window_game, width=300, height=40, bg="black") score.create_text(50, 20, text="SCORE :", fill="white", font=('Courrier')) score.grid(row=0,column=0) #x #y lives = Canvas(window_game, width=300, height=40, ...
[ "You can do this with the canvas itemconfig method. First you need make a reference to the canvas item. This is the return value of create_text and I've assigned it to score_text.\nscore_text = score.create_text(50, 20, text=\"SCORE :\", fill=\"white\", font=('Courrier'))\n\nThis can then be used to update the text...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074436931_python_tkinter.txt
Q: How to fix Artifacts not showing in MLflow UI I'd used MLflow and logged parameters using the function below (from pydataberlin). def train(alpha=0.5, l1_ratio=0.5): # train a model with given parameters warnings.filterwarnings("ignore") np.random.seed(40) # Read the wine-quality csv file (make su...
How to fix Artifacts not showing in MLflow UI
I'd used MLflow and logged parameters using the function below (from pydataberlin). def train(alpha=0.5, l1_ratio=0.5): # train a model with given parameters warnings.filterwarnings("ignore") np.random.seed(40) # Read the wine-quality csv file (make sure you're running this from the root of MLflow!) ...
[ "Is this code not being run locally? Are you moving the mlruns folder perhaps? I'd suggest checking the artifact URI present in the meta.yaml files. If the path there is incorrect, such issues might come up.\n", "Had a similar issue. In my case, I solved it by running mlflow ui inside the mlruns directory of your...
[ 5, 4, 1, 1, 0 ]
[]
[]
[ "artifacts", "mlflow", "python" ]
stackoverflow_0061980244_artifacts_mlflow_python.txt
Q: How two join multiple tables with multiple conditions in sqlalchemy select d.field_value as name,a.mobile,c.balance,a.created_at from users as a inner join user_profiles as b on a.id = b.user_id inner join wallets as c on c.user_profile_id = b.id left join profile_details as d on d.user_id = a.id where d.field_nam...
How two join multiple tables with multiple conditions in sqlalchemy
select d.field_value as name,a.mobile,c.balance,a.created_at from users as a inner join user_profiles as b on a.id = b.user_id inner join wallets as c on c.user_profile_id = b.id left join profile_details as d on d.user_id = a.id where d.field_name = "name" and c.balance > 0 order by a.id desc; This is my query and i ...
[ "It's pretty easy. I've some links to be referred.\nYou can refer to the documentation here.\nHow to join multiple tables here.\nHow to select only few columns from the query here.\nLeft and/or right outer join using sqlalchemy here\nI think now you may be able to solve your problem. Hope this helps.\n" ]
[ 0 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0074428458_orm_python_sqlalchemy.txt
Q: conda install UnicodeDecodeError When I run the command conda install -c conda-forge tensorflow, I encounter this error. matin:(all-in-one)~/ conda install -c conda-forge tensorflow # >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<< Traceback (most recent call last): File "/home/matin/Program...
conda install UnicodeDecodeError
When I run the command conda install -c conda-forge tensorflow, I encounter this error. matin:(all-in-one)~/ conda install -c conda-forge tensorflow # >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<< Traceback (most recent call last): File "/home/matin/Programs/miniconda3/lib/python3.9/site-packag...
[ "Problem\nIt was caused because my laptop's HDD got some issues (4 months ago, the live ubuntu USB that I was installing from it, was pulled out during moving partitions). So some of my anaconda files have been broken.\nfor example my .../miniconda3/pkgs/requests-oauthlib-1.3.1-pyhd8ed1ab_0/info/link.json file was ...
[ 0 ]
[]
[]
[ "conda", "python" ]
stackoverflow_0074437176_conda_python.txt
Q: Infinite recursion error in custom class that combines dict, defaultdict, and SimpleNamespace functionality I am writing a class in python that combines the functionality of dict, defaultdict, and SimpleNamespace So far I have the following code: import warnings class fluiddict: """! A class that emulates ...
Infinite recursion error in custom class that combines dict, defaultdict, and SimpleNamespace functionality
I am writing a class in python that combines the functionality of dict, defaultdict, and SimpleNamespace So far I have the following code: import warnings class fluiddict: """! A class that emulates a dictionary, while also being able to support attribute assignment and default values. The default v...
[ "I think this implements what you want. You can call the base class __setattr__ to allow the write.\nclass xdict:\n def __init__(self):\n self.datastore = {}\n def __getitem__(self,key):\n if key not in self.datastore:\n raise KeyError(f'{key} not found')\n if key not in self....
[ 2, 0 ]
[]
[]
[ "defaultdict", "dictionary", "python", "python_3.x", "python_simplenamespace" ]
stackoverflow_0074436601_defaultdict_dictionary_python_python_3.x_python_simplenamespace.txt
Q: Multiple transformations/actions and lazy evaluation in pyspark I am working on a project on PySpark that requires processing large datasets (multiple .csv files of size around 2GB). Let's say I have two dataframes A and B, and that I perform some transformations on A and B separately. Now let C be some dataframe ...
Multiple transformations/actions and lazy evaluation in pyspark
I am working on a project on PySpark that requires processing large datasets (multiple .csv files of size around 2GB). Let's say I have two dataframes A and B, and that I perform some transformations on A and B separately. Now let C be some dataframe such that: C = A.join(B, A.key_1 == B.key_2, "full") And then execute...
[ "\nDoes PySpark redo all the transformations that I performed on A and B *plus * the full join operation of A+B each time I invoke C.count() ? Or does it memorize them somewhere to speed up the action ?\n\nAssuming that all your operations on all DataFrames are part of the same, single job, then Spark is able to op...
[ 0 ]
[]
[]
[ "apache_spark", "pyspark", "python" ]
stackoverflow_0074436874_apache_spark_pyspark_python.txt
Q: Create a new data frame of counts from a list corresponding to column index values from a different data frame I have two unique lists like: a = [12, 12, 12, 3, 4, 5] b = [1, 2, 4, 5, 6, 12, 4, 7, 9, 2, 3, 5, 6] df.columns Index(['lep', 'eta', 'phi', 'missing energy magn', 'missing energy phi', 'jet]) etc (colum...
Create a new data frame of counts from a list corresponding to column index values from a different data frame
I have two unique lists like: a = [12, 12, 12, 3, 4, 5] b = [1, 2, 4, 5, 6, 12, 4, 7, 9, 2, 3, 5, 6] df.columns Index(['lep', 'eta', 'phi', 'missing energy magn', 'missing energy phi', 'jet]) etc (columns is longer than I wrote here, obviously). Lists a and b correspond to column index values. I want to create a new ...
[ "You can use count() to count number of occurences of element in list and enumerate() to iterate over list and keep a count of iterations.\nSo your code becomes:\nimport pandas as pd\n\na = [12, 12, 12, 3, 4, 5]\nb = [1, 2, 4, 5, 6, 12, 4, 7, 9, 2, 3, 5, 6]\n\n\nelements = ['lep', 'eta', 'phi', 'missing energy magn...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074436265_dataframe_pandas_python.txt
Q: Get python function source excluding the docstring? You might want to have the docstring not affect the hash for example like in joblib memory. Is there a good way of stripping the docstring? inspect.getsource and inspect.getdoc kind of fight each other: the docstring is "cleaned" in one. A: If you just want to...
Get python function source excluding the docstring?
You might want to have the docstring not affect the hash for example like in joblib memory. Is there a good way of stripping the docstring? inspect.getsource and inspect.getdoc kind of fight each other: the docstring is "cleaned" in one.
[ "If you just want to hash the body of a function, regardless of the docstring, you can use the function.__code__ attribute.\nIt gives access to a code object which is not affected by the docstring.\nunfortunately, using this, you will not be able to get a readable version of the source\ndef foo():\n \"\"\"Prints...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0060603113_python.txt
Q: how to query the user customer in user model to do a query and add record in django I have a custom user model with a field 'customer'. Each user has a customer. I am trying to get the logged in users customer so that when I add infringer, the correct customer is added for the record. I think below is wrong in vi...
how to query the user customer in user model to do a query and add record in django
I have a custom user model with a field 'customer'. Each user has a customer. I am trying to get the logged in users customer so that when I add infringer, the correct customer is added for the record. I think below is wrong in views. customer=request.user.customer think below is wrong in forms. customer__user=self.cu...
[ "If I understand correctly, you identified the problems correctly.\nSo I think you need to:\n\nChange line 5 in views.py: form = InfringerForm(customer=customer)\nChange line 5 in form.py\" self.fields['customer'].queryset = Customer.objects.filter(customer=customer)\n\n", "\nviews.py\ncustomer=request.user.custo...
[ 2, 1 ]
[]
[]
[ "django", "django_forms", "django_queryset", "python" ]
stackoverflow_0074436238_django_django_forms_django_queryset_python.txt
Q: NotImplementedError: this is an abstract class in speech recognition I got some code from google for speech recognition when i try to run that code i'm getting "NotImplementedError" please see the below code and help me.I'm using Mac. import speech_recognition as sr r = sr.Recognizer() with sr.Recognizer() as sou...
NotImplementedError: this is an abstract class in speech recognition
I got some code from google for speech recognition when i try to run that code i'm getting "NotImplementedError" please see the below code and help me.I'm using Mac. import speech_recognition as sr r = sr.Recognizer() with sr.Recognizer() as source: print("Speak Anything") audio = r.listen(source) try: text =...
[ "In the line above, you instantiate a Recognizer object, then you try to use the uninstatiated class in the problem line. Should that be \nwith r as source:\n ...\n\n", "I have the below code and it gives me same error i.e\nTraceback (most recent call last):\nFile \"/Users/../Listen.py\", line 25, in \nprint(L...
[ 1, 0 ]
[]
[]
[ "python", "speech_recognition" ]
stackoverflow_0056758116_python_speech_recognition.txt
Q: Python -m http.server 443 -- with SSL? Is it possible to create a temporary Python3 HTTP server with an SSL certificate? For example: $ python3 -m http.server 443 --certificate /path/to/cert A: Not from the command line, but it's pretty straightforward to write a simple script to do so. from http.server import H...
Python -m http.server 443 -- with SSL?
Is it possible to create a temporary Python3 HTTP server with an SSL certificate? For example: $ python3 -m http.server 443 --certificate /path/to/cert
[ "Not from the command line, but it's pretty straightforward to write a simple script to do so.\nfrom http.server import HTTPServer, BaseHTTPRequestHandler \nimport ssl\nhttpd = HTTPServer(('localhost', 4443), BaseHTTPRequestHandler)\nhttpd.socket = ssl.wrap_socket(\n httpd.socket,\n keyfile=\"path/to/key.pem\...
[ 7, 1, 0 ]
[]
[]
[ "http", "python", "python_3.x", "server", "ssl" ]
stackoverflow_0056503241_http_python_python_3.x_server_ssl.txt
Q: how to create a dataset for multi-output regression with sliding window approach I want to build normal DNN model, I have huge data with X_train= 8000000x7 and y_train=8000000x2. How to create a dataset with sliding window of 100 data points to feed the neural network. If I use a customized dataset using following...
how to create a dataset for multi-output regression with sliding window approach
I want to build normal DNN model, I have huge data with X_train= 8000000x7 and y_train=8000000x2. How to create a dataset with sliding window of 100 data points to feed the neural network. If I use a customized dataset using following code, I have a problem of allocation due to large dataset. def data_set(x_data, y_dat...
[ "You can use dataset.window method to achieve that.\ndataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))\nstride = 1\ndataset = dataset.window(batch_size, shift=batch_size-stride, drop_remainder=True)\n\n" ]
[ 1 ]
[]
[]
[ "data_generation", "python", "regression", "tensorflow" ]
stackoverflow_0074431297_data_generation_python_regression_tensorflow.txt
Q: ValueError: Error when checking input: expected flatten_input to have shape (1, 4) but got array with shape (1, 2) I'm fairly new to RL and i can't really understand why I'm getting this error. import random import numpy as np import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras....
ValueError: Error when checking input: expected flatten_input to have shape (1, 4) but got array with shape (1, 2)
I'm fairly new to RL and i can't really understand why I'm getting this error. import random import numpy as np import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras.optimizers import Adam from rl.agents import DQNAgent from rl.policy ...
[ "The keras-rl2 library has been discontinued since 2021. See their github repo here: https://github.com/taylormcnally/keras-rl2 You can see it has been archived and no longer being updated.\nThey have also deleted their online documentation.\nGym recommends that you do not use keras-rl2, rather use other libraries ...
[ 0, 0 ]
[]
[]
[ "keras", "openai_gym", "python", "reinforcement_learning", "tensorflow" ]
stackoverflow_0073978651_keras_openai_gym_python_reinforcement_learning_tensorflow.txt
Q: Is it possible to change the sent file in discord python? I need to change embed with local file (photo) from my machine. To send embed, you need to send the file along with it, but it cannot be changed. When i try to do this: My Code: embed = discord.Embed(title = "Title here", description = "", ...
Is it possible to change the sent file in discord python?
I need to change embed with local file (photo) from my machine. To send embed, you need to send the file along with it, but it cannot be changed. When i try to do this: My Code: embed = discord.Embed(title = "Title here", description = "", timestamp = datetime.utcnow(), ...
[ "You cannot change the attachments to a message after it has been sent. Discord simply doesn't allow it. If you check the discord.py documentation for discord.Message.edit, you'll see that the file parameter is not accepted. Your error is caused by discord.py trying to convert the file to a JSON to be sent with the...
[ 1, 0, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0070383667_discord.py_python.txt
Q: Dataframe date conversion of different types I am importing into a df from Excel, and the result of the date column resembles something like this dummy df, where some dates are yyyy-mm-dd-like, and others are codes. data = ['2020-01-20 00:00:00', '2020-04-27 00:00:00', '43836'] df = pd.DataFrame(data, columns=['en...
Dataframe date conversion of different types
I am importing into a df from Excel, and the result of the date column resembles something like this dummy df, where some dates are yyyy-mm-dd-like, and others are codes. data = ['2020-01-20 00:00:00', '2020-04-27 00:00:00', '43836'] df = pd.DataFrame(data, columns=['entry_date']) entry_date 0 2020-01-20 ...
[ "Here is one way to do it:\ndf = df.apply(\n lambda x: pd.to_datetime(x[\"entry_date\"], errors=\"coerce\")\n if pd.to_datetime(x[\"entry_date\"], errors=\"coerce\") is not pd.NaT\n else pd.to_datetime(\n pd.to_numeric(x[\"entry_date\"], errors=\"coerce\"),\n unit=\"D\",\n origin=\"189...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074395495_pandas_python.txt
Q: Simple Pandas Groupby/Pivot? I have the following DataFrame Value Date 0 1 2022-01-01 1 2 2022-01-01 2 3 2022-01-01 3 4 2022-01-02 4 5 2022-01-02 5 6 2022-01-02 6 7 2022-01-03 7 8 2022-01-03 8 9 2022-01-03 I would like to obtain the following ...
Simple Pandas Groupby/Pivot?
I have the following DataFrame Value Date 0 1 2022-01-01 1 2 2022-01-01 2 3 2022-01-01 3 4 2022-01-02 4 5 2022-01-02 5 6 2022-01-02 6 7 2022-01-03 7 8 2022-01-03 8 9 2022-01-03 I would like to obtain the following DataFrame, by grouping all the val...
[ "One option can be to use pandas.DataFrame.pivot and then drop nan values.\ndf_new = df.pivot(columns='Date', values='Value').apply(\n lambda x: pd.Series(x.dropna().values)).astype('int')\n\nprint(df_new)\n\nOutput:\nDate 2022-01-01 2022-01-02 2022-01-03\n0 1 4 7\n1 ...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074436805_dataframe_pandas_python.txt
Q: Want to reverse a range but I get back I'm coding a connect "M" and I want to enumerate the rows starting with the biggest number (the last one). So I tried using reverse in my function but it print this <range_iterator object at 0x0000017B4A49D7F0>. Could anyone help me out? Here's my code: def print_board(self)...
Want to reverse a range but I get back
I'm coding a connect "M" and I want to enumerate the rows starting with the biggest number (the last one). So I tried using reverse in my function but it print this <range_iterator object at 0x0000017B4A49D7F0>. Could anyone help me out? Here's my code: def print_board(self): # Number the columns separately to keep...
[ "reversed() returns a range object.\nLooking at your requirement, you want to print reverse numbers so you simply need to reverse the range(BOARD_ROWS).\nHere's how the code will look (for the range part):\nfor r in reversed(range(BOARD_ROWS)): # iterates 6 to 0\n print(r) # 6, 5, 4, 3, 2, 1, 0 - this is index\n...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074437388_python.txt
Q: Python Binary Search Tree: Search function error class Node: def __init__(self, key, parent = None): self.key = key self.parent = parent self.left = None self.right = None if parent != None: if key < parent.key: parent.left = self ...
Python Binary Search Tree: Search function error
class Node: def __init__(self, key, parent = None): self.key = key self.parent = parent self.left = None self.right = None if parent != None: if key < parent.key: parent.left = self else: parent.right = self def...
[ "I really had a brain fart with this question.... Thank you to those commenting reminding me the function is being called with the self instance being passed implicitly, I forgot basics of objects i guess lol. This implementation passes the test cases. If there is a better way of implementing this, feel free to pos...
[ 1 ]
[]
[]
[ "binary_search_tree", "python" ]
stackoverflow_0074436406_binary_search_tree_python.txt
Q: How to check if I have two values in an set of values of an table in Databricks Pyspark Is there any way to change a column based on the presence of two values in a set of values from a databricks pyspark dataframe? Example: df = ( [ ('E1', 'A1',''), ('E2', 'A2',''), ('F1', 'A3',''), ...
How to check if I have two values in an set of values of an table in Databricks Pyspark
Is there any way to change a column based on the presence of two values in a set of values from a databricks pyspark dataframe? Example: df = ( [ ('E1', 'A1',''), ('E2', 'A2',''), ('F1', 'A3',''), ('F2', 'B1',''), ('F3', 'B2',''), ('G1', 'B3',''), ('G2', 'C1'...
[ "I think you will have to do this in two steps. First, check if values C1 and E1 occur at least once in both columns and if so, then apply the operations, similar to what @Steven suggested:\nfrom pyspark.sql.functions import col, when\n\ndf = spark.createDataFrame([\n ('E1', 'A1',''), \n ('E2', 'A2','...
[ 1 ]
[]
[]
[ "azure_databricks", "performance", "pyspark", "python" ]
stackoverflow_0074432829_azure_databricks_performance_pyspark_python.txt
Q: Why is clustermap producing the same dendrogram when the values change? I want to cluster the similarities of the elements of a matrix but my code produces the same dendrogram even if I change the values of the elements of matrix (in this case, the position of matrix elements changes but dendrogram doesn't change ...
Why is clustermap producing the same dendrogram when the values change?
I want to cluster the similarities of the elements of a matrix but my code produces the same dendrogram even if I change the values of the elements of matrix (in this case, the position of matrix elements changes but dendrogram doesn't change ). Do you know how I can fix the code? Please run the code as it is. Then cha...
[ "\nseaborn.clustermap adjusts the locations of the columns and the index on the plot axes to create the dendrogram.\ng.ax_heatmap.set_xticklabels(methods) and g.ax_heatmap.set_yticklabels(methods) are incorrectly overwriting the x and y ticklabels. The new labels are not being mapped to the correct labels on the ax...
[ 1 ]
[]
[]
[ "clustermap", "dendrogram", "matplotlib", "python", "seaborn" ]
stackoverflow_0074437077_clustermap_dendrogram_matplotlib_python_seaborn.txt
Q: UnicodeDecodeError in pymssql library of Python I'm using pymssql to get some data from the SQL server and store the results in a pandas dataframe. When I try to select a column that contains utf-8 (Farsi) characters, I get this error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invali...
UnicodeDecodeError in pymssql library of Python
I'm using pymssql to get some data from the SQL server and store the results in a pandas dataframe. When I try to select a column that contains utf-8 (Farsi) characters, I get this error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte But everything is fine with othe...
[ "Are you 100% certain the data is stored in UTF-8? Running the command SELECT SERVERPROPERTY('Collation'); should help you determine how data is encoded in the database.\nI think the default encoding is Latin-1 and that would mean 0xCA is \"capital E circumflex (Ê)\".\nYou can configure pymssql to access the databa...
[ 2, 2, 0 ]
[]
[]
[ "pymssql", "python" ]
stackoverflow_0051036394_pymssql_python.txt
Q: How to apply a function to multiple dataframe columns and create a corresponding number of columns programatically? I want to create a function that takes in a dataframe and a list, and then creates n new columns (with different, programatically-generated names), and returns the expanded dataframe. Say for instanc...
How to apply a function to multiple dataframe columns and create a corresponding number of columns programatically?
I want to create a function that takes in a dataframe and a list, and then creates n new columns (with different, programatically-generated names), and returns the expanded dataframe. Say for instance that you have a dataframe consisting of three columns: Dogs Cats Horses "Bobby" "Memphis" "Incitatus" "Rudolp...
[ "Here is one way to do it by using the dataframe columns attribute and indexing operators []:\nfor col in df.columns:\n df[f\"{col}_new\"] = df.apply(lambda x: my_function(x[col], list_of_names), axis=1)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074363834_dataframe_pandas_python.txt
Q: Creating QR code containing both text and photo It is possible to create a QR code which contains both some text and photo (which is small logo) in python? I mean text, which is not part of the photo. But I will have separately text (string variable) and photo (e.g. *.png). So far I saw only the examples where it ...
Creating QR code containing both text and photo
It is possible to create a QR code which contains both some text and photo (which is small logo) in python? I mean text, which is not part of the photo. But I will have separately text (string variable) and photo (e.g. *.png). So far I saw only the examples where it was possible to create a QR code from text or photo. ...
[ "Expanding on my comment. QR Codes are used to encode text. So you have to read in your image, convert to base64, append your string with some delimiter and then write out your QR code.\nBecause we took special steps to encode the data (the image and the string) before storing in a QR code, we must also have a spec...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x", "python_imaging_library", "qr_code" ]
stackoverflow_0074434255_python_python_3.x_python_imaging_library_qr_code.txt
Q: How to corectly query for type "dict"? For my quiz application I have a module which asks questions, shows the 4 possible answers in a listbox, then you click a button to fetch result and check if true. Data type is interpreted incorrectly as a list, I convert to type:dict but then the code does not interpret it t...
How to corectly query for type "dict"?
For my quiz application I have a module which asks questions, shows the 4 possible answers in a listbox, then you click a button to fetch result and check if true. Data type is interpreted incorrectly as a list, I convert to type:dict but then the code does not interpret it the same as if manually defined. How can I re...
[ "I don't quite follow what you're doing at the moment. I propose something like this:\nquestions = []\nfor r in records:\n questions.append({\n \"question\": r[0],\n \"answer\": r[1],\n \"options\": list(r[1:])\n })\n\nfor question in questions:\n correct_answer = question[\"answer\"]\...
[ 1 ]
[]
[]
[ "list", "python", "sqlite", "type_conversion" ]
stackoverflow_0074437162_list_python_sqlite_type_conversion.txt
Q: Airflow taskgroup has status failed while all tasks in group have status success I have question regarding taskgroups in Airflow. My DAG contains two taskgroups that each contain a number of python operators. When I run my DAG all python operators are executed successfully and the DAG gets marked as success as wel...
Airflow taskgroup has status failed while all tasks in group have status success
I have question regarding taskgroups in Airflow. My DAG contains two taskgroups that each contain a number of python operators. When I run my DAG all python operators are executed successfully and the DAG gets marked as success as well. However, when I look at the grid view in the UI it seems that my two taskgroups hav...
[ "Grid view was introduced in Airflow 2.3 and it has some UI issues in consecutive releases.\nI recommend you upgrade first to the latest version of Airflow (2.4.3) and if the issue persists, please provide more context to reproduce it.\n" ]
[ 0 ]
[]
[]
[ "airflow", "python" ]
stackoverflow_0074181728_airflow_python.txt
Q: How to get a numeric value from Pandas DataFrame? I have a Pandas data frame, attack_probability_df: city date attack probability 0 Rome 1996-02-23 0.163317 1 Rome 1996-02-24 0.219221 2 Rome 1996-02-25 0.180625 3 Rome 1996-02-26 0.149749 4 Rome 1996-...
How to get a numeric value from Pandas DataFrame?
I have a Pandas data frame, attack_probability_df: city date attack probability 0 Rome 1996-02-23 0.163317 1 Rome 1996-02-24 0.219221 2 Rome 1996-02-25 0.180625 3 Rome 1996-02-26 0.149749 4 Rome 1996-02-27 0.121288 I use attack_probability_df.loc[atta...
[ "Just add .values[0] on the end to get the attack_probability.\n", "The answer by cmauck10 answers the question keeping the syntax suggested in the question.\nHere is an another way (known as boolean indexing) to get attack_probability without using .loc:\ndf:\n city date attack probability\n0 Rome 19...
[ 3, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074437284_dataframe_pandas_python.txt
Q: Django model filter with "exact" IN operator I want to find all users who have exactly same tags like a particular category (exactly same tags and also same amount of tags assigned) Something like... category = Category.objects.first() User.objects.filter(tags__in=category.tags.filter()) But this returns also use...
Django model filter with "exact" IN operator
I want to find all users who have exactly same tags like a particular category (exactly same tags and also same amount of tags assigned) Something like... category = Category.objects.first() User.objects.filter(tags__in=category.tags.filter()) But this returns also users who share even only one tag with the category. ...
[ "Not the best solution, but will work probably.\nIterate over User queryset and filter them one by one. example:\ncategory = Category.objects.first()\nfor tag in category.tags.all():\n qs = User.objects.filter(tags__id=tag.id)\n\nOther one:\ncategory = Category.objects.first()\ntag_ids = category.tags.values_lis...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074437213_django_django_models_python.txt
Q: Append column from one dataframe to another for rows that match in both dataframes I have two dataframes A and B that contain different sets of patient data, and need to append certain columns from B to A - however only for those rows that contain information from the same patient and visit, i.e. where A and B hav...
Append column from one dataframe to another for rows that match in both dataframes
I have two dataframes A and B that contain different sets of patient data, and need to append certain columns from B to A - however only for those rows that contain information from the same patient and visit, i.e. where A and B have a matching value in two particular columns. B is longer than A, not all rows in A are ...
[ "i think you can use merge:\nA['Visit_Date']=pd.to_datetime(A['Visit_Date'])\nB['Visit_Date']=pd.to_datetime(B['Visit_Date'])\nfinal=A.merge(B,on=['Visit_Date','ID'],how='outer')\nprint(final)\n'''\n\n ID Visit_Date Score Diagnosis\n0 A_190792 2010-10-31 30.0 G42\n1 X_210392 2011-09-24 23.0 ...
[ 0 ]
[]
[]
[ "append", "join", "merge", "pandas", "python" ]
stackoverflow_0074437566_append_join_merge_pandas_python.txt
Q: Python Django email login/authenticate 'user is None' with ModelBackend, CustomUserModel I tried to make a email login/authenticate in views.py, but it returns 'user is None'. I tried to use just email for login not username. If I tried to login with email, it seems to take 'user is None' with custom error message...
Python Django email login/authenticate 'user is None' with ModelBackend, CustomUserModel
I tried to make a email login/authenticate in views.py, but it returns 'user is None'. I tried to use just email for login not username. If I tried to login with email, it seems to take 'user is None' with custom error messages 'invalid credentials' in views.py. Django version: 3.0.4 // Model: Custom User Model (Abstra...
[ "try this\nuser = authenticate(email=email, password=password)\n\nor use check_password\nfrom django.contrib.auth.hashers import check_password\n\n\n# inside view function\n# ...\nuser = User.objects.get(email=email)\nif check_password(password, user.password):\n if user.is_active:\n login(request, user)\...
[ 0, 0 ]
[]
[]
[ "authentication", "django", "django_models", "email", "python" ]
stackoverflow_0061006311_authentication_django_django_models_email_python.txt
Q: modify pandas boxplot output I made this plot in pandas, according to the documentation: import pandas as pd import numpy as np import pyplot as plt df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D']) df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6'...
modify pandas boxplot output
I made this plot in pandas, according to the documentation: import pandas as pd import numpy as np import pyplot as plt df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D']) df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6', 'model7'], 20)) plt.figure() bp ...
[ "\nFor the arrangement use layout\nFor setting x label use set_xlabel('')\nFor figure title use figure.subtitle()\nFor changing the figure size use figsize=(w,h) (inches)\n\nnote: the line np.asarray(bp).reshape(-1) is converting the layout of the subplots (2x2 for instance) to an array. \ncode : \nimport pandas as...
[ 7, 2, 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0040125528_matplotlib_pandas_python.txt
Q: how to refresh the canvas to display a grid of a changing matrix I'm trying to implement Conway's Game of Life on python 3.10. I want to insert a shape in my grid and see how it evolves. the nextgen function evolves the matrix correctly however I couldn't fine a working way to update the canvas and display my new ...
how to refresh the canvas to display a grid of a changing matrix
I'm trying to implement Conway's Game of Life on python 3.10. I want to insert a shape in my grid and see how it evolves. the nextgen function evolves the matrix correctly however I couldn't fine a working way to update the canvas and display my new grid with each generation Any help is greatly appreciated! my code: im...
[ "It's not a good idea to create a new Canvas for every iteration. Instead, make one canvas and clear it when you want to draw the grid again.\ndef drawgrid(display, grid, cell_size):\n display.delete(\"all\") # Delete current grid\n for i in range(grid.shape[0]):\n ... # The rest of this is the same as...
[ 3 ]
[]
[]
[ "python", "python_3.x", "tkinter", "tkinter_canvas" ]
stackoverflow_0074437371_python_python_3.x_tkinter_tkinter_canvas.txt
Q: How to Create Piecewise Function in SymPy with Intervals i need to create a piece-wise function inside an interval but sympy piecewise can't use and (&). I read that the function can't recieve Boolean values so I tried to add them together and it doesn't seem to be right. The code is as follows: import numpy as np...
How to Create Piecewise Function in SymPy with Intervals
i need to create a piece-wise function inside an interval but sympy piecewise can't use and (&). I read that the function can't recieve Boolean values so I tried to add them together and it doesn't seem to be right. The code is as follows: import numpy as np import sympy as sp import matplotlib as plt # This is all th...
[ "It would be helpful if you give an example of how Piecewise did not do what you wanted. Piecewise will work with And (and intervals expressed with the same):\n\n" ]
[ 1 ]
[]
[]
[ "boolean_operations", "finite_element_analysis", "piecewise", "python", "sympy" ]
stackoverflow_0074435954_boolean_operations_finite_element_analysis_piecewise_python_sympy.txt
Q: Iterating over date range in python and setting the start and end date I know this question is a repeated one. But what I am trying to do is, I want to iterate through a date range and for each iteration i need to set the fromDate and toDate. for ex: If I give the date range as startDate = '2022-10-31' and endDate...
Iterating over date range in python and setting the start and end date
I know this question is a repeated one. But what I am trying to do is, I want to iterate through a date range and for each iteration i need to set the fromDate and toDate. for ex: If I give the date range as startDate = '2022-10-31' and endDate = '2022-11-04' and for each iteration fromDate = '2022-10-31' and toDate = ...
[ "You can change the code slightly to,\nimport datetime\n\nstart_date = datetime.date(2022, 10, 31)\nend_date = datetime.date(2022, 11, 4)\n\ndates_2011_2013 = [ (start_date + datetime.timedelta(n), start_date + datetime.timedelta(n+1)) for n in range(int ((end_date - start_date).days))]\n\n\n[(datetime.date(2022...
[ 1, 0 ]
[]
[]
[ "date_range", "datetime", "for_loop", "python", "python_3.x" ]
stackoverflow_0074435859_date_range_datetime_for_loop_python_python_3.x.txt
Q: Flexible List Cleaner I have a list: sol = ["U", "U'","U","R","R'", "R", "R", "R", "R","U","U'"] I also created a function to clean this list: def cleanSol(sol): res = '-'.join(sol) moveList = ['U', "U'", 'U2', 'D', "D'", 'D2', 'R', "R'", 'R2', 'L', "L'", 'L2', 'F', "F'", 'F2', 'B', "B'", 'B2', 'Y', "Y'",...
Flexible List Cleaner
I have a list: sol = ["U", "U'","U","R","R'", "R", "R", "R", "R","U","U'"] I also created a function to clean this list: def cleanSol(sol): res = '-'.join(sol) moveList = ['U', "U'", 'U2', 'D', "D'", 'D2', 'R', "R'", 'R2', 'L', "L'", 'L2', 'F', "F'", 'F2', 'B', "B'", 'B2', 'Y', "Y'", 'X', "X'", 'Z', "Z'", 'M',...
[ "Mine is also lengthy but easy to follow, I just wanted to share as a second approach.\nHere I check the list in a while True many times, every time from the beginning. If first items are removable, I remove them and start the loop again, if not I check next few items. I've put comment for each section.\ndef cleanS...
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074437242_list_python.txt
Q: Parsing nested JSON information in Python From the JSON string below I'm trying to pull just all the waiverId's: data = { "version": 4, "id": "(requestId)", "ts": "2022-11-14T20:24:50+00:00", "type": "checkins", "checkins": { "fromDts": "2022-07-01", "toDts": "2022-07-02", "moreCheckins": tr...
Parsing nested JSON information in Python
From the JSON string below I'm trying to pull just all the waiverId's: data = { "version": 4, "id": "(requestId)", "ts": "2022-11-14T20:24:50+00:00", "type": "checkins", "checkins": { "fromDts": "2022-07-01", "toDts": "2022-07-02", "moreCheckins": true, "checkins": [ { "date": "...
[ "You want to pull the list of checkins from 'checkins' as in:\nfor checkins in data['checkins']['checkins']:\n print(checkins)\n\nThe first key checkins returns a dict value containing a key of checkins that contains a list of the data you want in dict format.\n", "Assumptions:\n\nThe dictionary you deal with ...
[ 0, 0 ]
[]
[]
[ "json", "parsing", "python" ]
stackoverflow_0074437641_json_parsing_python.txt
Q: python nested dictionaries from sql queries Hello i am trying to create a dictionary that would like this {104: {'tid': 1234, 'date': '08/26/2022', 'total': '95.96'}, {'tid': 1235, 'date': '09/25/2022', 'total': '95.96'}, {'tid': 1236, 'date': '07/27/2022', 'total': '95.96'}} {105: {'tid': 1237, 'date': '08/26/202...
python nested dictionaries from sql queries
Hello i am trying to create a dictionary that would like this {104: {'tid': 1234, 'date': '08/26/2022', 'total': '95.96'}, {'tid': 1235, 'date': '09/25/2022', 'total': '95.96'}, {'tid': 1236, 'date': '07/27/2022', 'total': '95.96'}} {105: {'tid': 1237, 'date': '08/26/2022', 'total': '85.96'}, {'tid': 1238, 'date': '09/...
[ "I can only imagine that what you really wanted is something like this:\n{ \n 104: [\n {'tid': 1234, 'date': '08/26/2022', 'total': '95.96'}, \n {'tid': 1235, 'date': '09/25/2022', 'total': '95.96'}, \n {'tid': 1236, 'date': '07/27/2022', 'total': '95.96'}\n ],\n 105: [\n {'ti...
[ 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074437708_dictionary_python.txt
Q: why the function isnt detect that the variable the_greater_list as list Why the function is_greater doesn't detect the variable the_greater_list as a list type of variable and class it as none. def is_greater(my_list, n): """the function check wich numbers in my list greater than n. :param my_list: the list. ...
why the function isnt detect that the variable the_greater_list as list
Why the function is_greater doesn't detect the variable the_greater_list as a list type of variable and class it as none. def is_greater(my_list, n): """the function check wich numbers in my list greater than n. :param my_list: the list. :param n: the cut from nubers than greater to number than smaller. :type m...
[ "Firstly, list(the_greater_list = []) is incorrect. You define an empty list by doing the_greater_list = []. Then, doing the_greater_list.append(number) returns a None, so when you do the_greater_list = the_greater_list.append(number), it makes the_greater_list as None\ndef is_greater(my_list, n):\n the_greater_...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074437738_python.txt
Q: Python : Calculate average of all items in a txt.file I have the following text file and I need to calculate average of sold units. "Time";"unit" "2022-09-23 12:00:00";8.10 "2022-07-19 14:00:00";8.11 "2022-09-21 14:00:00";7.88 "2022-08-11 07:00:00";7.42 "2022-07-07 00:00:00";7.81 "2022-01-06 01:00:00";8.38 "2022-0...
Python : Calculate average of all items in a txt.file
I have the following text file and I need to calculate average of sold units. "Time";"unit" "2022-09-23 12:00:00";8.10 "2022-07-19 14:00:00";8.11 "2022-09-21 14:00:00";7.88 "2022-08-11 07:00:00";7.42 "2022-07-07 00:00:00";7.81 "2022-01-06 01:00:00";8.38 "2022-02-11 02:00:00";9.96 "2022-03-12 07:00:00";10.94 Code to a...
[ "Open your file with context manager.\nGet a list of all lines in the file. Count the number of lines (excluding the header). Parse all lines except the first and split on semi-colon. That will give you two tokens. Convert the second token to float. Add that value to a running total.\nDivide the running total by th...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074437311_python.txt
Q: is there a way to get higher precision with pyspark greater than 38? using pyspark and glue jobs, it seems there is a max precision of 38. lots of crypto systems need greater precision. is there a way around this to increase precision without having to use an entirely different system? A: 38 is the max precisi...
is there a way to get higher precision with pyspark greater than 38?
using pyspark and glue jobs, it seems there is a max precision of 38. lots of crypto systems need greater precision. is there a way around this to increase precision without having to use an entirely different system?
[ "38 is the max precision for a Spark Decimal, since they use Java's BigDecimal Implementation under the hood.\nIf you need to calculate with a higher precision, I think you need to look for an alternative. I am not aware of any workarounds.\n" ]
[ 3 ]
[]
[]
[ "aws_glue", "precision", "pyspark", "python" ]
stackoverflow_0074437616_aws_glue_precision_pyspark_python.txt
Q: getting http debug info I'm going through Dive into Python3. When I get to the chapter on http web services section 14.4, I can't seem to duplicate the following output in the python3 shell. Here's what the sample code looks like: from http.client import HTTPConnection HTTPConnection.debuglevel = 1 from urllib.r...
getting http debug info
I'm going through Dive into Python3. When I get to the chapter on http web services section 14.4, I can't seem to duplicate the following output in the python3 shell. Here's what the sample code looks like: from http.client import HTTPConnection HTTPConnection.debuglevel = 1 from urllib.request import urlopen respons...
[ "The final command should not give any output, what you probably want is:\nprint(response.read())\n\n", "I know this is an old question, bit I thought I would answer to help those who might still be seeing this question.\nEver since Python version 3.5.2 (release ~June 2016) the http.client.HTTPConnection.debuglev...
[ 2, 0 ]
[]
[]
[ "http.client", "python", "python_3.x", "urllib" ]
stackoverflow_0039260276_http.client_python_python_3.x_urllib.txt
Q: Read a file, modify it, write it out, and then read it again - better options? I have a fixed width text file that I am trying to read in using pandas.read_fwf. As noted here, this method removes leading and trailing whitespace. In order to get around that, I'd like to replace every whitespace character with some ...
Read a file, modify it, write it out, and then read it again - better options?
I have a fixed width text file that I am trying to read in using pandas.read_fwf. As noted here, this method removes leading and trailing whitespace. In order to get around that, I'd like to replace every whitespace character with some filler character, read the file in as a Dataframe, do my manipulation and editing, r...
[ "You can use io.StringIO as a file-like object to read from\nimport io\n\nwith open(\"input.txt\") as inFile:\n txt1 = io.StringIO(inFile.read().replace(\" \", \"~\"))\n \ndf = pandas.read_fwf(txt1, widths=[8, 8, 8])\n\nand to write to\nout_text = io.StringIO()\nnp.savetxt(out_text, df.values, fmt='%s', ...
[ 2 ]
[]
[]
[ "file_io", "pandas", "python", "python_3.x" ]
stackoverflow_0074437365_file_io_pandas_python_python_3.x.txt
Q: Is there a way to pass inputs to a script from another script in python 3 I have a script that I need to run in a loop, however this script uses the input() function to define variable and I cannot edit the Original Script. main takes the input values as parameters, but those input variables are global variables. ...
Is there a way to pass inputs to a script from another script in python 3
I have a script that I need to run in a loop, however this script uses the input() function to define variable and I cannot edit the Original Script. main takes the input values as parameters, but those input variables are global variables. I am running this in pycharm if that's relevant. How can I pass those inputs in...
[ "Assuming you really can't edit the other script at all and it's using input() to read input, you can use unittest.mock.patch (or any other monkey-patch, but it's conveniently there) to override sys.stdin, the stream that input() reads, with a StringIO stream pre-loaded with the number inputs your other script expe...
[ 0 ]
[]
[]
[ "for_loop", "python", "python_3.10" ]
stackoverflow_0074437746_for_loop_python_python_3.10.txt
Q: Discord bot with pre-defined tags I have a problem. I have a list of programming languages, for example Python Javascript Pearl Dart C# C++ Java The user should be assigned a maximum of three programming languages as roles. Is there a possibility to use a tag input like for web pages in Discord? For example, the ...
Discord bot with pre-defined tags
I have a problem. I have a list of programming languages, for example Python Javascript Pearl Dart C# C++ Java The user should be assigned a maximum of three programming languages as roles. Is there a possibility to use a tag input like for web pages in Discord? For example, the user just writes Ja and the user gets b...
[ "You can use Select Rows.\nResources:\n\nDiscord Documentation\nDiscord.py Select Menus\nDiscord.py Role Select Menus\n\n" ]
[ 1 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074436825_discord_discord.py_python.txt
Q: Break line chart on the plot I have a dataframe with a column for weeks and data captured for each week. it looks like this # Import pandas library import pandas as pd # initialize list of lists data = [['20', 10], ['21', 15], ['23', 14], ['40', 50], ['41', 56]] # Create the p...
Break line chart on the plot
I have a dataframe with a column for weeks and data captured for each week. it looks like this # Import pandas library import pandas as pd # initialize list of lists data = [['20', 10], ['21', 15], ['23', 14], ['40', 50], ['41', 56]] # Create the pandas DataFrame df = pd.DataFrame(...
[ "First, I would re-index the data so weeks with no data are accounted for.\ndf['weeks'] = df['weeks'].astype(int)\ndf = df.set_index('weeks').reindex(np.arange(df['weeks'].min(),df['weeks'].max()+1)).reset_index()\n\n>>> df\n weeks counts\n0 20 10.0\n1 21 15.0\n2 22 NaN\n3 23 14...
[ 1 ]
[]
[]
[ "dataframe", "matplotlib", "pandas", "plotly", "python" ]
stackoverflow_0074428004_dataframe_matplotlib_pandas_plotly_python.txt
Q: How do I search a SQL List inside of python to check if the username matches a user input? So I am making a login page, and I need to compare the username of an SQL list to the user input. I will also use the answer for the password. This is what I have tried and it returns false. list_of_users = [('joe@gmail.com'...
How do I search a SQL List inside of python to check if the username matches a user input?
So I am making a login page, and I need to compare the username of an SQL list to the user input. I will also use the answer for the password. This is what I have tried and it returns false. list_of_users = [('joe@gmail.com', 'qwerty'), ('jeremy', '123')] for i in list_of_users: if i == 'joe@gmail.com': pr...
[ "Because the elements of your list are tuples of two elements. So each element has two in turn. See the definition in the official documentation of Data Structures - Tuples and Sequences.\nIf you wanted to fix your code, you would then simply add a second element to the for loop:\nlist_of_users = [('joe@gmail.com',...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074437823_python.txt
Q: Convert Pandas DataFrame to dictionary where columns are keys and (column-wise) rows are values I wish to convert a DataFrame into a dictionary where columns are the keys and (column-wise) rows are its values. I also need to use grouping when doing so. team id name salary 0 Alpha 10 Jack 1...
Convert Pandas DataFrame to dictionary where columns are keys and (column-wise) rows are values
I wish to convert a DataFrame into a dictionary where columns are the keys and (column-wise) rows are its values. I also need to use grouping when doing so. team id name salary 0 Alpha 10 Jack 1000 1 Alpha 15 John 2000 2 Alpha 20 John 2000 3 Bravo 50 Thomas 500...
[ "A Groupby then to_dict should do the trick:\nout = df.groupby('team').agg(list).to_dict('index')\nprint(out)\n\nOutput:\n{'Alpha': {'id': [10, 15, 20],\n 'name': ['Jack', 'John', 'John'],\n 'salary': [1000, 2000, 2000]},\n 'Bravo': {'id': [50, 55, 60],\n 'name': ['Thomas', 'Robert', '...
[ 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074437669_pandas_python.txt
Q: Python: how to utilize instances of a class New to OOP and python, I am struggling enormously to grasp what good classes actually are for. I tried to ask help from a lecturer who said "oh, then you should read about general methods to classes". Been putting in a days work but get no where. I get it that a class al...
Python: how to utilize instances of a class
New to OOP and python, I am struggling enormously to grasp what good classes actually are for. I tried to ask help from a lecturer who said "oh, then you should read about general methods to classes". Been putting in a days work but get no where. I get it that a class allow you to collect an instance structure and meth...
[ "It seems you want to find all the instances of a certain element within a class.\nThis is as simple as:\nprint([x for x in iL if x.item_id == selected_item])\n\nNow, you may ask why you can't just store the elements of iL as tuples instead of classes. The answer is, you can, but\n(\"idA\", \"A\")\n\nis much less d...
[ 0, 0 ]
[]
[]
[ "class", "data_processing", "database", "filter", "python" ]
stackoverflow_0074437796_class_data_processing_database_filter_python.txt
Q: How to get method parameter names? Given the Python function: def a_method(arg1, arg2): pass How can I extract the number and names of the arguments. I.e., given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2"). The usage scenario for this is that I have a decorator, and...
How to get method parameter names?
Given the Python function: def a_method(arg1, arg2): pass How can I extract the number and names of the arguments. I.e., given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2"). The usage scenario for this is that I have a decorator, and I wish to use the method arguments in t...
[ "Take a look at the inspect module - this will do the inspection of the various code object properties for you.\n>>> inspect.getfullargspec(a_method)\n(['arg1', 'arg2'], None, None, None)\n\nThe other results are the name of the *args and **kwargs variables, and the defaults provided. ie.\n>>> def foo(a, b, c=4, *...
[ 465, 104, 34, 25, 20, 17, 14, 11, 11, 5, 2, 2, 2, 1, 0, 0, 0 ]
[ "I was googling to find how to print function name and supplied arguments for an assignment I had to create a decorator to print them and I used this:\ndef print_func_name_and_args(func):\n \n def wrapper(*args, **kwargs):\n print(f\"Function name: '{func.__name__}' supplied args: '{args}'\")\n func(arg...
[ -1, -1, -3 ]
[ "decorator", "introspection", "python", "python_datamodel" ]
stackoverflow_0000218616_decorator_introspection_python_python_datamodel.txt
Q: How to efficiently compare every row to all other rows in a Pandas Dataframe based on different conditions? I have a Python Pandas dataframe which consists of different columns: import pandas as pd import numpy as np dict = {'Payee Name':["John", "John", "John", "Sam", "Sam"], 'Amount': [100, 30, 95, 30, ...
How to efficiently compare every row to all other rows in a Pandas Dataframe based on different conditions?
I have a Python Pandas dataframe which consists of different columns: import pandas as pd import numpy as np dict = {'Payee Name':["John", "John", "John", "Sam", "Sam"], 'Amount': [100, 30, 95, 30, 30], 'Payment Method':['Cheque', 'Electronic', 'Electronic', 'Cheque', 'Electronic'], 'Payment R...
[ "I suggest you try using groupby on 'Payee Name' to break your dataframe into smaller pieces then run the inefficient code on these individually. (see split-apply-combine for discussion of approach). With luck you will see sufficient improvement to call it a day and move on to your next project.\nSee split-apply-co...
[ 1 ]
[]
[]
[ "dataframe", "iteration", "pandas", "python", "vectorization" ]
stackoverflow_0074430548_dataframe_iteration_pandas_python_vectorization.txt
Q: Check if all dataframe row values are in specified range How to check for each row in dataframe if all its values are in specified range? import pandas as pd new = pd.DataFrame({'a': [1,2,3], 'b': [-5,-8,-3], 'c': [20,0,0]}) For instance range <-5, 5>: >> a b c >> 0 1 -5 20 # abs(20) > 5, hence no >> 1 ...
Check if all dataframe row values are in specified range
How to check for each row in dataframe if all its values are in specified range? import pandas as pd new = pd.DataFrame({'a': [1,2,3], 'b': [-5,-8,-3], 'c': [20,0,0]}) For instance range <-5, 5>: >> a b c >> 0 1 -5 20 # abs(20) > 5, hence no >> 1 2 -8 0 # abs(-8) > 5, hence no >> 2 3 -3 0 # abs(-3) <...
[ "Doing:\nout = (df.gt(-5) & df.lt(5)).all(axis=1)\n# Or if you just want to supply a single value:\n# df.abs().lt(5).all(axis=1)\nprint(out)\n\nOutput:\n0 False\n1 False\n2 True\ndtype: bool\n\n\nYou could add this as a new column, and change things to no/yes if desired (which imo is a terrible idea):\ndf...
[ 2, 1 ]
[]
[]
[ "any", "dataframe", "pandas", "python" ]
stackoverflow_0074437465_any_dataframe_pandas_python.txt
Q: how do I save a random choice when I myself don't know what the choice will be? import random print( "Do you think you know all the animals?! if yes then this game is for \033[1myou!\033[0m") print("\033[7m""Let the game begin! ""\033[0m") animals = ("ant baboon badger bat bear beaver camel cat clam cobra cou...
how do I save a random choice when I myself don't know what the choice will be?
import random print( "Do you think you know all the animals?! if yes then this game is for \033[1myou!\033[0m") print("\033[7m""Let the game begin! ""\033[0m") animals = ("ant baboon badger bat bear beaver camel cat clam cobra cougar").split() you_chose = [] animal = random.choice(animals) hint = random.choice(lis...
[ "try something like this, this will make the animals string input into a list:\nanimals = list(animals)\nanimal = random.choice(animals)\nprint(animal)\nor try:\nanimals = ['cat','human','dog','bird'...]\nanimal = random.choice(animals)\nprint(animal)\n" ]
[ 0 ]
[]
[]
[ "python", "random", "while_loop" ]
stackoverflow_0074437682_python_random_while_loop.txt
Q: Adding whitespaces around each element of a list of lists python I want to add whitespaces around each element within a list of lists data = [["hello", "world"], ["python", "is", "cool"]] --> data = [[" hello ", " world "], [" python ", " is ", " cool "]] data_new = ["hello world", "python is cool"] data_new2 = [...
Adding whitespaces around each element of a list of lists python
I want to add whitespaces around each element within a list of lists data = [["hello", "world"], ["python", "is", "cool"]] --> data = [[" hello ", " world "], [" python ", " is ", " cool "]] data_new = ["hello world", "python is cool"] data_new2 = [x.split(" ") for x in data_new] --> [["hello", "world"], ["python", "i...
[ "You don't need to split, use a nested list comprehension (here with a f-string):\ndata = [[\"hello\", \"world\"], [\"python\", \"is\", \"cool\"]]\n\ndata2 = [[f' {x} ' for x in l] for l in data]\n\nOutput:\n[[' hello ', ' world '], [' python ', ' is ', ' cool ']]\n\nAlternative input:\ndata = [\"hello world\", \"p...
[ 0, 0 ]
[]
[]
[ "format", "list_comprehension", "python", "whitespace" ]
stackoverflow_0074429921_format_list_comprehension_python_whitespace.txt
Q: Python - Pandas - drop specific columns (axis)? So I got a numeric list [0-12] that matches the length of my columns in my spreadsheet and also replaced the column headers with that list df.columns = list. Now i want to drop specific columns out of that spreadsheet like this. To create the list of numbers to match...
Python - Pandas - drop specific columns (axis)?
So I got a numeric list [0-12] that matches the length of my columns in my spreadsheet and also replaced the column headers with that list df.columns = list. Now i want to drop specific columns out of that spreadsheet like this. To create the list of numbers to match the length of columns I got this: listOfNumbers = []...
[ "the proper way will be:\ncolumns_to_remove = [1, 2, 3] # columns to delete\ndf = df.drop(columns=df.columns[columns_to_remove])\n\nSo for your use case:\nfor i in range(1, len(df.columns)):\n for j in range(1, len(df.columns)):\n if i != colList[j]:\n df.drop(columns=df.columns[i], inplace=Tru...
[ 0, 0 ]
[]
[]
[ "axis", "drop", "pandas", "python", "spreadsheet" ]
stackoverflow_0074437709_axis_drop_pandas_python_spreadsheet.txt
Q: Find permutations which also match other constraints Given the following list: dbset = [[{'id': '10556', 'nation': 'France', 'worth': '70'}], [{'id': '14808', 'nation': 'France', 'worth': '65'}], [{'id': '11446', 'nation': 'Ghana', 'worth': '69'}], [{'id': '11419', 'nation': 'France', 'worth': '69'}], [{'id': '111...
Find permutations which also match other constraints
Given the following list: dbset = [[{'id': '10556', 'nation': 'France', 'worth': '70'}], [{'id': '14808', 'nation': 'France', 'worth': '65'}], [{'id': '11446', 'nation': 'Ghana', 'worth': '69'}], [{'id': '11419', 'nation': 'France', 'worth': '69'}], [{'id': '11185', 'nation': 'Ghana', 'worth': '69'}], [{'id': '1527', '...
[ "What you want is as simple as:\nperms = list(permutations(dbset,4))\nout = [x in perms if CONDITION]\n\nThe second condition is as simple as:\nout = [x for x in perms if sum([int(country[0][\"worth\"]) for country in x]) >= 300]\n\nNote that this will be empty in your case, since the maximum worth of any nation is...
[ 1, 0 ]
[]
[]
[ "constraints", "permutation", "python", "python_itertools" ]
stackoverflow_0074437910_constraints_permutation_python_python_itertools.txt
Q: 2 unknown equations raise NotImplementedError I have these 2 unknown equations problem(technically 4, two pairs) The results should be these or close to them: wI = 0.107 ∈ (a1, a2) , y= 0.176. wII = 0.123 ∈ (b1, b2) , x= 0.877. I wrote for each of them 2 types of solver, the first one is the case where the equati...
2 unknown equations raise NotImplementedError
I have these 2 unknown equations problem(technically 4, two pairs) The results should be these or close to them: wI = 0.107 ∈ (a1, a2) , y= 0.176. wII = 0.123 ∈ (b1, b2) , x= 0.877. I wrote for each of them 2 types of solver, the first one is the case where the equations are equal to zero and the second when they are...
[ "Based on your 'results', it seems like you're looking for a numeric solution - so Sympy is the wrong tool for the job. Do a bounded, numeric, non-linear minimization of a scalar least-squares cost. Many of the Scipy methods work; slsqp converges quickly, powell is a little more accurate:\nimport numpy as np\nfrom ...
[ 1, 0 ]
[]
[]
[ "math", "numpy", "python", "sympy" ]
stackoverflow_0074422203_math_numpy_python_sympy.txt
Q: SQLALCHEMY - returning a pretty format I am trying to create a basic CRUD application with python using sqlalchemy. It is just a virtual contact book, that runs in the terminal. I have managed to create this and get it working successfully, but I am having trouble with the following: Whenever I run one of the sqla...
SQLALCHEMY - returning a pretty format
I am trying to create a basic CRUD application with python using sqlalchemy. It is just a virtual contact book, that runs in the terminal. I have managed to create this and get it working successfully, but I am having trouble with the following: Whenever I run one of the sqlalchemy functions to access the database, I g...
[ "Try setting echo to False like this:\nengine = create_engine(\"sqlite:///contacts.db\", echo=False)\nsqlalchemy.create_engine.params.echo\n" ]
[ 1 ]
[]
[]
[ "crud", "database", "python", "sql", "sqlalchemy" ]
stackoverflow_0074437158_crud_database_python_sql_sqlalchemy.txt
Q: Verbose logging for urllib.request.urlopen Is there any way to enable some kind of verbose logging for urllib? I'm especially trying to find out which TLS-Cert files its using and which proxy its using. I.e. if it is actually using what I configured in the env. A: In Python version 3.5.1 and earlier, you can do ...
Verbose logging for urllib.request.urlopen
Is there any way to enable some kind of verbose logging for urllib? I'm especially trying to find out which TLS-Cert files its using and which proxy its using. I.e. if it is actually using what I configured in the env.
[ "In Python version 3.5.1 and earlier, you can do this two ways:\n\nYou can use the constructor argument for HTTPHandler and HTTPSHandler (as demonstrated in this SO answer):\nimport urllib.request\n\nhandler = urllib.request.HTTPHandler(debuglevel=10)\nopener = urllib.request.build_opener(handler)\ncontent = opener...
[ 0 ]
[]
[]
[ "python", "python_3.x", "urllib" ]
stackoverflow_0071696148_python_python_3.x_urllib.txt
Q: How to Solve a System of Equations with a constructor on python I am in Uni and I am required to do a specific task the task is: Create a class that represents a system of linear algebra equations (system of equations), finding roots and checking whether some set of numbers exists as a solution of the system. Bas...
How to Solve a System of Equations with a constructor on python
I am in Uni and I am required to do a specific task the task is: Create a class that represents a system of linear algebra equations (system of equations), finding roots and checking whether some set of numbers exists as a solution of the system. Based on this class, create descendant classes representing systems of t...
[ "Your class should not contain any sample numbers. You should just accept a and c as parameters, and store self.a = a and self.c = c. You don't pass in x, since that's an output of the class. And you don't do the solving until you call solve().\nSomething like this:\nimport numpy as np\nclass Linear:\n # lin...
[ 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074436435_numpy_python.txt
Q: How to get two synchronised generators from a function i have a nested tuple like this one : this_one = (w,h,(1,2,4,8,16),(0,2,3,4,6),("0"),("0"),(0,1)) It will be used to feed: itertools.product(*this_one) w and h have to be both generators. Generated values from h depends on generated values from w as in this f...
How to get two synchronised generators from a function
i have a nested tuple like this one : this_one = (w,h,(1,2,4,8,16),(0,2,3,4,6),("0"),("0"),(0,1)) It will be used to feed: itertools.product(*this_one) w and h have to be both generators. Generated values from h depends on generated values from w as in this function: def This_Function(maxvalue): for i in range(max...
[ "That's fundamentally not how product works. From the documentation:\n\nBefore product() runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products. Accordingly, it is only useful with finite inputs.\n\nThus, having the second one be dependent won't get you the resu...
[ 2, 1 ]
[]
[]
[ "generator", "python", "python_itertools", "yield" ]
stackoverflow_0074438010_generator_python_python_itertools_yield.txt
Q: How do I access a pandas groupby dataframe by grouped index? Following this example I can create a simple dataframe and groupby import pandas as pd # Create a sample data frame df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar'], 'B': range(5), 'C': range(5)}) # group by 'A' and sum 'B...
How do I access a pandas groupby dataframe by grouped index?
Following this example I can create a simple dataframe and groupby import pandas as pd # Create a sample data frame df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar'], 'B': range(5), 'C': range(5)}) # group by 'A' and sum 'B' gf = df.groupby('A').agg({'B': 'sum'}) The result is the groupe...
[ "gf.reset_index(level=0, inplace=True)\n\ngf[gf.A == 'bar']\n\nreturns: \n A B\n0 bar 7\n\nPlot: \nimport matplotlib.pyplot as plt\n\nplt.bar(gf.A, gf.B)\n\n", "What about:\nimport matplotlib.pyplot as plt\n\nfor k in gf['B'].index:\n print \"{}: {}\".format(k, gf['B'].loc[k])\n\nplt.bar(gf['B'].index, ...
[ 5, 0, 0 ]
[]
[]
[ "pandas", "pandas_groupby", "python", "python_3.x" ]
stackoverflow_0051124296_pandas_pandas_groupby_python_python_3.x.txt
Q: Creating an adjacency list class in Python I was wondering how to create an adjacency list class Here is what I have so far: class AdjNode: def __init__(self, value): self.vertex = value self.next = None class Graph: def __init__(self): # Add edges def add_edge(self, u...
Creating an adjacency list class in Python
I was wondering how to create an adjacency list class Here is what I have so far: class AdjNode: def __init__(self, value): self.vertex = value self.next = None class Graph: def __init__(self): # Add edges def add_edge(self, u, v): node = AdjNode(v) node.nex...
[ "Here is a very verbose example; not exactly what you want, but I feel it's a start, and as mentioned in the comments, uses a standard list.\nI think you should look into classes further and attempt to understand OOP; I think you'd be doing yourself an injustice by not understanding what is being asked but rather a...
[ 1 ]
[]
[]
[ "adjacency_list", "python" ]
stackoverflow_0074438226_adjacency_list_python.txt
Q: Pylance: "property" is incompatible with "int" from typing_extensions import Protocol class IFoo(Protocol): value: int class Foo(IFoo): @property def value(self) -> int: return 2 _value: int @value.setter def value(self, value: int): self._value = value Pylance in stric...
Pylance: "property" is incompatible with "int"
from typing_extensions import Protocol class IFoo(Protocol): value: int class Foo(IFoo): @property def value(self) -> int: return 2 _value: int @value.setter def value(self, value: int): self._value = value Pylance in strict mode(basic mode doesn't) is giving an error at ...
[ "Reading the Defining a protocol section of the relevant pep (PEP 544), the example implementation (in their case, class Resource) does not directly inherit from the protocol - their class SupportsClose functions as a reference type for type hinting validators.\nYour example is also reminiscent of the long establi...
[ 0 ]
[]
[]
[ "getter_setter", "interface", "pylance", "python", "type_hinting" ]
stackoverflow_0069006473_getter_setter_interface_pylance_python_type_hinting.txt
Q: Is "add" operation in set() or "insert" in dict() in Python actually O(n) where n is the length of the key string? There is a contradiction on whether the insert operation on dict() or add operation in set() is O(n) or O(1), where n is the length of the string. Suppose we have strings which vary in length i.e. n1,...
Is "add" operation in set() or "insert" in dict() in Python actually O(n) where n is the length of the key string?
There is a contradiction on whether the insert operation on dict() or add operation in set() is O(n) or O(1), where n is the length of the string. Suppose we have strings which vary in length i.e. n1, n2, ...n_x. Then the time complexity of performing the following: s = set() d = dict() for x in {N}: # where N = [n1, n...
[ "There are gazillion things on which the performance of insert depends on. The calculation of hash function indeed is O(k) for a string of length k, but it is just uninteresting in general case. \nIf you consider string keys of only 8 bytes of length, there are 18446744073709551616 different combinations and 8 is a...
[ 3, 0 ]
[]
[]
[ "add", "dictionary", "python", "set", "time_complexity" ]
stackoverflow_0055954204_add_dictionary_python_set_time_complexity.txt
Q: Is there any way to integrate Databricks and sonarlint for pyspark/python code? If not, then what can be the alternatives? I want my databricks notebook to automatically analyze the errors, bugs, suggestions etc, to make my work more efficient. I came to know about sonar lint but can't find it's implementation wi...
Is there any way to integrate Databricks and sonarlint for pyspark/python code? If not, then what can be the alternatives?
I want my databricks notebook to automatically analyze the errors, bugs, suggestions etc, to make my work more efficient. I came to know about sonar lint but can't find it's implementation with databricks. Pls, suggest some alternative, if any.
[ "I would recommend getting out of the Databricks web interface and use VSCode with Sonarlint thanks to this VSCode Extension : https://marketplace.visualstudio.com/items?itemName=paiqo.databricks-vscode\nIt will allow you to execute your code on the Databricks cluster from within VSCode notebooks and use any lintin...
[ 0 ]
[]
[]
[ "apache_spark", "databricks", "pyspark", "python", "sonarlint" ]
stackoverflow_0074428112_apache_spark_databricks_pyspark_python_sonarlint.txt
Q: Is there a way to set a debugger breakpoint on a Python inbuilt function like print()? I have a large codebase I'm working with, and somewhere within it there's a print statement which is printing many '\n' newline characters. I know I can set a breakpoint on my own code, but is there a way for me to set a breakpo...
Is there a way to set a debugger breakpoint on a Python inbuilt function like print()?
I have a large codebase I'm working with, and somewhere within it there's a print statement which is printing many '\n' newline characters. I know I can set a breakpoint on my own code, but is there a way for me to set a breakpoint Python's inbuilt print() statement? Or any inbuilt function for that matter. What would ...
[ "Python can be patched at runtime, trivially, so you could add something like this early on in your runtime:\nimport builtins\norig_print = builtins.print\n\ndef my_print(*args, **kwargs):\n orig_print(*args, **kwargs)\n breakpoint()\n\nbuiltins.print = my_print\n\nNote that there are other ways to get bytes ...
[ 1 ]
[]
[]
[ "breakpoints", "debugging", "python" ]
stackoverflow_0074438320_breakpoints_debugging_python.txt
Q: cannot find reference for opencv functions in pycharm I have opencv-python installed and the .pyd file is added in the site-packages and the DLLs. The code works with images. When I want to read, show, write an image it works. But I get a warning that the functions' references cannot be found in init.py . Due to t...
cannot find reference for opencv functions in pycharm
I have opencv-python installed and the .pyd file is added in the site-packages and the DLLs. The code works with images. When I want to read, show, write an image it works. But I get a warning that the functions' references cannot be found in init.py . Due to this, I can not use the auto-complete feature. Could someone...
[ "The problem is caused by CV2 and how __init__.py does the imports. Just ignore the warnings the program will work all the same, or you can do an import with an alias like:\nimport cv2.cv2 as cv2\n\nIf you have a warning on it press Alt+Enter to install and fix it. Now you will have the code completion and no other...
[ 25, 6, 5, 2, 1, 0 ]
[]
[]
[ "opencv", "pycharm", "python" ]
stackoverflow_0048772621_opencv_pycharm_python.txt
Q: TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced I am trying to convert a csv into numpy array. In the numpy array, I am replacing few elements with NaN. Then, I wanted to find the indices of the NaN elements in the numpy array. The code is : import pandas ...
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced
I am trying to convert a csv into numpy array. In the numpy array, I am replacing few elements with NaN. Then, I wanted to find the indices of the NaN elements in the numpy array. The code is : import pandas as pd import matplotlib.pyplot as plyt import numpy as np filename = 'wether.csv' df = pd.read_csv(filenam...
[ "Posting as it might help future users.\nAs correctly pointed out by others, np.isnan won't work for object or string dtypes. If you're using pandas, as mentioned here you can directly use pd.isnull, which should work in your case.\nimport pandas as pd\nimport numpy as np\nvar1 = ''\nvar2 = np.nan\n>>> type(var1)\n...
[ 39, 24, 23, 2, 1, 0, 0 ]
[]
[]
[ "missing_data", "nan", "numpy", "numpy_ufunc", "python" ]
stackoverflow_0052657223_missing_data_nan_numpy_numpy_ufunc_python.txt
Q: Pandas groupby filter on column, and then plot the results I have the following df: subject_id name day value 1 sld 0 0 1 sld 1 5 1 sld 2 12 1 dsld 0 0 1 dsld 1 -1 2 sld 0 0 2 sld 1 7 2 sld 2 8 2 sld 3 4 2 dsld 0 0 I want to make a line plot with the following criteria: Group by subject_id for each gr...
Pandas groupby filter on column, and then plot the results
I have the following df: subject_id name day value 1 sld 0 0 1 sld 1 5 1 sld 2 12 1 dsld 0 0 1 dsld 1 -1 2 sld 0 0 2 sld 1 7 2 sld 2 8 2 sld 3 4 2 dsld 0 0 I want to make a line plot with the following criteria: Group by subject_id for each group, only take the rows where name == sld line...
[ "IIUC,\ndf.query('name == \"sld\"').set_index(['day', 'subject_id'])['value'].unstack().plot()\n\nOutput:\n\n" ]
[ 0 ]
[]
[]
[ "group_by", "pandas", "python", "seaborn" ]
stackoverflow_0074437855_group_by_pandas_python_seaborn.txt
Q: Use Airflow Bash Operator with Airflow Config values automatically included We are using Airflow 2.3.4. We want to use the Bash Operator to perform Airflow commands. Following this documentation on the Bash operator. One can add environment variables to the bash operator so they can be used in the commands. Is the...
Use Airflow Bash Operator with Airflow Config values automatically included
We are using Airflow 2.3.4. We want to use the Bash Operator to perform Airflow commands. Following this documentation on the Bash operator. One can add environment variables to the bash operator so they can be used in the commands. Is there a way to also add values from the airflow config that are stored as environmen...
[ "You can add whatever you want:\nimport os\n\n# one env\nbash_task = BashOperator(\n task_id=\"bash_task\",\n bash_command=\"echo $var1_name && echo $var2_name\",\n env={\n \"var1_name\": \"{{ <any jinja var> }}\",\n \"var2_name\": \"static value\",\n },\n)\n\n# all env from airflow host\n...
[ 1 ]
[]
[]
[ "airflow", "bash", "python" ]
stackoverflow_0074429941_airflow_bash_python.txt
Q: Python GTK 3 - TreeView - Allow mouse selection on the row for copying contents I'm new on Python GTK and I was developing a simple TreeView that show several data: import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk # list of tuples for each variable, containing the environment variable nam...
Python GTK 3 - TreeView - Allow mouse selection on the row for copying contents
I'm new on Python GTK and I was developing a simple TreeView that show several data: import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk # list of tuples for each variable, containing the environment variable name, its path, and the security category variable_list = [ ("$ENV1", "/usr/share/ba...
[ "If selection was possible, this would have to be done by setting a property in Gtk.CellRendererText, but I don't see a property that would make that possible, besides editable:\nrenderer.set_property(\"editable\", True)\n\nMaking the cells editable would certainly allow users to copy from them, but this would sugg...
[ 0 ]
[]
[]
[ "copy_paste", "gtk", "gtk3", "python" ]
stackoverflow_0074310090_copy_paste_gtk_gtk3_python.txt
Q: How to replace single item in a 2D array? double indexing not working I have tried to use double indexing but this has not worked for me. P.S check my work below As you can see my code is not replacing only the digit at x,y position but every position at x. Example variables for solution field =[[0, 1, 1],[1, 0, 1...
How to replace single item in a 2D array? double indexing not working
I have tried to use double indexing but this has not worked for me. P.S check my work below As you can see my code is not replacing only the digit at x,y position but every position at x. Example variables for solution field =[[0, 1, 1],[1, 0, 1],[0, 0, 1]] x_axis = 1 y_axis = 1 Input def solution(field, x, y): ar...
[ "Why can´t you just replace your item like this:\ndef solution(field, x, y):\n field[x][y] = 5 # insert any number you want\n\nWhy are you iterating over your 2D array?\n", "For this you can use also numpy, that has not the reference problem stated by Yevhen Kuzmovych\nimport numpy as np\n\ndef solution(field, ...
[ 0, 0, 0 ]
[]
[]
[ "minesweeper", "python", "python_3.x" ]
stackoverflow_0074437889_minesweeper_python_python_3.x.txt
Q: iterate through a list and add to add an 1 or 0 to corresponding columns in a data frame I am creating a user interface with the code below: data_pool = {'corpus': ['aa', 'bb', 'cc','dd', 'ee'], 'zero_level_name': ['a', 'b', 'c','d', 'e'], 'time': ['', '', '', '', ''], 'labels': ['', '', '', '', '']} data_pool =...
iterate through a list and add to add an 1 or 0 to corresponding columns in a data frame
I am creating a user interface with the code below: data_pool = {'corpus': ['aa', 'bb', 'cc','dd', 'ee'], 'zero_level_name': ['a', 'b', 'c','d', 'e'], 'time': ['', '', '', '', ''], 'labels': ['', '', '', '', '']} data_pool = pd.DataFrame(data_pool) print(data_pool) data_pool[['label1', 'label2', 'label3', 'label4']...
[ "Note that your break is exiting the for loop, try to remove it and see if it solves your problem :)\nSo even if you have two labels that are valid, you exit after the first one\n(or maybe you wanted the break, to exit the while loop, but I'm not sure I understand the logic there..)\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074438246_dataframe_pandas_python.txt
Q: How to merge markers in Plotly for my Scattergeo map I've gathered a large dataset of longitude and latitude values, and I want to showcase them on a map. After some searching, I came across Plotly. Currently, I am able to generate a map that has all the locations marked on it; however, a lot of markers overlap. T...
How to merge markers in Plotly for my Scattergeo map
I've gathered a large dataset of longitude and latitude values, and I want to showcase them on a map. After some searching, I came across Plotly. Currently, I am able to generate a map that has all the locations marked on it; however, a lot of markers overlap. This happens because a lot of the locations are situated in...
[ "To my knowledge, Plotly can't do this automatically. You'd have to alter your dataframe and decide which points are close enough together to be grouped. For this dataframe, since the points are rather far away from each other, I've defined \"close\" to be within 200 miles.\nimport pandas as pd\nimport numpy as np\...
[ 0, 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074055452_plotly_python.txt
Q: Filtering a Pandas Dataframe by an aggregate function? So I have dataframe that looks like this: STORE PRODUCT INVENTORY 1 store1 a 1 2 store1 b 0 3 store2 a 0 4 store2 b 0 5 store3 a 1 6 store3 b 1 I w...
Filtering a Pandas Dataframe by an aggregate function?
So I have dataframe that looks like this: STORE PRODUCT INVENTORY 1 store1 a 1 2 store1 b 0 3 store2 a 0 4 store2 b 0 5 store3 a 1 6 store3 b 1 I want to filter this such that it only shows me stores with a ...
[ "You can try:\ndf.loc[(df.groupby('STORE')['INVENTORY'].transform(sum) > 0)]\n\n STORE PRODUCT INVENTORY\n1 store1 a 1\n2 store1 b 0\n5 store3 a 1\n6 store3 b 1\n\n", "We can use filter like below\ndf.groupby('STORE').filter(lambda x: x['INVENTOR...
[ 3, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074437634_dataframe_pandas_python.txt
Q: Creating A CSV file on ubuntu server using cocotb Here I want to create a csv file on cocotb, but the following code is for Google Colab which is working perfectly. import cocotb from cocotb.triggers import Timer import random import pyuvm import pandas as pd from pandas import Series, DataFrame import os from goo...
Creating A CSV file on ubuntu server using cocotb
Here I want to create a csv file on cocotb, but the following code is for Google Colab which is working perfectly. import cocotb from cocotb.triggers import Timer import random import pyuvm import pandas as pd from pandas import Series, DataFrame import os from google.colab import drive drive.mount('/content/drive') os...
[ "You probably just want to omit importing the google drive lib:\n# from google.colab import drive\n# drive.mount('/content/drive')\n# os.chdir('/content/drive/My Drive/Colab Notebooks')\n\n# Change directory to somewhere you have access on the server\nos.chdir('~/content/collab_notebooks')\n\n" ]
[ 0 ]
[]
[]
[ "csv", "python", "python_3.x", "ubuntu" ]
stackoverflow_0074438269_csv_python_python_3.x_ubuntu.txt
Q: Python using bar_label on multiple bars I would like to use the offer_difference list as bar_label on the plot. Prefer one that's in the above the two bars in the middle. However, after reading many explanations and tutorials including the official matplotlib ones, I can't manage to do it. Example code: import mat...
Python using bar_label on multiple bars
I would like to use the offer_difference list as bar_label on the plot. Prefer one that's in the above the two bars in the middle. However, after reading many explanations and tutorials including the official matplotlib ones, I can't manage to do it. Example code: import matplotlib.pyplot as plt import numpy as np nam...
[ "A method you can use is adding a text for the first bar of each pair and move it into position. To do this you can use the BarContainer that plt.bar returns (rects1 and rects2 in my code below) and get the x and y locations to use as guidance for the text. Here is how you can go about it:\nimport numpy as np\nimpo...
[ 0 ]
[]
[]
[ "bar_chart", "label", "matplotlib", "python" ]
stackoverflow_0074420330_bar_chart_label_matplotlib_python.txt
Q: How would I use input validation within a counter while loop in python code? Problem: Write a program that will allow a grocery store to keep track of the total number of bottles collected for recycling for seven days. The program should allow the user to enter the number of bottles returned for each of the seven ...
How would I use input validation within a counter while loop in python code?
Problem: Write a program that will allow a grocery store to keep track of the total number of bottles collected for recycling for seven days. The program should allow the user to enter the number of bottles returned for each of the seven days. The program will calculate the total number of bottles returned for the week...
[ "\nif the user enters a number less than 0, my code needs to writs \"Input cannot be less than 0\" and then it will continue with the code. How can I do this?\n\nYou can just add a verification and use the continue statement:\nwhile counter <= 7:\n\n print ('Enter the number of bottles for today: ')\n\n today...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074438450_python.txt
Q: ModuleNotFoundError even though I already installed it with pip I am trying to import python packages but it won't work. It fails with every package. And when I try pip install or conda install it says that the requirement is already satisfied... And when in the terminal I use python, import mysql won't work eith...
ModuleNotFoundError even though I already installed it with pip
I am trying to import python packages but it won't work. It fails with every package. And when I try pip install or conda install it says that the requirement is already satisfied... And when in the terminal I use python, import mysql won't work either. This is the content of my terminal : (venv) C:\Users\<user>\...
[ "mysql is actually just a meta-package that installs mysqlclient (see that in the pip output?). Naturally, you can't just import mysqlclient either because that would be too easy.\nYou need to use import MySQLdb\nSee: https://mysqlclient.readthedocs.io/user_guide.html\n" ]
[ 1 ]
[]
[]
[ "conda", "environment_variables", "modulenotfounderror", "path", "python" ]
stackoverflow_0074438422_conda_environment_variables_modulenotfounderror_path_python.txt
Q: Python build can't detect pyproject.toml file I keep getting the following error when I run python -m build in the directory I have my pyproject.toml file: package_name does not appear to be a Python project: no pyproject.toml or setup.py This is how my directory looks like package_root --> Base setup.cfg ...
Python build can't detect pyproject.toml file
I keep getting the following error when I run python -m build in the directory I have my pyproject.toml file: package_name does not appear to be a Python project: no pyproject.toml or setup.py This is how my directory looks like package_root --> Base setup.cfg MANIFEST.in pyproject.toml src/ --> ...
[ "I am able to build a package with this structure basically:\npackage_root --> Base\n pyproject.toml\n requirements.txt\n src/ --> Actual Module\n some_code_file.py\n some_code_file2.py\n __init__.py\n\nAnd this is the contents of my pyproject.toml:\n[build-system]\nrequires = [\...
[ 0 ]
[]
[]
[ "package", "pyproject.toml", "python", "setup.py", "setuptools" ]
stackoverflow_0070159630_package_pyproject.toml_python_setup.py_setuptools.txt
Q: VSCode Run -> Start Debugging Python with Launch.json Doesn't Run Anything In Visual Studio Code, After setting up a launch.json for Python Flask, I got a file like this: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more informat...
VSCode Run -> Start Debugging Python with Launch.json Doesn't Run Anything
In Visual Studio Code, After setting up a launch.json for Python Flask, I got a file like this: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0...
[ "This can happen when the Python version of your project (e.g. used by venv) is no longer supported by the Python debugger installed as a VSCode Extension. For example, Python 3.6 stopped being supported by the extension mid 2022, so if your project still uses Python 3.6, the latest version of the debugger will sil...
[ 1 ]
[]
[]
[ "flask", "python", "visual_studio_code", "vscode_debugger" ]
stackoverflow_0074438532_flask_python_visual_studio_code_vscode_debugger.txt
Q: How to format the output correct with combined methods? I have a combination of methods. And I try to fromat them correct. So I have this functions: from __future__ import print_function import itertools import locale import operator import re verdi50 ="[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuu...
How to format the output correct with combined methods?
I have a combination of methods. And I try to fromat them correct. So I have this functions: from __future__ import print_function import itertools import locale import operator import re verdi50 ="[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. : 71201 Koopliedenweg 33\nDeb. nr. : 108636 2991 LN BA...
[ "You're concatenating total_fruit_per_sort() at the end of the join. You need to concatenate it to the first 3 items being joined.\nYou can split it into lines, then use itertools.zip_longest() to loop over this in parallel with the generator.\ndef show_extracted_data_from_file():\n regexes = [\n verdi_tot...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074438187_python.txt
Q: Is it beneficial to replace a simple Python class with a closure? I have the following Python class: class class A: """a class that increments internal variable""" def __init__(self, x): self._x = x def incr(self): self._x = (self._x + 1) % 10 return self._x I heard a talk that...
Is it beneficial to replace a simple Python class with a closure?
I have the following Python class: class class A: """a class that increments internal variable""" def __init__(self, x): self._x = x def incr(self): self._x = (self._x + 1) % 10 return self._x I heard a talk that recommended that such classes with just a constructor and another meth...
[ "The real benefit of closures and higher-order functions is that they can represent what the programmer sometimes has in mind. If you as the programmer find that what you have in mind is a piece of code, a function, an instruction on how to compute something (or do something), then you should use a closure for thi...
[ 6, 0, 0 ]
[]
[]
[ "closures", "python" ]
stackoverflow_0019090024_closures_python.txt