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:
Creating a program that reads a file and returns the smallest variable and how many variables are in the file
I am creating a program on Python that reads a text file and prints the lowest variable and then prints however many variables are in the text file. I have gotten somewhat finished with it, however it is r... | Creating a program that reads a file and returns the smallest variable and how many variables are in the file | I am creating a program on Python that reads a text file and prints the lowest variable and then prints however many variables are in the text file. I have gotten somewhat finished with it, however it is returning '0' when I run the program. I, too, want to create this with it catching IOError and ValueErrors. This is ... | [
"You can store the data on a dictionary and use min() to find the smallest value.\ndict = {}\n\nfor line in numbers:\n ...\n dict[name] = grade # {'a': 1, 'b': 2}\n \nprint(f'{min(dict)}: {dict[min(dict)]}') # Mark: 77 \n\nThe min() function search the lowest value on the dict and return this key, that in... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074452621_python.txt |
Q:
Python Pandas Concat Error (Reindexing only valid with uniquely valued Index objects)
I am trying to parse rows of xml from a snowflake database. The xml is stored in fields of a snowflake database. In each row of xml, there are thousands of children which I am trying to parse into a single dataframe with thousa... | Python Pandas Concat Error (Reindexing only valid with uniquely valued Index objects) | I am trying to parse rows of xml from a snowflake database. The xml is stored in fields of a snowflake database. In each row of xml, there are thousands of children which I am trying to parse into a single dataframe with thousands of columns. Additionally, the structure of each row of xml could potentially be differ... | [
"The issue was how I was building the df_parsed dataframe. Instead I build the parsed dataframe by looping through the xml and storing the tags and texts in a dict, then using the dict to build the dataframe.\ndf_dict = {}\n\n#loop through entire responsexml (element object) and extract all child tags and texts int... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"parsing",
"python",
"xml"
] | stackoverflow_0074439195_dataframe_pandas_parsing_python_xml.txt |
Q:
Jump game 2 leetcode: while loop not terminating
You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:
0 ... | Jump game 2 leetcode: while loop not terminating | You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:
0 <= j <= nums[i] and
i + j < n
Return the minimum numbe... | [
"Your while condition is wrong. It will always be true since j is never going to become negative.\nThe meaning of j in your algorithm is the index that must be jumped to from some earlier index. But index 0 must never be jumped to, since we already achieved that index by starting there.\nTo fix this, the while cond... | [
0
] | [] | [] | [
"algorithm",
"dynamic_programming",
"python"
] | stackoverflow_0074452297_algorithm_dynamic_programming_python.txt |
Q:
NameError: class is not defined when overriding a class in python
Why can't python seem to find the InterfaceWithNoMenu class
class Settings(Screen):
class SettingsWithNoMenu(kivy.uix.settings.SettingsWithNoMenu):
def __init__(self, *args, **kwargs):
self.interface... | NameError: class is not defined when overriding a class in python | Why can't python seem to find the InterfaceWithNoMenu class
class Settings(Screen):
class SettingsWithNoMenu(kivy.uix.settings.SettingsWithNoMenu):
def __init__(self, *args, **kwargs):
self.interface_cls = InterfaceWithNoMenu
kivy.uix.settings.Se... | [
"InterfaceWithNoMenu is defined in the namespace of the Settings class, not the global or local namespace. You should be able to do:\nself.interface_cls = Settings.InterfaceWithNoMenu\n\nsince Settings is available in the global namespace.\nNested class definitions are a little awkward IMO and I would usually reco... | [
1,
0
] | [] | [] | [
"kivy",
"nameerror",
"overriding",
"python"
] | stackoverflow_0074452839_kivy_nameerror_overriding_python.txt |
Q:
discord.py AttributeError: 'list' object has no attribute 'commands'
I am trying to do commands to discord.py in other file but when i try to setup them i get error
'Client' object has no attribute 'add_cog'
My main.py file:
import discord
import music
from discord.ext import commands
client = commands.Bot(comman... | discord.py AttributeError: 'list' object has no attribute 'commands' | I am trying to do commands to discord.py in other file but when i try to setup them i get error
'Client' object has no attribute 'add_cog'
My main.py file:
import discord
import music
from discord.ext import commands
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
token = ""
cogs = [music]
@... | [
"following your code, this is an outdated version of cog loading/setting. according to the new Migrations made by python you will need to re-edit your code to move smoothly with the migration.\nasync def setup(client):\n await client.add_cog(commands(client)) \n\nand in your Main.py file, along with your on_read... | [
0,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074437266_discord_discord.py_python.txt |
Q:
Does R have dot notation like Python?
I am currently working on converting, refactoring, and optimizing a code base from R to Python.
The R code base uses the source() function a lot. From my understanding this is similar to importing a python file.
In python I can do the following:
import myFile
myFile.some_fun... | Does R have dot notation like Python? | I am currently working on converting, refactoring, and optimizing a code base from R to Python.
The R code base uses the source() function a lot. From my understanding this is similar to importing a python file.
In python I can do the following:
import myFile
myFile.some_function_or_variable_in_the_file
Seems like yo... | [
"source can import an R script into an environment and then the objects can be accessed by qualification.\nmyfile <- environment()\nsource(\"myfile.R\", myfile)\n\nmyfile$fun(x, y, z) # call fun from myfile passing x, y and z\nls(myfile) # show what was sourced into the myfile environment\n\nAlso look at the sys.s... | [
2,
0
] | [] | [] | [
"python",
"r"
] | stackoverflow_0074452719_python_r.txt |
Q:
QLDB Python driver seems very slow
I am using the Python AWS QLDB Driver to make queries against a QLDB ledger. I've noticed that the total time for results to return is about double what the internal qldb timing statistics says it should be. Just wondering what additional overhead there is or what can be done abo... | QLDB Python driver seems very slow | I am using the Python AWS QLDB Driver to make queries against a QLDB ledger. I've noticed that the total time for results to return is about double what the internal qldb timing statistics says it should be. Just wondering what additional overhead there is or what can be done about this.
Driver setup:
qldb_driver =... | [
"the timing information doesn't include time spent on network calls and other overhead before QLDB frontend server starts the timing on server side. It's only calculating the server time of a single statement that is being executed and commands like StartSession, StartTransaction, CommitTransaction are not included... | [
0
] | [] | [] | [
"amazon_qldb",
"python"
] | stackoverflow_0074367745_amazon_qldb_python.txt |
Q:
Compare two dataframes and retrieve common row elements
I need to compare two datasets:
DF1
Subj 1 2 3
0 Biotech Cell culture Bioinfo Immunology
1 Zoology Cell culture Immunology NaN
2 Math Trigonometry Algebra NaN
3 Microbio B... | Compare two dataframes and retrieve common row elements | I need to compare two datasets:
DF1
Subj 1 2 3
0 Biotech Cell culture Bioinfo Immunology
1 Zoology Cell culture Immunology NaN
2 Math Trigonometry Algebra NaN
3 Microbio Biotech NaN NaN
4 Physics Optics ... | [
"You can match columns and then set the subject column as an index while merging the dataframes:\nmatch=df2.columns.intersection(df1.columns).tolist()\ndf2.merge(df1,on=match, how='left').reindex(df2.columns,axis=1).set_index('Subj').dropna(how='all')\n\n\nwhich returns:\n 1 2\nSubj ... | [
1,
1
] | [] | [] | [
"compare",
"dataframe",
"pandas",
"python",
"row"
] | stackoverflow_0074450386_compare_dataframe_pandas_python_row.txt |
Q:
How could I solve the error of putting a string in the sympy set solver with an input?
So I'm trying to create this program where it takes an input (for example x+2=5) and sympy solves that equation. However since I believe that "=" sign will cause an error I tried to cut it out from the input but with this I'm fi... | How could I solve the error of putting a string in the sympy set solver with an input? | So I'm trying to create this program where it takes an input (for example x+2=5) and sympy solves that equation. However since I believe that "=" sign will cause an error I tried to cut it out from the input but with this I'm finding my self inputting a string type in the simpy solver. Is there any solution to this?
im... | [
"You can use sympify to convert a string to a symbolic expression, although you will have to remove the equal sign first. In the following code, first I split the string where the equal sign is found, then I convert the two resulting strings to symbolic expressions with sympify, finally I solve the equation.\ndef s... | [
1,
0
] | [] | [] | [
"math",
"python",
"sympy"
] | stackoverflow_0074451264_math_python_sympy.txt |
Q:
Can't get pymongo to connect to mongodb in jupyter notebook to run CRUD python file?
I am running into the error that the authentication is not working for my project. I have tried a few different solutions that I found online and it still won't authenticate the user for me. I tried to write it in different ways a... | Can't get pymongo to connect to mongodb in jupyter notebook to run CRUD python file? | I am running into the error that the authentication is not working for my project. I have tried a few different solutions that I found online and it still won't authenticate the user for me. I tried to write it in different ways and found similar issues on stackoverflow that had working solutions but the solutions did ... | [
"self.client = MongoClient('mongodb://localhost:27017/'format.(username, password))\n\nthis alteration fixed my problem\n"
] | [
0
] | [] | [] | [
"jupyter_notebook",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0074449526_jupyter_notebook_mongodb_pymongo_python.txt |
Q:
Requests doesn't work when sending message to discord
I am trying to send a message with python to discord using requests.. Why doesn't this work? Did I do something wrong?
import requests
id = 935325134879850517
r = requests.post(f'http://discord.com/api/v9/channels/{id}/messages', json={'content':'message'}, hea... | Requests doesn't work when sending message to discord | I am trying to send a message with python to discord using requests.. Why doesn't this work? Did I do something wrong?
import requests
id = 935325134879850517
r = requests.post(f'http://discord.com/api/v9/channels/{id}/messages', json={'content':'message'}, headers={'authorization': 'token'})
| [
"Consider using Discord webhooks, I had problem with API too, but webhooks works very simple -- without auth.\n"
] | [
0
] | [] | [] | [
"discord",
"post",
"python",
"python_requests"
] | stackoverflow_0074452749_discord_post_python_python_requests.txt |
Q:
Python, Import config.py
# config.py
white = (255,255,255)
# main.py
import config
print(white)
# output:
Traceback (most recent call last):
File "C:\...\Test\Test2.py", line 2, in <module>
print(white)
NameError: name 'white' is not defined
Process finished with exit code 1
# wanted output
(255, 255, 25... | Python, Import config.py | # config.py
white = (255,255,255)
# main.py
import config
print(white)
# output:
Traceback (most recent call last):
File "C:\...\Test\Test2.py", line 2, in <module>
print(white)
NameError: name 'white' is not defined
Process finished with exit code 1
# wanted output
(255, 255, 255)
Process finished with exi... | [
"Just do:\n# main.py\nfrom config import white\nprint(white)\n\nFor multiple variables:\nfrom config import white, variable_1, variable_2, ...\n\n"
] | [
1
] | [] | [] | [
"python",
"python_import"
] | stackoverflow_0074452890_python_python_import.txt |
Q:
How to merge multiple DataFrames in python
I have a list of Dataframes and Im trying to merge it into a one using the _id column.
List of dataframes(df) looks like
0 thyx07y1bg8 ... 2000-03-31 2004-12-31
1 ofr7s6wf1j ... 2000-03-31 2004-12-31
[2 rows x 4 columns], _id ... calc... | How to merge multiple DataFrames in python | I have a list of Dataframes and Im trying to merge it into a one using the _id column.
List of dataframes(df) looks like
0 thyx07y1bg8 ... 2000-03-31 2004-12-31
1 ofr7s6wf1j ... 2000-03-31 2004-12-31
[2 rows x 4 columns], _id ... calculate_from calculate_to
0 3sw1btgso6t ... ... | [
"This is more like combine_first or concat with drop\nout = pd.concat([df1, df2]).drop_duplicates('id')\n\nOr\nout = df1.set_index('id').combine_first(df2.set_index('id')).reset_index()\n\n"
] | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074452962_pandas_python.txt |
Q:
read public http csv data into Apache Beam
I'm trying to use apache_beam.dataframe.io.read_csv function to read an online source with no success. Everything works if the file is hosted on google storage 'gs://bucket/source.csv' but fails on getting the file from 'https://github.com/../source.csv' like sources..
fr... | read public http csv data into Apache Beam | I'm trying to use apache_beam.dataframe.io.read_csv function to read an online source with no success. Everything works if the file is hosted on google storage 'gs://bucket/source.csv' but fails on getting the file from 'https://github.com/../source.csv' like sources..
from apache_beam.dataframe.io import read_csv
url... | [
"Beam can only read files from filesystems (like gcs, hdfs, etc.) not arbitrary URLs (which are difficult to parallelize reads from). Local files work as well on the direct runner.\nAlternatively, you could do something like\ndef parse_csv(contents):\n [use pandas, the csv module, etc. to parse the contents string... | [
1,
0
] | [] | [] | [
"apache_beam",
"csv",
"pandas",
"python"
] | stackoverflow_0074444185_apache_beam_csv_pandas_python.txt |
Q:
OSError: Starting path not found (dotenv-0.21.0-py3.9.egg)
I'm developing a script in Python 3.9 that works perfectly on my personal PC. When I tried moving and running it on a server, which has an older python version, it gives me the following error:
Does anyone know how to fix this error?
I tried to install do... | OSError: Starting path not found (dotenv-0.21.0-py3.9.egg) | I'm developing a script in Python 3.9 that works perfectly on my personal PC. When I tried moving and running it on a server, which has an older python version, it gives me the following error:
Does anyone know how to fix this error?
I tried to install dotenv via pip manually, but it doesn't work.
| [] | [] | [
"I think you should use Pylaucher, to start Pylaucher you must Use Shebang (#) in The Script Run Pylauncher Command. Then you will be able to run multiple versions of python in Windows without getting errors. There are too many methods you can use; I strongly suggest this one since has once worked for me.\n"
] | [
-1
] | [
"python",
"python_3.x",
"python_dotenv"
] | stackoverflow_0074452912_python_python_3.x_python_dotenv.txt |
Q:
Code successfully running but returning an empty dataframe
I found this code written from a few years ago, I wanted to implement it to scrap data from OpenTable since I am a beginner with web scraping. Here is the code:
from selenium import webdriver
import pandas as pd
from bs4 import BeautifulSoup
from time impo... | Code successfully running but returning an empty dataframe | I found this code written from a few years ago, I wanted to implement it to scrap data from OpenTable since I am a beginner with web scraping. Here is the code:
from selenium import webdriver
import pandas as pd
from bs4 import BeautifulSoup
from time import sleep
import re
def parse_html(html):
data, item = pd.Da... | [
"Wrong Tag or missing tag\nYour code item is empty because the code can not locate the tag you pass in your BeautifulSoup library. Inspect the browser and confirm if the tag is available.\nExample of the tag is:\nsoup.find_all('div', class_='rest-row-info')):\n\n"
] | [
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0074452348_html_python.txt |
Q:
the list in my code is not working properly
import random
def foo():
list_of_odd_num = []
for i in range (1, 10000, 2):
list_of_odd_num.append(i)
return list_of_odd_num
def bar():
list_of_uppercase_letters = []
for k in range(1, 100):
rand_num = random.randint(65, 90)
... | the list in my code is not working properly | import random
def foo():
list_of_odd_num = []
for i in range (1, 10000, 2):
list_of_odd_num.append(i)
return list_of_odd_num
def bar():
list_of_uppercase_letters = []
for k in range(1, 100):
rand_num = random.randint(65, 90)
letter = chr(rand_num)
k = list_of_upp... | [
"The inner loop does not break when a value is added, thus, it may add multiple ? to the list before checking the outer loop condition (resulting in too many ?).\nYou could fix the code like this:\nimport random\n\ndef foo():\n list_of_odd_num = []\n for i in range (1, 10000, 2):\n list_of_odd_num.appe... | [
0,
0,
0
] | [] | [] | [
"for_loop",
"list",
"python",
"random",
"while_loop"
] | stackoverflow_0074452982_for_loop_list_python_random_while_loop.txt |
Q:
What is the fastest way to serialize a DataFrame besides to_pickle?
I need to serialize DataFrames and send them over the wire. For security reasons, I cannot use pickle.
What would be the next fastest way to do this? I was intrigued by msgpacks in v0.13, but unless I'm doing something wrong, the performance see... | What is the fastest way to serialize a DataFrame besides to_pickle? | I need to serialize DataFrames and send them over the wire. For security reasons, I cannot use pickle.
What would be the next fastest way to do this? I was intrigued by msgpacks in v0.13, but unless I'm doing something wrong, the performance seems much worse than with pickle.
In [107]: from pandas.io.packers import p... | [
"This is now pretty competetive with this PR: https://github.com/pydata/pandas/pull/5498 (going to merge for 0.13 shortly)\nIn [1]: from pandas.io.packers import pack\n\nIn [2]: import cPickle as pkl\n\nIn [3]: df = pd.DataFrame(np.random.rand(1000, 100))\n\nAbove example\nIn [6]: %timeit buf = pack(df)\n1000 loops... | [
7,
0
] | [] | [] | [
"numpy",
"pandas",
"pickle",
"python",
"serialization"
] | stackoverflow_0019914508_numpy_pandas_pickle_python_serialization.txt |
Q:
Divide Array in subarrays by local peaks
Hey there i have an numpy array y with over 4000 values.
data=pd.read_csv('samplesdata.csv',sep=";", decimal=",",encoding='latin-1')
sensor_data=data[['Euklidische Norm']]
sensor_data = np.array(sensor_data).ravel()
sensor_data = sensor_data - np.average(sensor_data)
# F... | Divide Array in subarrays by local peaks | Hey there i have an numpy array y with over 4000 values.
data=pd.read_csv('samplesdata.csv',sep=";", decimal=",",encoding='latin-1')
sensor_data=data[['Euklidische Norm']]
sensor_data = np.array(sensor_data).ravel()
sensor_data = sensor_data - np.average(sensor_data)
# Filter requirements.
order = 2
fs = 100 # samp... | [
"You can try the code below to subdivise your y array according to the intervals given by your heights (note that your heights array needs to be sorted)\nimport numpy as np\n\nheights = np.array([0,4,8,12,20,30])\n\ny = np.array([1,25,30,7,12])\n\ndef subdivise(arr,heights):\n # np.digitize will assign each item... | [
0
] | [] | [] | [
"arrays",
"jupyter_notebook",
"numpy",
"python",
"sub_array"
] | stackoverflow_0074451289_arrays_jupyter_notebook_numpy_python_sub_array.txt |
Q:
Pandas: Get first and last row of the same date and calculate time difference
I have a dataframe where I have a date and a time column.
Each row describes some event. I want to calculate the timespan for each different day and add it as new row. The actual calculation is not that important (which units etc.), I ju... | Pandas: Get first and last row of the same date and calculate time difference | I have a dataframe where I have a date and a time column.
Each row describes some event. I want to calculate the timespan for each different day and add it as new row. The actual calculation is not that important (which units etc.), I just want to know, how I can the first and last row for each date, to access the time... | [
"I hope you will find this helpful.\nimport pandas as pd\n\ndf = pd.DataFrame({\"Date\": [\"01.01.2020\", \"01.01.2020\", \"01.01.2020\", \"02.02.2022\", \"02.02.2022\"],\n \"Time\": [\"12:00\", \"13:00\", \"14:45\", \"02:00\", \"08:00\"]})\n\ndf[\"Datetime\"] = pd.to_datetime((df[\"Date\"] + \" \... | [
1,
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074452582_dataframe_pandas_python.txt |
Q:
Count input length without spaces, periods, or commas, can someone help here?
enter image description hereGiven a line of text as input, output the number of characters excluding spaces, periods, or commas.
Ex: If the input is: Listen, Mr. Jones, calm down. the output is: 21
Note: Account for all characters that... | Count input length without spaces, periods, or commas, can someone help here? | enter image description hereGiven a line of text as input, output the number of characters excluding spaces, periods, or commas.
Ex: If the input is: Listen, Mr. Jones, calm down. the output is: 21
Note: Account for all characters that aren't spaces, periods, or commas (Ex: "r", "2", "!").
I don't know what I am doin... | [
"In the most simple terms all you have to do is create a character filter, and sum all the characters that are not in the filter. sum is used because using len would also require a join and a condition. We can save some processing by not trying to reformat the string.\nf = ' .,' #character filter\n\nlength = sum... | [
1
] | [
"Does this help?\nprint(len(string.replace(',','').replace(' ','').replace('.','')))\n\nWhere string is your input string.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074439442_python.txt |
Q:
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers)
I tried to run the graph cut algorithm for a slice of an MRI after converting it into PNG format. I keep encountering the following problem:
Clipping input data to the valid range for imshow with RGB data (... | Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers) | I tried to run the graph cut algorithm for a slice of an MRI after converting it into PNG format. I keep encountering the following problem:
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
This is even after setting vmin and vmax as follows:
plt.imshow(out,... | [
"Cast the image to np.uint8 after scaling [0, 255] range will dismiss this warning. It seems like a feature in matplotlib, as discussed in this issue.\nplt.imshow((out * 255).astype(np.uint8))\n\n",
"Instead of plt.imshow(out), use plt.imshow(out.astype('uint8')). That's it!\n",
"If you want to show it, you can... | [
69,
30,
17,
10,
1,
0,
0,
0,
0
] | [] | [] | [
"matplotlib",
"normalization",
"python"
] | stackoverflow_0049643907_matplotlib_normalization_python.txt |
Q:
Selenium, issue getting ID of a generic tag and clicking
Issue: I cannot get a clickable variable that points the chosen anime title. The title is an tag that has a tag that contains the anime name.
What I want to do is:
1)Get all anime that appear from the website
2)Select the anime that has the same name as th... | Selenium, issue getting ID of a generic tag and clicking | Issue: I cannot get a clickable variable that points the chosen anime title. The title is an tag that has a tag that contains the anime name.
What I want to do is:
1)Get all anime that appear from the website
2)Select the anime that has the same name as the input variable "b"
3)Get the chosen anime title clickable to... | [
"Your code is not working because driver.find_elements() returns a list, even if it only finds one element. You are probably getting an error like: 'list' object has no attribute 'Click'\nI think an easier way would be to find the element whose text matches your input string. The driver.find_element_by_xpath() meth... | [
0,
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074452655_python_selenium_web_scraping.txt |
Q:
How does Python Pandas Transform work internally when passed a lambda question?
I found the following example online which explains how to essentially achieve a SQL equivalent of PARTITION BY
df['percent_of_points'] = df.groupby('team')['points'].transform(lambda x: x/x.sum())
#view updated DataFrame
print(df)
... | How does Python Pandas Transform work internally when passed a lambda question? | I found the following example online which explains how to essentially achieve a SQL equivalent of PARTITION BY
df['percent_of_points'] = df.groupby('team')['points'].transform(lambda x: x/x.sum())
#view updated DataFrame
print(df)
team points percent_of_points
0 A 30 0.352941
1 A 22 ... | [
"\nit appears to refer to an individual element when used as the\nnumerator i.e. 'x' but also appears to be a list of values when used\nas a denominator i.e. x.sum()\n\nIt doesn't, it returns a pd.Series of length the size of the group, and x / x.sum() is not a single value, it a pd.Series of the same size.\n.trans... | [
0
] | [] | [] | [
"dataframe",
"group_by",
"numpy",
"pandas",
"python"
] | stackoverflow_0074453184_dataframe_group_by_numpy_pandas_python.txt |
Q:
Select rows in pandas MultiIndex DataFrame
What are the most common pandas ways to select/filter rows of a dataframe whose index is a MultiIndex?
Slicing based on a single value/label
Slicing based on multiple labels from one or more levels
Filtering on boolean conditions and expressions
Which methods are applica... | Select rows in pandas MultiIndex DataFrame | What are the most common pandas ways to select/filter rows of a dataframe whose index is a MultiIndex?
Slicing based on a single value/label
Slicing based on multiple labels from one or more levels
Filtering on boolean conditions and expressions
Which methods are applicable in what circumstances
Assumptions for simpl... | [
"MultiIndex / Advanced Indexing\n\nNote\nThis post will be structured in the following manner:\n\nThe questions put forth in the OP will be addressed, one by one\nFor each question, one or more methods applicable to solving this problem and getting the expected result will be demonstrated.\n\nNotes (much like this ... | [
337,
19,
1,
1,
0
] | [] | [] | [
"dataframe",
"multi_index",
"pandas",
"python",
"slice"
] | stackoverflow_0053927460_dataframe_multi_index_pandas_python_slice.txt |
Q:
How to check if request post has been successfully posted?
I'm using the python requests module to handle requests on a particular website i'm crawling. I'm fairly new to HTTP requests, but I do understand the basics. Here's the situation. There's a form I want to submit and I do that by using the post method from... | How to check if request post has been successfully posted? |
I'm using the python requests module to handle requests on a particular website i'm crawling. I'm fairly new to HTTP requests, but I do understand the basics. Here's the situation. There's a form I want to submit and I do that by using the post method from the requests module:
# I create a session
Session = requests.S... | [
"If you pick up the result from when you post you can then check the status code:\nresult = Session.post(SubmitURL, data=PostData)\nif result.status_code == requests.codes.ok:\n # All went well...\n\n",
"I am a Python newbie but I think the easiest way is:\nif response.ok:\n # whatever\n\nbecause all 2XX co... | [
8,
6,
0,
0
] | [] | [] | [
"http",
"module",
"python",
"python_requests"
] | stackoverflow_0043071816_http_module_python_python_requests.txt |
Q:
Combination of map() and filter()
I just had an idea that I find pretty intriguing: A combination between map() and filter() using generator as predicate and yield from. To make it short, here's the code:
def map_filter(function, iterable):
"""convert and filter a sequence"""
for i in iterable:
yie... | Combination of map() and filter() | I just had an idea that I find pretty intriguing: A combination between map() and filter() using generator as predicate and yield from. To make it short, here's the code:
def map_filter(function, iterable):
"""convert and filter a sequence"""
for i in iterable:
yield from function(i)
Now, what's the de... | [
"You can define generator expressions:\n>>> values = range(0, 10)\n>>> evens = (value for value in values if not value % 2)\n>>> even_squares = (even * even for even in evens)\n>>> list(even_squares)\n[0, 4, 16, 36, 64]\n\n",
"Use list comprehensions with conditional instead. For example:\nsquared_evens = [n*n fo... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0034234222_python.txt |
Q:
Get consumer group state using confluent kafka python
I am doing this way currently to get the groupmetadata for list of consumers
admin = AdminClient({ 'bootstrap.servers' : config['kafka']['brokers'] })
for group in config['kafka']['groups']:
metadata = admin.list_groups(group)
print(metadata[0].sta... | Get consumer group state using confluent kafka python | I am doing this way currently to get the groupmetadata for list of consumers
admin = AdminClient({ 'bootstrap.servers' : config['kafka']['brokers'] })
for group in config['kafka']['groups']:
metadata = admin.list_groups(group)
print(metadata[0].state)
Is there a way to achieve the below
metadata = admin.l... | [
"The docs say group param is only str, not list(str)\nIf you don't provide it, it will return all groups, which you could then choose to filter, based on your config.\n"
] | [
0
] | [] | [] | [
"apache_kafka",
"confluent_kafka_python",
"python"
] | stackoverflow_0074450168_apache_kafka_confluent_kafka_python_python.txt |
Q:
How to curve_fit a function that return dataFrame on a data set
I am trying to curve fit my defined function to a dataset. I defined my function using pandas and it prints the values. But when I try to optimize it using Curve_fit, it gives me an error that "list index out of range". I don't understand why?
import ... | How to curve_fit a function that return dataFrame on a data set | I am trying to curve fit my defined function to a dataset. I defined my function using pandas and it prints the values. But when I try to optimize it using Curve_fit, it gives me an error that "list index out of range". I don't understand why?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
ydata... | [
"The message \"list index out of range\" means exactly what it says: you are trying to access a list element that doesn't exist. In this case it's caused because ta1 can be an empty list, and you are trying to access the 0th element here dfy.iloc[:ta1[0],1] = a\nNow why would ta1 be empty? The offending statement i... | [
0
] | [] | [] | [
"curve_fitting",
"pandas",
"python"
] | stackoverflow_0074451817_curve_fitting_pandas_python.txt |
Q:
python automatically add variable to a list
i want to create a basic animation in python just with print() with multiple variable with all a name just like that: frame0, frame1, frame2,... I can copy paste the frame, but i want to add their on a list called frames.
That's my code:
frame0 = "D"
frame1 = "CD"
frame2... | python automatically add variable to a list | i want to create a basic animation in python just with print() with multiple variable with all a name just like that: frame0, frame1, frame2,... I can copy paste the frame, but i want to add their on a list called frames.
That's my code:
frame0 = "D"
frame1 = "CD"
frame2 = "BCD"
frame3 = "ABCD"
frames = []
for i in ra... | [
"If the variables frame{..} are global variables, you can do this\nframe0 = \"D\"\nframe1 = \"CD\"\nframe2 = \"BCD\"\nframe3 = \"ABCD\"\n\nframes = []\nfor i in range(4):\n frames.append(locals()[f'frame{i}'])\n\nNote if the variables are global and not local, then you can use globals()[f'frame{i}'] instead\... | [
0
] | [] | [] | [
"append",
"list",
"python",
"python_3.11",
"variables"
] | stackoverflow_0074453309_append_list_python_python_3.11_variables.txt |
Q:
Map numerical values in one column to categorical values in another column in pandas
I have a dataframe with numerical values
score
16.0
49.0
55.0
65.0
77.0
89.0
98.0
I want to create another column in the same dataframe with categorical values based on the numerical values.
score
names
16.0
low
49.0
l... | Map numerical values in one column to categorical values in another column in pandas | I have a dataframe with numerical values
score
16.0
49.0
55.0
65.0
77.0
89.0
98.0
I want to create another column in the same dataframe with categorical values based on the numerical values.
score
names
16.0
low
49.0
low
55.0
low
65.0
avg
77.0
avg
89.0
high
98.0
very high
| [
"scores = df['score'].tolist()\nnames = []\nfor i in range(len(scores)):\n if scores[i] < 60.0:\n names.append('low')\n elif scores[i] < 80.0:\n names.append('avg')\n elif scores[i] < 90.0:\n names.append('high')\n else:\n names.append('very high')\ndf['names'] = names\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"mapping",
"pandas",
"python"
] | stackoverflow_0074453324_dataframe_mapping_pandas_python.txt |
Q:
Read files from s3 bucket that match a pattern in python
I am reading a file from s3 in pandas.
aws_credentials = {
"key": "xxxx",
"secret": "xxxx"
}
# Read data from S3
df_aln = pd.read_csv("s3://dir/ABC/fname_0521.csv", storage_options=aws_credential... | Read files from s3 bucket that match a pattern in python | I am reading a file from s3 in pandas.
aws_credentials = {
"key": "xxxx",
"secret": "xxxx"
}
# Read data from S3
df_aln = pd.read_csv("s3://dir/ABC/fname_0521.csv", storage_options=aws_credentials, encoding='latin-1')
However, I have several files with sam... | [
"According to this answer: https://stackoverflow.com/a/69568591/687896 , you can use glob on S3. Your pattern would be something like fname_*.csv:\n# get the list of CSV files (from cited answer):\nimport s3fs\ns3 = s3fs.S3FileSystem(anon=False)\ncsvs = s3.glob('your/s3/path/to/fname*.csv')\n\n# read them into pand... | [
1
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"python"
] | stackoverflow_0074453237_amazon_s3_amazon_web_services_python.txt |
Q:
When is it possible to assign to a function call in Python?
In C++, you sometimes have a situation where assigning to a function call makes sense--my understanding is that this is permissible when the function call returns an lvalue. So you might have:
some_function() = some_value;
In Python, it's not quite the s... | When is it possible to assign to a function call in Python? | In C++, you sometimes have a situation where assigning to a function call makes sense--my understanding is that this is permissible when the function call returns an lvalue. So you might have:
some_function() = some_value;
In Python, it's not quite the same. Based on my understanding of the language, I would assume th... | [
"You can't assign to a function call. It's just a confusing error message.\nThe error message comes from a general rule for generating syntax errors for invalid assignments:\ninvalid_named_expression(memo):\n | a=expression ':=' expression {\n RAISE_SYNTAX_ERROR_KNOWN_LOCATION(\n a, \"cannot us... | [
4
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0074453371_python_syntax.txt |
Q:
Python: Add subelement to an element based on value of a sibling subelement?
Lots of python XML parsing tutorials out there, but not that many on updating XML, and none I can find that match my needs. Sorry for the N00B.
I have a need to add subelements to a particular element based on the value of another subele... | Python: Add subelement to an element based on value of a sibling subelement? | Lots of python XML parsing tutorials out there, but not that many on updating XML, and none I can find that match my needs. Sorry for the N00B.
I have a need to add subelements to a particular element based on the value of another subelement.
<CadData>
<FireIncidentCollection>
<FireIncident>
<Inciden... | [
"The first step would be to put this information into a dictionary - then it will be much easier to update your data\nI'd recommend using xmltodict library with a mixture of this tutorial - which will allow you to convert to a dictionary that you can traverse.\nFrom there, just traverse down the dictionary. The nic... | [
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0074452907_python_xml.txt |
Q:
Unable to read json file and print output
user = {}
max_length = 4
while len(user) < max_length:
name = input("What is your name? ")
food= input("What is your favourite food? ")
user[name]= food
users = json.dumps(user)
if name.lower() == 'q' or food.lower()== 'q':
break
with open('users.json'... | Unable to read json file and print output | user = {}
max_length = 4
while len(user) < max_length:
name = input("What is your name? ")
food= input("What is your favourite food? ")
user[name]= food
users = json.dumps(user)
if name.lower() == 'q' or food.lower()== 'q':
break
with open('users.json', 'a') as outfile:
outfile.write(f"{users.t... | [
"The main problem is that you are adding data to a JSON file in a non-JSON format. To keep this consistent, I recommend using json.dump for placing the data in the file too.\nEdit: when you define the first user, store the data as a dictionary, but inside an array. That way, you can append to it later on. Still, yo... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074453392_python.txt |
Q:
discord.py invites - approximate_presence_count API gradually becomes slower
TL/DR: I'm querying an invite link's approximate_presence_count every 10 seconds, and it gradually stops detecting presence changes over a very long period. How can I fix this?
Goal
I'm writing a discord bot which monitors the number of ... | discord.py invites - approximate_presence_count API gradually becomes slower | TL/DR: I'm querying an invite link's approximate_presence_count every 10 seconds, and it gradually stops detecting presence changes over a very long period. How can I fix this?
Goal
I'm writing a discord bot which monitors the number of online (and other statuses) members in several large (>100 members) servers I'm a ... | [
"This is most likely an issue on Discord's end as suggested in the comments. They have changed how their invites work. This includes how permanent invite links work. While the article doesn't state the internal changes, it does state how the new invites work on the actual app/site. The time of change to the invites... | [
1
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0072596371_bots_discord_discord.py_python.txt |
Q:
Python problem - Editing value in dictionary inside two dimensional list edits the whole matrix instead of only one item
I have a matrix (two-dimensional list) filled with dictionary-type variable in the entire scope containing "val": False
The problem is when I want to change only one item in the matrix and chanh... | Python problem - Editing value in dictionary inside two dimensional list edits the whole matrix instead of only one item | I have a matrix (two-dimensional list) filled with dictionary-type variable in the entire scope containing "val": False
The problem is when I want to change only one item in the matrix and chanhge the value to True for this one paticular item.
Somehow this part of code: matrix[3][2]["val"] = True causes the entire matr... | [
"This behavior arises due to variables in python being passed by reference rather than by value. For example:\nsome_dict = {'foo': 'bar'}\nother_dict = some_dict # actually references the same object as some_dict\nother_dict['foo'] = 'buzz' # update applies to the dictionary object being referenced\nprint(other_dic... | [
2,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074453306_dictionary_list_python.txt |
Q:
Python: Iteration Practice looking to break out of two loops
I am having some issues with loops, In general my question is how to break out of two loops. Line 60 is what I am referencing to, When I complete the code with valid values and then select yes to add another persons values it asks for weight first instea... | Python: Iteration Practice looking to break out of two loops | I am having some issues with loops, In general my question is how to break out of two loops. Line 60 is what I am referencing to, When I complete the code with valid values and then select yes to add another persons values it asks for weight first instead of height.
UPDATE: I am a self taught programmer with a very bas... | [
"A suggestion would be to use a function and to just return\nfor i in range(10):\n for j in range(10):\n if condition: return\n``\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074453416_python.txt |
Q:
delete an element of a tuple within a list [Python, Tuples, Lists] (SOLVED)
I am creating a menu for a billing program with tuples inside lists, how would you do to delete a data requested by the user deleting all its values?
menu = """
(1) Añadir Cliente
(2) Eliminar Cliente
(3) Añadir Factura
(4) Procesar factur... | delete an element of a tuple within a list [Python, Tuples, Lists] (SOLVED) | I am creating a menu for a billing program with tuples inside lists, how would you do to delete a data requested by the user deleting all its values?
menu = """
(1) Añadir Cliente
(2) Eliminar Cliente
(3) Añadir Factura
(4) Procesar facturacion del mes
(5) Listar todos los clientes
(6) Terminar
"""
lista_nom =[]
list_b... | [
"Instead of deleting an element, what is not possible inside of tuples, you could define a new tuple by doing\nnom_remove = lista_nom[:nom] + lista_nom[(nom+1):]\n\n",
"At the end I resolved the problem with this, like the other guy tell me the tuples are immutable so I need to go inside the list and i can access... | [
1,
0
] | [] | [] | [
"del",
"for_loop",
"list",
"python",
"tuples"
] | stackoverflow_0074453047_del_for_loop_list_python_tuples.txt |
Q:
How to turn multiple rows of dictionaries from a file into a dataframe
I have a script that I use to fire orders from a csv file, to an exchange using a for loop.
data = pd.read_csv('orderparameters.csv')
df = pd.DataFrame(data)
for i in range(len(df)):
order = Client.new_order(...
...)
file = open('o... | How to turn multiple rows of dictionaries from a file into a dataframe | I have a script that I use to fire orders from a csv file, to an exchange using a for loop.
data = pd.read_csv('orderparameters.csv')
df = pd.DataFrame(data)
for i in range(len(df)):
order = Client.new_order(...
...)
file = open('orderData.txt', 'a')
original_stdout = sys.stdout
with file as f:
... | [
"If I understand your question correctly, you can simply do the following:\nimport pandas as pd\n\norders = pd.read_csv('orderparameters.csv')\nresponses = pd.DataFrame(Client.new_order(...) for _ in range(len(orders)))\n\n",
"It looks like you are getting json strings back, you could read json objects into dicti... | [
0,
0
] | [] | [] | [
"binance",
"pandas",
"python"
] | stackoverflow_0074447371_binance_pandas_python.txt |
Q:
Running gunicorn for HTTPS by using a public certificate
I need to run a flask HTTPS API application by using either Gunicorn or uWSGI. I have acquired a public certificate from AWS (ACM or AWS Certificate Manager) so It doesn't have any chain certificate files. Based on the gunicorn documents to run an HHTPS appl... | Running gunicorn for HTTPS by using a public certificate | I need to run a flask HTTPS API application by using either Gunicorn or uWSGI. I have acquired a public certificate from AWS (ACM or AWS Certificate Manager) so It doesn't have any chain certificate files. Based on the gunicorn documents to run an HHTPS application, the syntax is like below
gunicorn --certfile=server.... | [
"\nCan I run gunicron with such a public certifcate?\n\nNo. Certificates from ACM can't be exported and you can't use them with gunicron. You have to get valid certificates from an external party, such as https://letsencrypt.org/.\n"
] | [
0
] | [] | [] | [
"amazon_web_services",
"aws_certificate_manager",
"gunicorn",
"python",
"uwsgi"
] | stackoverflow_0074453464_amazon_web_services_aws_certificate_manager_gunicorn_python_uwsgi.txt |
Q:
2 Python nested Dictionaries, current data in one the other will fill with the data from the previous minute displays. I need to diff int data
I'm really new to Python so I hope this makes sense.
These are a sample of 2 dictionaries. What I cannot work out is how to subtract the current entries from the previous e... | 2 Python nested Dictionaries, current data in one the other will fill with the data from the previous minute displays. I need to diff int data | I'm really new to Python so I hope this makes sense.
These are a sample of 2 dictionaries. What I cannot work out is how to subtract the current entries from the previous entries where the nested dictionary ie "Name2" matches in the previous dictionary.
Also I cannot introduce or use extra libraries.
previous = {}
c =... | [
"The calcDiff() function seems to be incorrect. I tried running your code but couldn't get your expected output. Hence I modified your code as follows:\ncurrent = {'Name2': {'Date': '07Nov2022', 'Name': 'Name2', 'Type': 'stats', 'Time': '12.49.09', 'C_001': 20742, 'C_002': 20415, 'P_002': '98.4', 'C_003': 327, 'P_... | [
1,
1
] | [] | [] | [
"dictionary",
"nested",
"python",
"python_3.x"
] | stackoverflow_0074370871_dictionary_nested_python_python_3.x.txt |
Q:
What is the purpose of the .enfold() method in the context of Datetime objects and timezones?
I am continuing to practice on Data Camp and the current session covers Datetimes, timezone, dateutil, etc. However, there is a function I am not sure about. The function mentioned in the below code is .enfold() and I can... | What is the purpose of the .enfold() method in the context of Datetime objects and timezones? | I am continuing to practice on Data Camp and the current session covers Datetimes, timezone, dateutil, etc. However, there is a function I am not sure about. The function mentioned in the below code is .enfold() and I cannot seem to locate an easy explanation in the documentation. What is its general purpose and what i... | [
"I am assuming that enfold in your code is the function from the tz module in the third-party timezone package: https://dateutil.readthedocs.io/en/stable/tz.html#dateutil.tz.enfold\nAs the documentation mentions, \"fold\" is an attribute of datetime objects whose implementation was changed in Python 3.6 by PEP 495.... | [
0
] | [] | [] | [
"datetime",
"python",
"python_dateutil",
"timezone"
] | stackoverflow_0074453259_datetime_python_python_dateutil_timezone.txt |
Q:
Why does my asyncio event loop die when I kill a forked subprocess (PTY)?
I try to create a software that spawns bash shells and makes them controllable via websockets.
It's based on fastapi and fastapi_socketio on the server side and socket.io + JS on the client side.
Gotta admit that I am an absolute noob when i... | Why does my asyncio event loop die when I kill a forked subprocess (PTY)? | I try to create a software that spawns bash shells and makes them controllable via websockets.
It's based on fastapi and fastapi_socketio on the server side and socket.io + JS on the client side.
Gotta admit that I am an absolute noob when it comes down to asyncio. I can use it when I control it by myself but I am not ... | [
"I luckily got the problem fixed by invoking os.execvpe() instead of using subprocess.run(). This approach replaces the child process with a completely new process while staying connected to the file descriptor the parent process is able to read.\nI didn't really know the consequences of using fork() in the child w... | [
0
] | [] | [] | [
"fastapi",
"pty",
"python",
"python_asyncio",
"subprocess"
] | stackoverflow_0074452176_fastapi_pty_python_python_asyncio_subprocess.txt |
Q:
How to append items to various lists without iterating from the beginning?
I am trying to fill my variable 'test' with items from 'mylist'. If the condition totaltime < 6 is met, the iteration starts over at mylist[0], so the lists never get beyond '3' (2nd indice in mylist). However, I want that if the condition ... | How to append items to various lists without iterating from the beginning? | I am trying to fill my variable 'test' with items from 'mylist'. If the condition totaltime < 6 is met, the iteration starts over at mylist[0], so the lists never get beyond '3' (2nd indice in mylist). However, I want that if the condition is met, then the iteration will continue filling the second list. How can I ensu... | [
"The problem is that you are nesting the looping. I think the easiest way is just to loop over once and keep an index into test which you can increment when you need to. The following works:\nmylist = [1, 2, 3, 4, 5, 6, 7, 8]\ntime = [2, 2, 2, 5, 1, 6, 5, 1]\n\n\ntotal_time = 0\ni = 0\ntest = [[], [], [], []]\nfor ... | [
0,
0
] | [] | [] | [
"nested_for_loop",
"python"
] | stackoverflow_0074452882_nested_for_loop_python.txt |
Q:
Getting code from a .txt on a website and pasting it in a tempfile PYTHON
I was trying to make a script that gets a .txt from a websites, pastes the code into a python executable temp file but its not working. Here is the code:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
imp... | Getting code from a .txt on a website and pasting it in a tempfile PYTHON | I was trying to make a script that gets a .txt from a websites, pastes the code into a python executable temp file but its not working. Here is the code:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
import tempfile
filename = urlopen("https://randomsiteeeee.000webhostapp.com/scri... | [
"you are missing a read:\nfrom urllib.request import urlopen as urlopen\nimport os\nimport subprocess\nimport os\nimport tempfile\n\nfilename = urlopen(\"https://randomsiteeeee.000webhostapp.com/script.txt\").read() # <-- here\ntemp = open(filename)\ntemp.close()\n # Clean up the temporary file yourself\nos.remo... | [
2,
0
] | [] | [] | [
"python",
"request",
"temporary_files"
] | stackoverflow_0074453534_python_request_temporary_files.txt |
Q:
How to save file with pickles and usual characters?
I needed to save a list that contained strings and integers and that was easy to access the elements in another notebook (like for example through data[i]).
I saved the list
data = ["eos", 5, 10, 20]
with pickles:
with open(path + '/data.txt', 'wb') as f:
pic... | How to save file with pickles and usual characters? | I needed to save a list that contained strings and integers and that was easy to access the elements in another notebook (like for example through data[i]).
I saved the list
data = ["eos", 5, 10, 20]
with pickles:
with open(path + '/data.txt', 'wb') as f:
pickle.dump(data, f)
However, it is important that I can re... | [
"Pickle is Python-specific, and it also changes over time as improvements are made. If you want to be able to read the file with other programs, you should choose another format.\nIf your data is a table, which is what your example loosely implies, I would suggest CSV (comma-separated values) because it can be open... | [
0
] | [] | [] | [
"database",
"pickle",
"python"
] | stackoverflow_0074453458_database_pickle_python.txt |
Q:
Process finished with exit code 0 python
I'm new to python. I have this code. I need to get a result as a json from postoffices, but it only tells that I don't have problems in my code like "Process finished with exit code 0". When I'm trying to print(get_settlement_postoffices()), it gives me the same answer.
fro... | Process finished with exit code 0 python | I'm new to python. I have this code. I need to get a result as a json from postoffices, but it only tells that I don't have problems in my code like "Process finished with exit code 0". When I'm trying to print(get_settlement_postoffices()), it gives me the same answer.
from __future__ import annotations
from datetime... | [
"You should create an instance of this class and call its method, like this:\nmyinstance = Services()\nprint(myinstance.get_settlement_postoffices())\n\nThe exit code of 0 means that the process has been executed and exited successfully.\n",
"Are you creating an instance of that class, before calling the function... | [
0,
0,
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074453563_arrays_python.txt |
Q:
Python Selective Copy Homework Assistance
Selective Copy:
Write a program that walks through a folder tree and searches for
files with a certain file extension (such as .pdf or .jpg). Copy these
files from whatever location they are into a new folder.
I keep getting a traceback error as seen in this screenshot.
I... | Python Selective Copy Homework Assistance |
Selective Copy:
Write a program that walks through a folder tree and searches for
files with a certain file extension (such as .pdf or .jpg). Copy these
files from whatever location they are into a new folder.
I keep getting a traceback error as seen in this screenshot.
I do not know what I am doing wrong.
This is th... | [] | [] | [
"Instead of os.mkdir(), I would suggest looking at os.makedirs() (documentation). It has a parameter that I believe you'll find useful for this situation.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074453573_python.txt |
Q:
send_with_components() got an unexpected keyword argument 'ephemeral'
m = await interaction.channel.send(f'<@{interaction.author.id}>',embed=embed, components=[Button(label='News', custom_id="button-give-news", style=ButtonStyle.grey),Button(label='Media', custom_id="button-give-media", style=ButtonStyle.red)], ep... | send_with_components() got an unexpected keyword argument 'ephemeral' | m = await interaction.channel.send(f'<@{interaction.author.id}>',embed=embed, components=[Button(label='News', custom_id="button-give-news", style=ButtonStyle.grey),Button(label='Media', custom_id="button-give-media", style=ButtonStyle.red)], ephemeral=True)
I tryed to send ephemeral message with Buttons, but Python s... | [
"For a message to be ephemeral, it has to directly reply to the user. If you're sending into a specific channel, that means it's not directly replying to the user. To get around this, you can just switch interaction.channel.send to interaction.response.send_message()\nUnfortunately, that means that what you're goin... | [
1
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074445672_discord.py_python.txt |
Q:
Some turtle functions not working on new turtle
So i have created a new turtle by doing bassel = turtle.Turtle(), however, some functions such as tracer() and onkeypress() just don't work, I get an error saying 'Turtle' object has no attribute 'tracer' or 'Turtle' object has no attribute 'onkeypress'...
But as soo... | Some turtle functions not working on new turtle | So i have created a new turtle by doing bassel = turtle.Turtle(), however, some functions such as tracer() and onkeypress() just don't work, I get an error saying 'Turtle' object has no attribute 'tracer' or 'Turtle' object has no attribute 'onkeypress'...
But as soon as I replace bassel by turtle it works
So for insta... | [
"Right. Those functions are not attributes of a SPECIFIC turtle object, they are services offered by the turtle module. Just use turtle.tracer and turtle.onkeypress.\n"
] | [
2
] | [] | [] | [
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074453602_python_python_turtle_turtle_graphics.txt |
Q:
Adding rows with value '0' in txt file to make total no. of rows divisible by 3
I'm trying to add new rows with value '0' in my txt file to make total no of rows divisible by 3, here is the code:
import pandas as pd
# read text file into pandas DataFrame
def process():
df = pd.read_csv("./calibration.txt", se... | Adding rows with value '0' in txt file to make total no. of rows divisible by 3 | I'm trying to add new rows with value '0' in my txt file to make total no of rows divisible by 3, here is the code:
import pandas as pd
# read text file into pandas DataFrame
def process():
df = pd.read_csv("./calibration.txt", sep=' ', header=None)
if len(df)%3!=0:
print("add zero in the last")
... | [
"Try something like\nimport numpy as np\nimport pandas as pd\n\n# extracted as config var; allows for changing dataframe width in one location\nWIDTH = 3\n\ndef process(path):\n df = pd.read_csv(path, sep=' ', header=None)\n vals = df.iloc[:,0].values\n remainder = len(vals) % WIDTH\n \n # pad with n... | [
0
] | [] | [] | [
"dataframe",
"newrow",
"pandas",
"python",
"txt"
] | stackoverflow_0074450298_dataframe_newrow_pandas_python_txt.txt |
Q:
Is there a way to run a T-SQL script using pyodbc in Python?
I could not find a way to run a T-SQL Script using pyodbc without having to change the script content.
Here's the simple SQL script file I'm trying to run:
SET NOCOUNT ON
USE db_test
GO
CREATE OR ALTER FUNCTION usf_test()
RETURNS NVARCHAR(10)
BEGIN
... | Is there a way to run a T-SQL script using pyodbc in Python? | I could not find a way to run a T-SQL Script using pyodbc without having to change the script content.
Here's the simple SQL script file I'm trying to run:
SET NOCOUNT ON
USE db_test
GO
CREATE OR ALTER FUNCTION usf_test()
RETURNS NVARCHAR(10)
BEGIN
DECLARE @var NVARCHAR(10)
SELECT @var = 'TEST'
RETURN @... | [
"As mentioned in the comment session \"The GO keyword is not standard T-SQL, it's something that's specific to SQL Server Management Studio (the management client, not the underlying SQL Server database server/s) and sqlcmd for separating batches.\"\nI really wanted my app not to change the file logic and just run ... | [
0
] | [
"Establish a Connection:\ncnxn_str = (\"Driver={SQL Server Native Client 11.0};\"\n \"Server=USXXX00345,67800;\"\n \"Database=DB02;\"\n \"Trusted_Connection=yes;\")\ncnxn = pyodbc.connect(cnxn_str)\n\nor\ncnxn_str = (\"Driver={SQL Server Native Client 11.0};\"\n \"Server=... | [
-1
] | [
"python",
"sql",
"sql_server"
] | stackoverflow_0074438283_python_sql_sql_server.txt |
Q:
Left Rotation on an Array
I have a question where I need to rotate an array left k times.
i.e. if k = 2, [1, 2, 3, 4, 5] . -> [3, 4, 5, 1, 2]
So, my code is:
def array_left_rotation(a, n, k):
for i in range(n):
t = a[i]
a[i] = a[(i+n-1+k)%n]
a[(i+n-1+k)%n] = t
return a
where n = l... | Left Rotation on an Array | I have a question where I need to rotate an array left k times.
i.e. if k = 2, [1, 2, 3, 4, 5] . -> [3, 4, 5, 1, 2]
So, my code is:
def array_left_rotation(a, n, k):
for i in range(n):
t = a[i]
a[i] = a[(i+n-1+k)%n]
a[(i+n-1+k)%n] = t
return a
where n = length of the array.
I think the... | [
"Another way to do this with the help of indexing is shown below..\ndef rotate(l, n):\n return l[n:] + l[:n]\n\nprint(rotate([1, 2, 3, 4, 5], 2))\n\n#output : [3, 4, 5, 1, 2]\n\nThis will only return the original list if n is outside the range [-len(l), len(l)]. To make it work for all values of n, use:\ndef rot... | [
18,
5,
5,
3,
1,
1,
1,
0,
0,
0,
0
] | [
"This solution requires constant extra memory, and runs in O(nk). \nIf the array has zero length, or there are zero rotations, skip the loop and return arr. \nFor every rotation we store the first element, then shift every other element to the left, finally placing the first element at the back of the list. We save... | [
-1,
-1,
-2,
-3
] | [
"algorithm",
"data_structures",
"python"
] | stackoverflow_0049462195_algorithm_data_structures_python.txt |
Q:
SyntaxError: unexpected EOF while parsing
I'm getting an error while running this part of the code. I tried some of the existing solutions, but none of them helped.
elec_and_weather = pd.read_csv(r'C:\HOUR.csv', parse_dates=True,index_col=0)
# Add historic DEMAND to each X vector
for i in range(0,24):
elec_an... | SyntaxError: unexpected EOF while parsing | I'm getting an error while running this part of the code. I tried some of the existing solutions, but none of them helped.
elec_and_weather = pd.read_csv(r'C:\HOUR.csv', parse_dates=True,index_col=0)
# Add historic DEMAND to each X vector
for i in range(0,24):
elec_and_weather[i] = np.zeros(len(elec_and_weather['D... | [
"The SyntaxError: unexpected EOF while parsing means that the end of your source code was reached before all code blocks were completed. A code block starts with a statement like for i in range(100): and requires at least one line afterwards that contains code that should be in it.\nIt seems like you were executing... | [
106,
68,
11,
7,
3,
3,
1,
1,
0
] | [] | [] | [
"eof",
"lint",
"python",
"python_3.6",
"python_3.x"
] | stackoverflow_0043189302_eof_lint_python_python_3.6_python_3.x.txt |
Q:
nested while loop in python tkinter
The following code searches a text file for a name and displays the related number in a tkinter entry box in Python.
so original text file includes:
bob 19
dan 20
shayne 17
I would like add another nested loop so that if there are two names the same then two numbers are returne... | nested while loop in python tkinter | The following code searches a text file for a name and displays the related number in a tkinter entry box in Python.
so original text file includes:
bob 19
dan 20
shayne 17
I would like add another nested loop so that if there are two names the same then two numbers are returned to the entry box. Sorry, I am new to Py... | [
"your question is not related to tkinter, so I made the code without it.\nIt works like this: you enter the name you're looking for, then it looks for matches using the count method. If there is a match, then the index is written to the 'B' array. Further, since there is a space between the name and number, we take... | [
1,
0
] | [] | [] | [
"loops",
"python",
"tkinter",
"while_loop"
] | stackoverflow_0074363728_loops_python_tkinter_while_loop.txt |
Q:
Unable to apply formula in a column of google sheet using python
import pandas as pd
import pygsheets
import gspread
from gspread_dataframe import set_with_dataframe
from google.oauth2.service_account import Credentials
def csv_to_sheets():
tokenPath ='path for service account file.json'
scopes = ['https://ww... | Unable to apply formula in a column of google sheet using python | import pandas as pd
import pygsheets
import gspread
from gspread_dataframe import set_with_dataframe
from google.oauth2.service_account import Credentials
def csv_to_sheets():
tokenPath ='path for service account file.json'
scopes = ['https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.... | [
"I believe your goal is as follows.\n\nYou want to put a formula of =SUM(S:AE) to a cell \"AF17\" using gspread for python.\n\nWhen I saw your script, I thought that workSheet1.batch_update(\"AF\",\"=SUM(S:AE)\") is required to be modified. So, how about the following modification?\nFrom:\nworkSheet1.batch_update(\... | [
1
] | [] | [] | [
"csv",
"google_sheets",
"google_sheets_api",
"gspread",
"python"
] | stackoverflow_0074445510_csv_google_sheets_google_sheets_api_gspread_python.txt |
Q:
Docker running script but server doesn't work
I am doing an encryption service that everytime a user goes on the server it changes the key , the problem is that when i run the python file alone in works like this
when it works
but when I am dockerizing it by the below code
FROM python:3
RUN mkdir -p "C:\Users\joe... | Docker running script but server doesn't work | I am doing an encryption service that everytime a user goes on the server it changes the key , the problem is that when i run the python file alone in works like this
when it works
but when I am dockerizing it by the below code
FROM python:3
RUN mkdir -p "C:\Users\joel\Desktop\mcast-freshers-week-devops-main\mcast-fre... | [
"When you run your command with docker run, you can always expose the internal port on the docker container to match your local host network port, use this command instead for running your docker container\ndocker run -it --rm -p 8080:8080 --name my-running-app my-python-app\n\nYou can then access your server by vi... | [
0
] | [] | [] | [
"docker",
"dockerfile",
"encryption",
"python"
] | stackoverflow_0074453625_docker_dockerfile_encryption_python.txt |
Q:
How to define specific coefficients for each input feature to increase and decrease their influence in loss function calculation?
I have a regression neural network with ten input features and three outputs. But all ten features do not have the same importance in loss function calculation (mean square error). So I... | How to define specific coefficients for each input feature to increase and decrease their influence in loss function calculation? | I have a regression neural network with ten input features and three outputs. But all ten features do not have the same importance in loss function calculation (mean square error). So I want to define specific coefficients for each input feature to increase their role in the loss function.
Consider we define coefficien... | [
"If you use the functional api, then you could add a custom loss function with the model.add_loss function, within the model. Your loss function can then use the model inputs and outputs and anything in your model.\nThe problem with this approach is, that in the model you don't have the 'true' y values. So you woul... | [
0
] | [] | [] | [
"keras",
"loss_function",
"mse",
"python",
"regression"
] | stackoverflow_0074425890_keras_loss_function_mse_python_regression.txt |
Q:
instantly ratelimited for no reason discord.py
I am trying to make a Discord.py bot on Repl.it, but the moment I ran it, I got ratelimited.
from keep_alive import keep_alive
import discord
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_... | instantly ratelimited for no reason discord.py | I am trying to make a Discord.py bot on Repl.it, but the moment I ran it, I got ratelimited.
from keep_alive import keep_alive
import discord
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
import os
from dis... | [
"There is many reasons why you can get rate-limited from the Discord API. The official info is listed here.\nFrom your post, you said you were using replit. Replit is actually not all that good for hosting bots (but of course its easy, cheap/free, and friendly for beginners). This is for multiple reasons, including... | [
1
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074418535_discord.py_python.txt |
Q:
Is everything an object in Python like Ruby?
I read on another Stack Overflow question that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby.
Is this true? Is everything an object in Python like Ruby?
How are the two different in this resp... | Is everything an object in Python like Ruby? | I read on another Stack Overflow question that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby.
Is this true? Is everything an object in Python like Ruby?
How are the two different in this respect or are they really the same? For example, can ... | [
"DiveIntoPython - Everything Is an Object \n\nEverything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code. The sys module is an object which has (among other things) an attrib... | [
93,
44,
25,
23,
2,
1,
1,
0
] | [] | [] | [
"language_comparisons",
"object",
"python",
"ruby"
] | stackoverflow_0000865911_language_comparisons_object_python_ruby.txt |
Q:
How to change sqlalchemy Oracle dialect use upper case for case insensitive?
I mean, at least uppercase column names in selected result.
I have an Oracle database and a lot of legacy documents/sql.
All column name in these documents are uppercase.
I want to write a new python project and use the documents as refer... | How to change sqlalchemy Oracle dialect use upper case for case insensitive? | I mean, at least uppercase column names in selected result.
I have an Oracle database and a lot of legacy documents/sql.
All column name in these documents are uppercase.
I want to write a new python project and use the documents as reference, but column name in sqlalchemy is all lower case and case a lot of problem.
I... | [
"After reading the source code I found a way, writing my own dialect to get case insensitive.\nclass MyOracleIdentifierPreparer(OracleIdentifierPreparer):\n\n def _requires_quotes(self, value):\n \"\"\"Return True if the given identifier requires quoting.\"\"\"\n lc_value = value.lower()\n l... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0072575977_python_sqlalchemy.txt |
Q:
I have a lot of SQL code that helps to model some data graphically, is there a way to easily convert this code to Python?
I am currently working with a code-base that has thousands of lines of SQL code. The logic is correct however the code will need to be converted to Python.
Is there an easy way to convert this ... | I have a lot of SQL code that helps to model some data graphically, is there a way to easily convert this code to Python? | I am currently working with a code-base that has thousands of lines of SQL code. The logic is correct however the code will need to be converted to Python.
Is there an easy way to convert this code to Python while maintaining the SQL logic/functionality?
I've looked into SQlalchemy but not too sure if this is the optim... | [
"If your logic already consists of \"SQL code that already works,\" then I recommend that you use Python code which simply executes those SQL queries \"directly, as written,\" and returns a recordset that you can then iterate. In this case, you do not need to concern yourself with libraries which endeavor to \"dyna... | [
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0074453839_python_sql.txt |
Q:
discord.py slash permissions
How to add permissions to discord.py slash-commands command? There is no @has_permissions() in slash-commands.
@slash.slash(
name="kick",
description="Kicks member from the server",
options=[manage_commands.create_option(
name = "member",
description = "Who ... | discord.py slash permissions | How to add permissions to discord.py slash-commands command? There is no @has_permissions() in slash-commands.
@slash.slash(
name="kick",
description="Kicks member from the server",
options=[manage_commands.create_option(
name = "member",
description = "Who do you want to kick?",
opt... | [
"Since there is currently no permissions check for (discord-py-slash-command)[https://pypi.org/project/discord-py-slash-command/], you can check within of your code if a member has a certain permission, as shown below\n@slash.slash(name=\"cool_command\")\nasync def cool_command(ctx, option):\n if not ctx.author.... | [
2,
1,
1,
0,
0,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0066143642_discord_discord.py_python.txt |
Q:
How to obtain just the year from pandas data frame?
So I wrote some code to turn a list of strings into date times:
s = pd.Series(["14 Nov 2020", "14/11/2020", "2020/11/14",
"Hello World", "Nov 14th, 2020"])
s_dates = pd.to_datetime(s, errors='coerce', exact=False)
print(s_dates)
It produced the follow... | How to obtain just the year from pandas data frame? | So I wrote some code to turn a list of strings into date times:
s = pd.Series(["14 Nov 2020", "14/11/2020", "2020/11/14",
"Hello World", "Nov 14th, 2020"])
s_dates = pd.to_datetime(s, errors='coerce', exact=False)
print(s_dates)
It produced the following output:
0 2020-11-14
1 2020-11-14
2 2020-11-14
... | [
"Since your seriess_dates has dtype datetime64[ns], you can directly use\nSeries.dt.year like:\nprint(s_dates.dt.year)\n\nThis will return a series containing only the year (as dtype int64).\nCheck the documentation for more useful datetime transformations.\n",
"Assuming your years would always be 4 digits, we ca... | [
3,
0
] | [] | [] | [
"datetime",
"pandas",
"python",
"python_3.x",
"time"
] | stackoverflow_0074453902_datetime_pandas_python_python_3.x_time.txt |
Q:
I'm trying to write a discord bot using python but i got no responses from the bot :'(
I have tried to make a discord bot using python but thing is that the bot does not respond...
So I just restarted from 0 and made this little code :
import discord
bot = discord.Bot()
@bot.event
async def on_ready():
print... | I'm trying to write a discord bot using python but i got no responses from the bot :'( | I have tried to make a discord bot using python but thing is that the bot does not respond...
So I just restarted from 0 and made this little code :
import discord
bot = discord.Bot()
@bot.event
async def on_ready():
print(" -----------------")
print(" H2H - Here 2 Help")
print(" -----------------")
... | [
"close you are but its not discord.Bot but rather commands.Bot\nimport discord\nfrom discord.ext import commands\n\nbot = commands.bot()\n\n@bot.event\nasync def on_ready():\n print(\" -----------------\")\n print(\" H2H - Here 2 Help\")\n print(\" -----------------\")\n print(\" \")\n print(\"-->... | [
0,
0
] | [
"You were so close but there were a few issues:\n\nmessage.content.lower() is not a thing. try just using message.content\nTo access message.content you will need to enable the message intent.\nTo do this, head over to Discord Developer Portal and click on your bot. Then go to the bot slide and copy these settings ... | [
-1
] | [
"discord.py",
"python",
"python_3.x"
] | stackoverflow_0074435809_discord.py_python_python_3.x.txt |
Q:
PYQT5 - How to change the backgroun color of a checkbox when it is checked, and change it back when unchecked
I am using checkboxes to make a seating chart for a movie theater and I would like to know how I can change the background of the checkbox when its clicked. I have set a style sheet for its default color b... | PYQT5 - How to change the backgroun color of a checkbox when it is checked, and change it back when unchecked | I am using checkboxes to make a seating chart for a movie theater and I would like to know how I can change the background of the checkbox when its clicked. I have set a style sheet for its default color but I would like to change it to another one when it gets selected.
The seating chart:
I have searched around for a... | [
"I recommend to use the QPushButton with the checkable property set to True, rather than tweaking with the QCheckBox and QLabel.\nYou can do like this.\nb = QPushButton('A-1', checkable = True)\nb.setStyleSheet('''\n QPushButton {\n width:50px; height:50px;\n border: none;\n background-color... | [
0
] | [] | [] | [
"pyqt5",
"python",
"qt"
] | stackoverflow_0074450357_pyqt5_python_qt.txt |
Q:
How to list all installed Jupyter kernels?
Listing all the available environments is as simple as:
$ conda env list
Now how does one list the currently installed kernels, without having to go to the path:
$ ls /home/{{user}}/.local/share/jupyter/kernels/
A:
With Jupyter installed you get the list of currently i... | How to list all installed Jupyter kernels? | Listing all the available environments is as simple as:
$ conda env list
Now how does one list the currently installed kernels, without having to go to the path:
$ ls /home/{{user}}/.local/share/jupyter/kernels/
| [
"With Jupyter installed you get the list of currently installed kernels with:\n$ jupyter kernelspec list\n\npython2 /usr/local/lib/python2.7/dist-packages/ipykernel/resources\ntestenv /home/{{user}}/.local/share/jupyter/kernels/sparkenv\n\n",
"For those that come here because VSCode can't find the kernel ... | [
114,
0
] | [] | [] | [
"conda",
"python"
] | stackoverflow_0049299574_conda_python.txt |
Q:
How to transpose few columns in pandas and restructure the dataframe
I have a data frame like this:
df:
Col-1 Col-2 Type Rate
Ford Honda SUV 4
Ford Honda Sedan 3
Ford Jeep SUV 5
Ford Jeep Sedan 2
Ford RAM SUV 4
Ford RAM Sedan 3
There are thousands of ro... | How to transpose few columns in pandas and restructure the dataframe | I have a data frame like this:
df:
Col-1 Col-2 Type Rate
Ford Honda SUV 4
Ford Honda Sedan 3
Ford Jeep SUV 5
Ford Jeep Sedan 2
Ford RAM SUV 4
Ford RAM Sedan 3
There are thousands of rows and the Type column is a categorial column consisting of 2 different va... | [
"What you are looking for is a pivot table\npd.pivot_table(df, values='Rate', index=['Col-1', 'Col-2'], columns='Type').reset_index().rename_axis(None, axis=1)\n\nOutput\n Col-1 Col-2 SUV Sedan\n0 Ford Honda 4 3\n1 Ford Jeep 5 2\n2 Ford RAM 4 3\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074453913_dataframe_pandas_python_python_3.x.txt |
Q:
Find permutations of positive integers given sum and given number of elements
How to find all permutations of positive integers for a given sum and given number of elements.
For example,
Input: sum = 4, number of elements = 2.
Output: (1,3), (3,1), (2,2)
My thinking is, since I know the number of elements is N,... | Find permutations of positive integers given sum and given number of elements | How to find all permutations of positive integers for a given sum and given number of elements.
For example,
Input: sum = 4, number of elements = 2.
Output: (1,3), (3,1), (2,2)
My thinking is, since I know the number of elements is N, I will create N arrays, each from 1 to the sum S-1. So for the example, I will sta... | [
"Here's a recursive solution that will generate tuples that meet the requirements.\ndef get_combinations(target, num_elements, combinations=None):\n # Initialise an empty list\n if combinations == None:\n combinations = []\n # Calculate the sum of the current list of numbers\n combinations_sum = ... | [
2,
2
] | [] | [] | [
"combinations",
"numpy",
"permutation",
"python",
"python_3.x"
] | stackoverflow_0074452864_combinations_numpy_permutation_python_python_3.x.txt |
Q:
How do I create a representation when my constructor has added kwargs?
How do I create a representation when my constructor has added kwargs?
class Thing:
def __init__(self, a, b, **kwargs):
self.a = a
self.b = b
self.__dict__.update(kwargs)
# def __repr__(self):
# return ?... | How do I create a representation when my constructor has added kwargs? | How do I create a representation when my constructor has added kwargs?
class Thing:
def __init__(self, a, b, **kwargs):
self.a = a
self.b = b
self.__dict__.update(kwargs)
# def __repr__(self):
# return ???
thing1 = Thing(6, 5, color="red")
| [
"Assuming your exact scenario (i.e. every parameter is assigned to an attribute as-is), this should work:\nclass Thing:\n def __init__(self, a, b, **kwargs):\n self.a = a\n self.b = b\n self.__dict__.update(kwargs)\n\n def __repr__(self):\n argnames = self.__init__.__code__.co_varn... | [
0
] | [] | [] | [
"oop",
"python",
"representation"
] | stackoverflow_0074453930_oop_python_representation.txt |
Q:
pytrec library not able to install on my system raising error
I am trying to install the pytrec_eval library in python and is throwing me the following error
`
pip install pytrec_eval
Collecting pytrec_eval
Using cached pytrec_eval-0.5.tar.gz (15 kB)
Preparing metadata (setup.py) ... done
Installing collected... | pytrec library not able to install on my system raising error | I am trying to install the pytrec_eval library in python and is throwing me the following error
`
pip install pytrec_eval
Collecting pytrec_eval
Using cached pytrec_eval-0.5.tar.gz (15 kB)
Preparing metadata (setup.py) ... done
Installing collected packages: pytrec_eval
DEPRECATION: pytrec_eval is being installe... | [
"Accoring to this line:\n\nerror: Microsoft Visual C++ 14.0 or greater is required. Get it with\n\"Microsoft C++ Build Tools\":\nhttps://visualstudio.microsoft.com/visual-cpp-build-tools/\n\nYou need to install Microsoft Visual C++ 14.0.\n"
] | [
1
] | [] | [] | [
"failed_installation",
"python",
"visual_studio_code"
] | stackoverflow_0074444484_failed_installation_python_visual_studio_code.txt |
Q:
Using Python decorators to retry request
I have multiple functions in my script which does a REST API api requests.As i need to handle the error scenarios i have put a retry mechanism as below.
no_of_retries = 3
def check_status():
for i in range(0,no_of_retries):
url = "http://something/something"
... | Using Python decorators to retry request | I have multiple functions in my script which does a REST API api requests.As i need to handle the error scenarios i have put a retry mechanism as below.
no_of_retries = 3
def check_status():
for i in range(0,no_of_retries):
url = "http://something/something"
try:
result = requests.get(ur... | [
"You can use a decorator like this and handle your own exception.\ndef retry(times, exceptions):\n \"\"\"\n Retry Decorator\n Retries the wrapped function/method `times` times if the exceptions listed\n in ``exceptions`` are thrown\n :param times: The number of times to repeat the wrapped function/me... | [
21,
18,
7,
5,
1,
1,
0
] | [] | [] | [
"python",
"python_requests"
] | stackoverflow_0050246304_python_python_requests.txt |
Q:
How do I have this line of code print out the greeting, excluding some characters
#This is my string known as "greeting".
greeting = "hello how are you, what?"
#This prints the greeting the normal way.
print(greeting.title())
#This prints the greeting backwards and excluding the chosen letter "h" on the outsi... | How do I have this line of code print out the greeting, excluding some characters | #This is my string known as "greeting".
greeting = "hello how are you, what?"
#This prints the greeting the normal way.
print(greeting.title())
#This prints the greeting backwards and excluding the chosen letter "h" on the outside.
print (greeting.title()[:greeting.find("h"):-1] + greeting[greeting.rfind("h")-1... | [
"greeting = \"hello how are you, what?\"\ntitle = greeting.title()\nprint(title)\nprint(title[greeting.rfind('h') - 1:greeting.find('h'):-1])\n\nThis outputs:\nHello How Are You, What?\nW ,uoY erA woH olle\n\nDemo: https://replit.com/@blhsing/UnknownMustyFlatassembler\n",
"Regular expressions would be another way... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074454005_python.txt |
Q:
How do I detect whether a variable is a function?
I have a variable, x, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
>>> isinstance(x, function)
But that gives me:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function'... | How do I detect whether a variable is a function? | I have a variable, x, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
>>> isinstance(x, function)
But that gives me:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
The reason I picked that is because
>>... | [
"If this is for Python 2.x or for Python 3.2+, you can use callable(). It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: http://bugs.python.org/issue10518. You can do this with:\ncallable(obj)\n\nIf this is for Python 3.x but before 3.2, check if the objec... | [
1164,
329,
104,
86,
53,
30,
26,
19,
16,
15,
9,
8,
6,
6,
5,
4,
4,
4,
3,
2,
1,
1,
1,
0,
0,
0
] | [
"If the code will go on to perform the call if the value is callable, just perform the call and catch TypeError.\ndef myfunc(x):\n try:\n x()\n except TypeError:\n raise Exception(\"Not callable\")\n\n",
"The following is a \"repr way\" to check it. Also it works with lambda.\ndef a():pass\ntype(a) #<clas... | [
-1,
-1,
-2,
-4
] | [
"python"
] | stackoverflow_0000624926_python.txt |
Q:
Project Euler #8 in Python
Find the greatest product of five consecutive digits in the 1000-digit number:
import time
num = '\
73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
1254069874715852386305071569329... | Project Euler #8 in Python | Find the greatest product of five consecutive digits in the 1000-digit number:
import time
num = '\
73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950... | [
"There were several issues.\n\nYou were printing product not biggest. Make sure to print the right variable!\nYou were iterating through the length of the entire string when you should really just iterate in the range [0..len(num) - 4) so that you don't get an IndexError when you do your product calculation.\nYou w... | [
11,
3,
1,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0019285079_python.txt |
Q:
How to call elements from a .txt file with python?
I have a .txt file that was saved with python. It has the form:
file_inputs
Where the first line is just a title that helps me remember the order of each element that was saved and the second line is a sequence of a string ('eos') and other elements inside. How ca... | How to call elements from a .txt file with python? | I have a .txt file that was saved with python. It has the form:
file_inputs
Where the first line is just a title that helps me remember the order of each element that was saved and the second line is a sequence of a string ('eos') and other elements inside. How can I call the elements so that inputs[0] returns a string... | [
"I am not sure why you want inputs[&] to return 5.\nHowever here is a the standard (simple) way to read a text file with python:\nf = open('/path/to/file.txt', 'r')\ncontent = f. read()\n#do whatever you want there\nf. close()\n\nTo get eos printed first you might want to iterate through the content string until yo... | [
0,
0
] | [] | [] | [
"database",
"json",
"jupyter",
"pickle",
"python"
] | stackoverflow_0074454026_database_json_jupyter_pickle_python.txt |
Q:
Pylint on VS Code with WSL2: Unable to import local packages (import-error)
Context:
Windows 10 + VS Code + WSL2
WSL2 using Ubuntu 20.04 and all the dev environment is installed inside the distro
On the distro I use pyenv to create a virtual environment
My workspace has a project with sub-projects folder structur... | Pylint on VS Code with WSL2: Unable to import local packages (import-error) | Context:
Windows 10 + VS Code + WSL2
WSL2 using Ubuntu 20.04 and all the dev environment is installed inside the distro
On the distro I use pyenv to create a virtual environment
My workspace has a project with sub-projects folder structure, I need to configure pylint for one specific sub-project
I'm using python 3.10 ... | [
"Vscode identification file is found with the workspace as the root directory. You can use the following methods to import method:\n\nUse code from sub_projects.proj_2.src.app.services import database\n\nPlace a .env file at the root of your project which adds your source directory to PYTHONPATH:\nPYTHONPATH=/sub_p... | [
1
] | [] | [] | [
"pylint",
"python",
"visual_studio_code"
] | stackoverflow_0074446653_pylint_python_visual_studio_code.txt |
Q:
Bitwise: Why 14 & -14 is equals to 2 and 16 & -16 is equals to 16?
it is a dummy question, but I need to understand it more deeply
A:
Python integers use two's complement to store signed values. That means that positive numbers are stored simply as their bit sequence (so 14 is 00001110 since it's equal to 8 + 4 ... | Bitwise: Why 14 & -14 is equals to 2 and 16 & -16 is equals to 16? | it is a dummy question, but I need to understand it more deeply
| [
"Python integers use two's complement to store signed values. That means that positive numbers are stored simply as their bit sequence (so 14 is 00001110 since it's equal to 8 + 4 + 2). On the other hand, negative numbers are stored by taking their positive quantity, inverting it, and adding one. So -14 is 11110010... | [
1
] | [
"A bitwise operation is a binary operation.\nIn some representations of integers, one bit is used to represent the sign of the number. Depending upon which bit that is, will change the result of the bitwise &. In 2's complement, negative numbers are represented by inverting all the bits and then adding 1. There are... | [
-1
] | [
"bit_manipulation",
"python"
] | stackoverflow_0074453905_bit_manipulation_python.txt |
Q:
How to distance between all points in list?
I am plotting random points on a graph. I want to find the Eucildean distance from every point to another in a list.
Previous result/attempt can be viewed here
I generate 4 random numbers between 0 and 10 for the x and y coordinates, and then pair them using np.array. I ... | How to distance between all points in list? | I am plotting random points on a graph. I want to find the Eucildean distance from every point to another in a list.
Previous result/attempt can be viewed here
I generate 4 random numbers between 0 and 10 for the x and y coordinates, and then pair them using np.array. I need use distance formula and a nested loop to ca... | [
"You can try the code below to achieve calculating the distance between each pair of points\nimport random\nimport math\n\ndist = []\n\nx = [random.uniform(1, 10) for n in range(4)]\ny = [random.uniform(1, 10) for n in range(4)]\n\npairs = list(zip(x,y))\n\n\ndef distance(x, y):\n return math.sqrt((x[0]-x[1])**2... | [
0,
0
] | [] | [] | [
"distance",
"nested",
"python"
] | stackoverflow_0074453574_distance_nested_python.txt |
Q:
PostgreSQL - query all tables' all table columns
How can I query all tables' all table columns in a database?
Method I've tried:
get all table names using select tablename from pg_tables where schemaname = 'public'
Process cmd string using UNION method of Postgres.
Execute the cmd string.
I have 19 tables in a ... | PostgreSQL - query all tables' all table columns | How can I query all tables' all table columns in a database?
Method I've tried:
get all table names using select tablename from pg_tables where schemaname = 'public'
Process cmd string using UNION method of Postgres.
Execute the cmd string.
I have 19 tables in a DB, and my method results in 19 times slower querying ... | [
"You can do this in a single query by using array_agg() and a join on the information_schema.tables and information_schema.columns tables.\nThis would return something similar to your expected output:\nselect\n t.table_name,\n array_agg(c.column_name::text) as columns\nfrom\n information_schema.tables t\ni... | [
11,
2,
0,
0
] | [] | [] | [
"arrays",
"database",
"postgresql",
"python",
"sql"
] | stackoverflow_0051941149_arrays_database_postgresql_python_sql.txt |
Q:
VSC Conda Enviroments - Can select interpreter but kernel remains always at base
(This is the first time I am asking a question on Stack Overflow, so apologies in advance if I am breaking a convention).
Context:
I am using a work laptop with VSC, Anaconda (22.9.0), and Python (3.9.13) installed. I have created an ... | VSC Conda Enviroments - Can select interpreter but kernel remains always at base | (This is the first time I am asking a question on Stack Overflow, so apologies in advance if I am breaking a convention).
Context:
I am using a work laptop with VSC, Anaconda (22.9.0), and Python (3.9.13) installed. I have created an environment to work with geospatial datasets using anaconda prompt conda create -n spa... | [
"The Select Interpreter panel is to select the interpreter for the .py file. If you want to change the jupyter kernel, click the kernel version in the upper right corner of the jupyter notebook interface and select it.\n\n"
] | [
0
] | [] | [] | [
"anaconda",
"environment",
"python",
"visual_studio_code"
] | stackoverflow_0074445752_anaconda_environment_python_visual_studio_code.txt |
Q:
ndb datastore query fetch_page always returns no cursor and more = false
I have a class which is an ndb.Model.
I am trying to add pagination so I added this:
@classmethod
def get_next_page(cls, cursor):
q = cls.query()
q_forward = q.order(cls.title)
if cursor:
cursor = ndb.datastore_query.Curso... | ndb datastore query fetch_page always returns no cursor and more = false | I have a class which is an ndb.Model.
I am trying to add pagination so I added this:
@classmethod
def get_next_page(cls, cursor):
q = cls.query()
q_forward = q.order(cls.title)
if cursor:
cursor = ndb.datastore_query.Cursor(cursor)
objects, cursor, more = q_forward.fetch_page(10, start_cursor=cu... | [
"\nI believe it should be ndb._datastore_query.Cursor (see reference) or just do ndb.Cursor\n\nIf the cursor came from UI and you had previously made it urlsafe, then you should be doing ndb._datastore_query.Cursor(urlsafe=cursor) or ndb.Cursor(urlsafe=cursor)\n\nAlso, when you don't have a cursor, make sure it's e... | [
0
] | [] | [] | [
"google_app_engine",
"google_app_engine_python",
"ndb",
"python"
] | stackoverflow_0074447309_google_app_engine_google_app_engine_python_ndb_python.txt |
Q:
docker forgets to install dependency from requirements file
I am trying to troubleshoot a tutorial on udemy on Windows 10 but when I run my containers the django app does not seem to want to load celery as a module. I tried a few different versions but still get the same error message. The celery worker seems fi... | docker forgets to install dependency from requirements file | I am trying to troubleshoot a tutorial on udemy on Windows 10 but when I run my containers the django app does not seem to want to load celery as a module. I tried a few different versions but still get the same error message. The celery worker seems fine. Does anyone here see my issue and help me understand what is... | [
"The problem was solved by completely deleting the image and rebuilding it from scratch.\n"
] | [
0
] | [] | [] | [
"celery",
"django",
"docker",
"pip",
"python"
] | stackoverflow_0074426687_celery_django_docker_pip_python.txt |
Q:
Count the frenquency of an item which appears in the sublist of a list-Python
I am writing Python, and I want to count the times of an item appears in a list(which is made up by multiple sublist)
a = [[3,2,5,6],[2,5,1,20],[7,3,16,5]]
The result: 3->2 times ; 1->1 time; 5->3 times
Heres the things, I do not want t... | Count the frenquency of an item which appears in the sublist of a list-Python | I am writing Python, and I want to count the times of an item appears in a list(which is made up by multiple sublist)
a = [[3,2,5,6],[2,5,1,20],[7,3,16,5]]
The result: 3->2 times ; 1->1 time; 5->3 times
Heres the things, I do not want to use loop.!!
Is there any other way? Thank you for helping. :)
| [
"It is not possible to do this without doing any loops. Comprehensions are loops. Counter uses a loop internally. Here is one possible answer:\nfrom collections import Counter\nCounter(e for s in a for e in s)\n# => Counter({5: 3, 3: 2, 2: 2, 6: 1, 1: 1, 20: 1, 7: 1, 16: 1})\n\n",
"You could do it using High orde... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074454101_list_python.txt |
Q:
Variable combinations of column designations in pandas
I can best explain my problem by starting with an example:
df = pd.DataFrame({"ID" : [1, 2, 3, 4],
"age": [46, 48, 55, 55],
"gender": ['female', 'female', 'male', 'male'],
"overweight": ['y', 'n', 'y', 'y'... | Variable combinations of column designations in pandas | I can best explain my problem by starting with an example:
df = pd.DataFrame({"ID" : [1, 2, 3, 4],
"age": [46, 48, 55, 55],
"gender": ['female', 'female', 'male', 'male'],
"overweight": ['y', 'n', 'y', 'y']},
index = [0, 1, 2, 3])
Now I... | [
"You can use itertools.combinations directly on the dataframe as iteration occurs on the column names:\nfrom itertools import combinations\n\nm = 2\nout = list(combinations(df, m))\n\noutput:\n[('ID', 'age'),\n ('ID', 'gender'),\n ('ID', 'overweight'),\n ('age', 'gender'),\n ('age', 'overweight'),\n ('gender', 'ove... | [
3,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0072490518_pandas_python.txt |
Q:
Code works only when i use print() in pygame library
This chunk of code only works when i declare the print("abc"), otherwise it just won't work at all for no aparent reason
Im using pygame for a Minesweeper project that im doing
works:
for Sprite in self.CellsSprites:
if Sprite.rect.colliderect(self.rect):
... | Code works only when i use print() in pygame library | This chunk of code only works when i declare the print("abc"), otherwise it just won't work at all for no aparent reason
Im using pygame for a Minesweeper project that im doing
works:
for Sprite in self.CellsSprites:
if Sprite.rect.colliderect(self.rect):
print("abc")
if time.time() - self.time > 0.... | [
"time.time() - self.time > 0.1\nMaybe the print(\"abc\") line slows the execution time just enough for this if clause to be true? Whereas without the print line, the code runs too fast so that this clause is false? Try lowering the float number a bit and see if you notice a difference. Or else pause the execution f... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074454280_pygame_python.txt |
Q:
ValueError: The number of FixedLocator locations (5), usually from a call to set_ticks, does not match the number of ticklabels (12)
this piece of code was working before, however, after creating a new environment , it stopped working for the line
plt.xticks(x, months, rotation=25,fontsize=8)
if i comment this li... | ValueError: The number of FixedLocator locations (5), usually from a call to set_ticks, does not match the number of ticklabels (12) | this piece of code was working before, however, after creating a new environment , it stopped working for the line
plt.xticks(x, months, rotation=25,fontsize=8)
if i comment this line then no error, after putting this line error is thrown
ValueError: The number of FixedLocator locations (5), usually from a call to set... | [
"I am using subplots and came across the same error. I've noticed that the error disappears if the axis being re-labelled (in my case the y-axis) shows all labels. If it does not, then the error you have flagged appears. I suggest increasing the chart height until all the y-axis labels are shown by default (See scr... | [
7,
6,
0,
0
] | [] | [] | [
"matplotlib",
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0062953704_matplotlib_numpy_pandas_python_python_3.x.txt |
Q:
Network graph not showing arrows along edge in Python
I have an adjacency matrix A and an array defining the coordinates of each node:
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
%matplotlib inline
Import adjacency matrix A[i,j]
A = np.matrix([[0, 1, 1, 0, 0, 1, 0],
[... | Network graph not showing arrows along edge in Python | I have an adjacency matrix A and an array defining the coordinates of each node:
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
%matplotlib inline
Import adjacency matrix A[i,j]
A = np.matrix([[0, 1, 1, 0, 0, 1, 0],
[0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0],... | [
"At some point, I got very annoyed at the lack of proper arrow support in the networkx drawing facilities and wrote my own, while keeping the API pretty much the same. Code can be found here.\n \nimport numpy as np\nimport netgraph\n\nA = np.matrix([[0, 1, 1, 0, 0, 1, 0],\n [0, 0, 1, 1, 0, 0, 0],\n ... | [
5,
3,
1,
0
] | [] | [] | [
"adjacency_matrix",
"graph",
"networkx",
"python"
] | stackoverflow_0046150015_adjacency_matrix_graph_networkx_python.txt |
Q:
Replace non-unique values between data frames based on a condition
I have n_df:
x y1 y2 y3 y4
0 -20.0 -0.839071 10.0 0.816164 -8795.000
1 -19.9 -0.865213 9.9 0.994372 -8667.619
2 -19.8 -0.889191 9.8 1.162644 -8541.472
3 -19.7 -0.910947 9.7 1.319299 -8416.553
4 -... | Replace non-unique values between data frames based on a condition | I have n_df:
x y1 y2 y3 y4
0 -20.0 -0.839071 10.0 0.816164 -8795.000
1 -19.9 -0.865213 9.9 0.994372 -8667.619
2 -19.8 -0.889191 9.8 1.162644 -8541.472
3 -19.7 -0.910947 9.7 1.319299 -8416.553
4 -19.6 -0.930426 9.6 1.462772 -8292.856
.. ... ... ... ... | [
"Assuming this n_df as example:\n x y1 y4\n252 -20.0 0 23.345\n253 5.3 1 97.697\n254 5.3 2 12.345\n\nYou can use a merge_asof, however it is a bit capricious so you need some pre- and post-processing (by key cannot be a float, on key must be sorted and temporarily renamed, the index must b... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074453807_dataframe_pandas_python.txt |
Q:
Selenium, trying to figure out how to loop through job search on linkedIn and scrape data
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import ex... | Selenium, trying to figure out how to loop through job search on linkedIn and scrape data | from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = ... | [
"\nIt would be always better to sign in with linkedin to figure out the real scenario.\n\nYou have to select the right element locator strategy in correct way\n\nYou have to scroll to grab all the elements from a page\n\n\nFull working code with an example:\nfrom selenium import webdriver\nfrom selenium.webdriver.... | [
0
] | [] | [] | [
"file_writing",
"printing",
"python",
"selenium"
] | stackoverflow_0074452078_file_writing_printing_python_selenium.txt |
Q:
Python fast api getting internal server error
I am new to python and fastapi, and was playing around it.
I wrote this code
from fastapi import FastAPI
app = FastAPI()
people = {
"1": {
"name": "abc",
"age": 27
},
"2": {
"name": "xyz",
"age": 60
}
}
@app.get("/"... | Python fast api getting internal server error | I am new to python and fastapi, and was playing around it.
I wrote this code
from fastapi import FastAPI
app = FastAPI()
people = {
"1": {
"name": "abc",
"age": 27
},
"2": {
"name": "xyz",
"age": 60
}
}
@app.get("/")
def read_root():
return {"Hello": "World"}
... | [
"In your dictionary \"people\" you have declared the \"id\" (the keys) as strings.\nHowever in the path operation of @app.get(\"/people/{person_id}\") you have declared the person_id as an int. That's why the error occurs. Remember that pydantic uses these type declarations for data validation.\nThe correct thing w... | [
1
] | [] | [] | [
"fastapi",
"python",
"python_3.x"
] | stackoverflow_0074452604_fastapi_python_python_3.x.txt |
Q:
how to make a nested data array in python
i have a nested data in array javascript,i want to make that in python,
what i should use to make multiple data inside an array like this in python.
const people = [
{ id: 1, name: 'Udin', age: 12 },
{ id: 2, name: 'Wati', age: 51 },
{ id: 3, name: 'Budi', a... | how to make a nested data array in python | i have a nested data in array javascript,i want to make that in python,
what i should use to make multiple data inside an array like this in python.
const people = [
{ id: 1, name: 'Udin', age: 12 },
{ id: 2, name: 'Wati', age: 51 },
{ id: 3, name: 'Budi', age: 34 },
{ id: 4, name: 'Agus', age: 16 }... | [
"Pretty straightforward, just have to quote the string keys:\npeople = [ \n { 'id': 1, 'name': 'Udin', 'age': 12 }, \n { 'id': 2, 'name': 'Wati', 'age': 51 }, \n { 'id': 3, 'name': 'Budi', 'age': 34 }, \n { 'id': 4, 'name': 'Agus', 'age': 16 }, \n { 'id': 5, 'name': 'Sari', 'age': 19 }, \n { 'id':... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074454094_python.txt |
Q:
Python. list.pop() based on index
I was working with list in python and I need to remove non-true values.
Can someone explain why here I get index out of range error:
for n in range(len(lst)-1): #index outside the range
if not bool(lst[n]):
lst.pop(n)
return lst
It is ... | Python. list.pop() based on index | I was working with list in python and I need to remove non-true values.
Can someone explain why here I get index out of range error:
for n in range(len(lst)-1): #index outside the range
if not bool(lst[n]):
lst.pop(n)
return lst
It is kind of work with while loop
def compac... | [
"When you delete an element, all the elements after it renumber: the n+1th element becomes nth element, etc. But you progress to the next n anyway. This is why you are skipping some elements.\nIn the first snippet, you pre-construct the list of indices to iterate over; but as the list shortens, some of the later in... | [
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074454230_list_python.txt |
Q:
Sort a list of dict according to an order of another list
I have a list and another list which consists of dictionaries.
list1 = ['d', 'a', 'c', 'b', 'e', 'g']
list2 = [{'key1':'a', 'key2': 'asdf'}, {'key1': 'f', 'key2': 'dd'}, {'key1': 'b', 'key2': 'afd'}, {'key1': 'c', 'key2': 'ff'}, {'key1': 'd', 'key2': 'aa'},... | Sort a list of dict according to an order of another list | I have a list and another list which consists of dictionaries.
list1 = ['d', 'a', 'c', 'b', 'e', 'g']
list2 = [{'key1':'a', 'key2': 'asdf'}, {'key1': 'f', 'key2': 'dd'}, {'key1': 'b', 'key2': 'afd'}, {'key1': 'c', 'key2': 'ff'}, {'key1': 'd', 'key2': 'aa'}, {'key1': 'e', 'key2': 'aab'}]
Neither list1 nor list2 is sort... | [
"Your desired result doesn't include the dict with 'key1': 'f', so I assume you want to filter anything out that can't be sorted according to the rule you've specified. Start there:\n>>> list1 = ['d', 'a', 'c', 'b', 'e', 'g']\n>>> list2 = [{'key1':'a', 'key2': 'asdf'}, {'key1': 'f', 'key2': 'dd'}, {'key1': 'b', 'k... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074454226_python.txt |
Q:
My program can't seem to find the python.exe in my Computer
Iv'e tried using my folder that I made in school in my own pc but I can't seem to start it as I am assuming that the path to my python3.9 in school and in my house is not the same place. I write these 2 commands:
.\env\Scripts\activate
python app.py
And t... | My program can't seem to find the python.exe in my Computer | Iv'e tried using my folder that I made in school in my own pc but I can't seem to start it as I am assuming that the path to my python3.9 in school and in my house is not the same place. I write these 2 commands:
.\env\Scripts\activate
python app.py
And then I get this back:
No Python at 'C:\Python\Python39\python.exe
... | [
"First, I would make sure you have Python installed. To do this, at a command prompt, just type 'python' and see if you get a current version.\nOne 1 of 3 things will happen:\n\n\n\nYou'll see this...meaning that IT IS installed.\n\nNothing will happen at all, because you don't have it installed.\n\nWindows will a... | [
1,
0
] | [] | [] | [
"pip",
"python",
"python_venv",
"visual_studio_code"
] | stackoverflow_0074449331_pip_python_python_venv_visual_studio_code.txt |
Q:
UnboundLocalError - variable referenced before assignment
I have the following function that I need help debugging. I am getting an error saying
"in checkValidMove
i
UnboundLocalError: local variable 'i' referenced before assignment"
How can I fix this? Please see the function below. Thanks!
def checkValidMove(boa... | UnboundLocalError - variable referenced before assignment | I have the following function that I need help debugging. I am getting an error saying
"in checkValidMove
i
UnboundLocalError: local variable 'i' referenced before assignment"
How can I fix this? Please see the function below. Thanks!
def checkValidMove(board, row, col, tile):
#check if spot is valid to place tile ... | [
"I'm assuming that since you want to access the value of i, it should be properly indented under the appropriate loops.\nfor i in range(col -1, -1, -1):\n if board[row][i] == '.':\n break\n left = i + 1 \n\n(Do the same for the others)\n"
] | [
0
] | [] | [] | [
"python",
"unbound"
] | stackoverflow_0074454491_python_unbound.txt |
Q:
Python using random within a loop - separated by user action
I'm new to coding and started with a python course now.
I was trying to work on a word bingo game but can't seem to make it work.
import random
from random import randint
print "Let's play Bingo!"
print
# prompt for input
bingo = input("First enter you... | Python using random within a loop - separated by user action | I'm new to coding and started with a python course now.
I was trying to work on a word bingo game but can't seem to make it work.
import random
from random import randint
print "Let's play Bingo!"
print
# prompt for input
bingo = input("First enter your bingo words: ")
# split up the sentence into a list of words
l... | [
"Two comments:\n\nDon't use list for variable name, it is a keyword in Python for type list\nrandom.shuffle(l) does operation in-place (i.e. after you called it, l will be shuffled). So, you just supply l into the loop. Hope this helps.\n\nimport random\nfrom random import randint\n\nprint \"Let's play Bingo!\"\npr... | [
2
] | [] | [] | [
"loops",
"python",
"random"
] | stackoverflow_0074453867_loops_python_random.txt |
Q:
How do I delay one loop while the other runs independantly?
import time
i = 1
def sendData(x):
time.sleep(5)
print("delayed data: ", x)
while (1):
print(i)
sendData(i)
i += 1
time.sleep(0.5)
What I want is to print a value every 5 seconds while the infinite loop runs.
so I can see the va... | How do I delay one loop while the other runs independantly? | import time
i = 1
def sendData(x):
time.sleep(5)
print("delayed data: ", x)
while (1):
print(i)
sendData(i)
i += 1
time.sleep(0.5)
What I want is to print a value every 5 seconds while the infinite loop runs.
so I can see the values printing very .5 seconds and another value being printed eve... | [
"You can achieve your goal using the threading library. It allows you to run code in the \"background\" while your main code runs alongside it.\nHere's an example of how to run the sendData function in the background with the main loop executing concurrently. Notice that I modified sendData to use the global variab... | [
5,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074445750_python.txt |
Q:
How to fit 2 gauss in python
I am a new user of Python. I am trying to fit 2 Gaussians with data but there are some errors in the results.
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy as scipy
from scipy import optimize
from matplotlib.ticker import AutoMinorLocator
from matplo... | How to fit 2 gauss in python | I am a new user of Python. I am trying to fit 2 Gaussians with data but there are some errors in the results.
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy as scipy
from scipy import optimize
from matplotlib.ticker import AutoMinorLocator
from matplotlib import gridspec
import matplo... | [
"Don't rewrite _1gaussian2 as a near-identical implementation of _1gaussian1.\nDon't hard-code your time offsets - unless these come from real experimental settings, leave them as degrees of freedom for your fit. Same for the 0.2 vertical offset.\nDon't throw away your power data (the column headings). If I interpr... | [
0
] | [] | [] | [
"amplitude",
"csv",
"curve_fitting",
"gauss",
"python"
] | stackoverflow_0074426740_amplitude_csv_curve_fitting_gauss_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.