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: Defined function is miscounting number of upper/lowercase characters def letcheck(a): upper = 0 lower = 0 for letter in a: if a.islower(): lower += 1 else: upper += 1 print('The number of lowercase letters is', lower) print('The number of uppercase letter...
Defined function is miscounting number of upper/lowercase characters
def letcheck(a): upper = 0 lower = 0 for letter in a: if a.islower(): lower += 1 else: upper += 1 print('The number of lowercase letters is', lower) print('The number of uppercase letters is', upper) return letcheck('My name is Slugcat') Hi there. I imag...
[ "Change if a.islower() to if letter.islower() as you want to check the case for each letter not a which is the sentence itself. Spaces are counted as uppercase so for an accurate reading loop over the sentence with the whitespace removed.\ndef letcheck(a):\n upper = 0\n lower = 0\n #Loop over sentence with...
[ -1 ]
[]
[]
[ "for_loop", "function", "python", "user_defined_functions" ]
stackoverflow_0074173682_for_loop_function_python_user_defined_functions.txt
Q: Sudoku solving taking forever to run The example below is working however, if more zeros (empty cells) are added to the sudoku grid g, it takes longer to run, if it ever finishes. Not asking for a code review here, just I might've overlooked something, and I'd appreciate pointing it out. def is_solved(grid): f...
Sudoku solving taking forever to run
The example below is working however, if more zeros (empty cells) are added to the sudoku grid g, it takes longer to run, if it ever finishes. Not asking for a code review here, just I might've overlooked something, and I'd appreciate pointing it out. def is_solved(grid): for row, col in zip(grid, [*zip(*grid)]): ...
[ "Looking only at the first version of your code, there are a few things you can improve in the solve function:\n\n(A problem also in the second version:) You shouldn't loop over all empty_cells. Instead consider that you must find a solution for the first empty cell, and if after doing all of the recursive effort t...
[ 1 ]
[]
[]
[ "backtracking", "python", "sudoku" ]
stackoverflow_0074168960_backtracking_python_sudoku.txt
Q: How I can remove hidden nan values I have a dataset which has many nan values when I am type the unique values : plays.yardlineSide.unique() array(['TB', 'DAL', nan, 'ATL', 'PHI', 'PIT', 'BUF', 'NYJ', 'CAR', 'MIN', 'CIN', 'DET', 'SF', 'HOU', 'JAX', 'IND', 'SEA', 'TEN', 'ARI', 'LAC', 'WAS', 'CLE', 'KC', 'MIA...
How I can remove hidden nan values
I have a dataset which has many nan values when I am type the unique values : plays.yardlineSide.unique() array(['TB', 'DAL', nan, 'ATL', 'PHI', 'PIT', 'BUF', 'NYJ', 'CAR', 'MIN', 'CIN', 'DET', 'SF', 'HOU', 'JAX', 'IND', 'SEA', 'TEN', 'ARI', 'LAC', 'WAS', 'CLE', 'KC', 'MIA', 'NE', 'NO', 'GB', 'NYG', 'DEN', 'C...
[ "I think this might work.\n import pandas as pd\n\n df = pd.read_csv(\"file.csv\")\n\n for col in df.columns:\n if df[col].isnull().sum() > 0:\n print(\"Column {} has {} hidden nan values\".format(col, \n df[col].isnull().sum()))\n df.drop(col, axis=1, inplace=True)\n\n df.to_csv(\"file_without_...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074173237_pandas_python.txt
Q: Error to install Jupyter Notebook for Python in Windows 10 using PIP i am very on amateur on these things. I downloaded pip and then i used this python get-pip.py to install pip which completed successfully and then i used pip install jupyter notebook and i got the below error error: subprocess-exited-with-error ...
Error to install Jupyter Notebook for Python in Windows 10 using PIP
i am very on amateur on these things. I downloaded pip and then i used this python get-pip.py to install pip which completed successfully and then i used pip install jupyter notebook and i got the below error error: subprocess-exited-with-error Any help will ve appreciated Microsoft Windows [Version 10.0.19043.2130]...
[ "This problem is usually related to your python version, you can try to delete python 3.10 and install 3.9\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074173679_jupyter_notebook_python.txt
Q: Error text input entry and get() entry input have getting confused in getting the value from the Tkinter() Entry Field. I have this kind of code... def login(): root_login = Tk() root_login.title("Login") root_login.geometry("400x400") label_text_name = Label(root_login, text="Type mail your :") label_text_na...
Error text input entry and get() entry input
have getting confused in getting the value from the Tkinter() Entry Field. I have this kind of code... def login(): root_login = Tk() root_login.title("Login") root_login.geometry("400x400") label_text_name = Label(root_login, text="Type mail your :") label_text_name.pack() label_text_name.place(x=25, y=50) label_...
[ "This is because your after_login function doesn't know what e1 is, since it's defined outside of the functions scope. You have to modify your code, maybe by setting the variable as global ( Which can lead to other problems if done incorrectly ) or some other way let after_login know what an e1 is ( by maybe giving...
[ 2, 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074156808_python_tkinter.txt
Q: How to terminate a thread from threadpoolexecutor that import another python file? The code defines a function that import another file using importlib. And I want to import multiple files using for loops and making all imports as threads, but I came into the problem of killing those threads. Here's my main file: ...
How to terminate a thread from threadpoolexecutor that import another python file?
The code defines a function that import another file using importlib. And I want to import multiple files using for loops and making all imports as threads, but I came into the problem of killing those threads. Here's my main file: from concurrent import futures import importlib thread_pool_executor = futures.ThreadPoo...
[ "You need to change your design. Define your interface so that every add-in module has a function with a known name. Consider:\nimport time\nclass SomeClass:\n def __init__(self):\n self.terminate = False #flag variable\n self.run()\n\n def run(self):\n while True:\n #some op...
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0074047886_multithreading_python.txt
Q: How to Parse Visio Files Using Python I have used Apache POI to parse .pptx and visio files in Java. I also know that Python has python-pptx for parsing powerpoints. But has anyone run across a really good library for parsing the binary associated with Visio files for Python? I see a lot of questions and answers ...
How to Parse Visio Files Using Python
I have used Apache POI to parse .pptx and visio files in Java. I also know that Python has python-pptx for parsing powerpoints. But has anyone run across a really good library for parsing the binary associated with Visio files for Python? I see a lot of questions and answers for other languages, but not for Python. A...
[ "Please try vsdx - A python library for processing .vsdx files\n" ]
[ 1 ]
[]
[]
[ "binary", "python", "visio" ]
stackoverflow_0074173570_binary_python_visio.txt
Q: illegal target for annotation issue I run the following query, and got a error reminder -Error on line 7: string== Name:first_name ^ SyntaxError: illegal target for annotation. could anyone help me figure out the reason? thanks def format_name(first_name, last_name): if first_name==" " and last_name==" ": strin...
illegal target for annotation issue
I run the following query, and got a error reminder -Error on line 7: string== Name:first_name ^ SyntaxError: illegal target for annotation. could anyone help me figure out the reason? thanks def format_name(first_name, last_name): if first_name==" " and last_name==" ": string== Name:" " elif first_name==" " an...
[ "You have made this more complicated than it needs to be. Remember that you only need to add an extra space if both names are given. So:\ndef format_name(first_name, last_name):\n if first_name and last_name:\n return first_name+\" \"+last_name\n else:\n return first_name+last_name\n\nprint(for...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074173880_python.txt
Q: I am trying to split an arithmetic equation into a list of terms and operators An examples of what im trying to do: split('2.1 * -5 + 3 ^ 2 + 1 + -4.45') should output [2.1,'*',-5.0,'+',3.0,'^',2.0,'+',1.0,'+',-4.45] my current code: ops = ('+','-','*','/','^','(') def split(txt): final = [...
I am trying to split an arithmetic equation into a list of terms and operators
An examples of what im trying to do: split('2.1 * -5 + 3 ^ 2 + 1 + -4.45') should output [2.1,'*',-5.0,'+',3.0,'^',2.0,'+',1.0,'+',-4.45] my current code: ops = ('+','-','*','/','^','(') def split(txt): final = [] temp = [] inp = "".join(txt.split()) for x in inp: if x.isdigi...
[ "In line 32, you split the string.\nprint(split('2* ( -5.2 + 3 ) ^2+ ( 1 +4 )'))\n\nBut what you are appending in line 26 is int, not string therefore, you have an error.\nfinal.append(\"\".join(temp))\n\ntry\nfinal.append(\"\".join(str(temp)))\n\n", "Don't know exactly what is wrong with your program but y...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074173667_python.txt
Q: python use os.path.join to take spesific location I need to save a folder called D:\MyPc if the hostname is MyPc name_file = open("D:/Others/name.txt" , "r") data = name_file.readline() name_file.close() print(os.path.join("D:\", data)) the output is D: MyPc A: To check the hostname: How can I use Python to get...
python use os.path.join to take spesific location
I need to save a folder called D:\MyPc if the hostname is MyPc name_file = open("D:/Others/name.txt" , "r") data = name_file.readline() name_file.close() print(os.path.join("D:\", data)) the output is D: MyPc
[ "To check the hostname: How can I use Python to get the system hostname?\nAlso, there is an error in your code. Change the last line to have double backslash in string:\nprint(os.path.join(\"D:\\\\\", data))\n\n" ]
[ 0 ]
[]
[]
[ "operating_system", "os.path", "python" ]
stackoverflow_0074173919_operating_system_os.path_python.txt
Q: How to print in Python 3.10 a series of lists [1], [1, 2], [1, 2, 3], [1, 2, 3, ..., n] in one liner list comprehension I have a list [1, 2, 3, 4, ..., n]. In a one-liner list comprehension, how can I print the progression [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], ..., [1, 2, 3, 4, ..., n-1], where n represents an arb...
How to print in Python 3.10 a series of lists [1], [1, 2], [1, 2, 3], [1, 2, 3, ..., n] in one liner list comprehension
I have a list [1, 2, 3, 4, ..., n]. In a one-liner list comprehension, how can I print the progression [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], ..., [1, 2, 3, 4, ..., n-1], where n represents an arbitrary natural number?
[ "Now if you want this principle to operate on any starting list (not necessarily [1,2,...]), you can do this:\nrawlist=['a','b','c','d']\n\nnewlist=[rawlist[:i] for i in range(1,len(rawlist)+1)]\n\n", "Try this:\nn = 10\nres = [list(range(1,i)) for i in range(2,n+1)]\nprint(res)\n\nOutput:\n[\n [1], # range(1, 2)...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074173699_list_python.txt
Q: Time complexity question: why is it O(n log n)? Can someone explain why this is O(n log n) and not O(n^2)? I had the idea that the if statement is n times and the else is log n so you pick the worst case between the two in this case is O(n) so multiply it with the outer loop O(n) making it O(n^2) but apparently is...
Time complexity question: why is it O(n log n)?
Can someone explain why this is O(n log n) and not O(n^2)? I had the idea that the if statement is n times and the else is log n so you pick the worst case between the two in this case is O(n) so multiply it with the outer loop O(n) making it O(n^2) but apparently is O(n log n) and I am not seeing how. for i in range( ...
[ "For a large value of n, the if: condition will be neglected.\nInside else:, while loop continues to run for -\n\nj = 1 and j = 2 and j = 4 and ... and j = 2^m where 2^m <= n\n\n\nSo the total number of loops is m+1. And m = log n\n\nNow the time complexity is O(n * log n)\nfor i in range( len(nums_lst)): # Time c...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "time_complexity" ]
stackoverflow_0073875662_python_time_complexity.txt
Q: python: cant scrape table data from html website I have tried for hours to get the "decoded input data" from: https://polygonscan.com/tx/0x0d2e262cd328f53977d166a5cd1df3a9510b533efc81c71faa626b75cb7826e0 (to find it scroll down and click "see more" and then "decode input data" I scraped a lot of information from e...
python: cant scrape table data from html website
I have tried for hours to get the "decoded input data" from: https://polygonscan.com/tx/0x0d2e262cd328f53977d166a5cd1df3a9510b533efc81c71faa626b75cb7826e0 (to find it scroll down and click "see more" and then "decode input data" I scraped a lot of information from etherscan before but could never get the decoded input ...
[ "I suggest you use xpath to get the data you need. something like:\n 1 import requests\n 2 from lxml import etree\n 3 \n 4 s = requests.session()\n 5 r = s.get(\"https://polygonscan.com/tx/0x0d2e262cd328f53977d166a5cd1df3a9510b533efc81c71faa626b75cb7826e0\")\n 6 tree = etree.HTML(r.content)\n 7 inputdata = t...
[ 1 ]
[]
[]
[ "html", "html_table", "polygon", "python", "screen_scraping" ]
stackoverflow_0074173208_html_html_table_polygon_python_screen_scraping.txt
Q: How to set a background color to cells in a multiindex table? I have this multiindex column df: None INT INT INT PP PP PP DATE 2021-12-01 2021-12-02 2021-12-03 2021-12-04 2021-12-05 2021-12-06 0 1.0 0.0 2.0 2.0...
How to set a background color to cells in a multiindex table?
I have this multiindex column df: None INT INT INT PP PP PP DATE 2021-12-01 2021-12-02 2021-12-03 2021-12-04 2021-12-05 2021-12-06 0 1.0 0.0 2.0 2.0 4.0 2.0 1 NaN NaN NaN ...
[ "You can use Styler.apply(func, axis=None, subset) to get a DataFrame with valid index and columns labels considering subset:\ndef highlight_cols(df):\n color = pd.DataFrame().reindex_like(df.droplevel(0, axis=1))\n colors = ['yellow', 'lightgray', 'gray']\n\n color = color.fillna(f'background-color: {colo...
[ 2, 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074075209_pandas_python.txt
Q: Adding a 2nd order polynomial trend line px.scatter I have a data (a lot of rows in a dataframe) and was able to generate a linear trend line. I want also to add to the plot 2nd order polynomial trend line. How can this be done? thanks this is the code only on one row: import pandas as pd, numpy as np import plotl...
Adding a 2nd order polynomial trend line px.scatter
I have a data (a lot of rows in a dataframe) and was able to generate a linear trend line. I want also to add to the plot 2nd order polynomial trend line. How can this be done? thanks this is the code only on one row: import pandas as pd, numpy as np import plotly.express as px import statsmodels import nbformat x = [...
[ "plt.scatter(x,y)\nz=np.polyfit(x,y,1)\np=np.poly1d(z)\nz2=np.polyfit(x,y,2)\np2=np.poly1d(z2)\npd.options.display.float_format = '{:,.3f}'.format\nplt.plot(x, y , 'go')\nplt.plot(x, p(x),'r')\nplt.plot(x,p2(x))\nfor x1,y1 in zip(x,y):\n\n label = '{:,.3f}'.format(y1)\n\n plt.annotate(label, # this is the tex...
[ 0 ]
[]
[]
[ "plot", "polynomials", "python", "scatter_plot", "trendline" ]
stackoverflow_0074152059_plot_polynomials_python_scatter_plot_trendline.txt
Q: How do i use django rest frameworks to serialise a reverse relationship I've got a Favorites model which keeps track of each users' favorite NFT. I want to display the actual NFT data instead of the NFT id. I'm not quite sure how to do so as only primary keys are being returned. model class Favorites(models.Model)...
How do i use django rest frameworks to serialise a reverse relationship
I've got a Favorites model which keeps track of each users' favorite NFT. I want to display the actual NFT data instead of the NFT id. I'm not quite sure how to do so as only primary keys are being returned. model class Favorites(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) nft = mode...
[ "If you inspect that page a little further you will come across this link, and I'll answer quickly with a reference link as you seem competent enough to understand, whilst I contruct a proper answer.\nNested relationships in django rest framework link:\nhttps://www.django-rest-framework.org/api-guide/relations/#nes...
[ 2 ]
[]
[]
[ "django", "django_rest_framework", "python", "python_3.x" ]
stackoverflow_0074173940_django_django_rest_framework_python_python_3.x.txt
Q: Edit datetime for manipulation I have a list of customer orders for certain products, quantity and weight. I would like to forecast the orders by month, but my dates are displayed as DD-MM-YY date format I want to groupby the orders by month And in general it will display the indexes as MM-YY But when I try to see...
Edit datetime for manipulation
I have a list of customer orders for certain products, quantity and weight. I would like to forecast the orders by month, but my dates are displayed as DD-MM-YY date format I want to groupby the orders by month And in general it will display the indexes as MM-YY But when I try to see the graph of the activity it shows ...
[ "You can convert the index to datetime format, then you can cast it to a PeriodIndex:\ndf.index = pd.to_datetime(df.index, format='%Y-%m-%d')\ndf.index = df.index.to_period(\"M\")\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "datetime", "group_by", "pandas", "python" ]
stackoverflow_0074173785_dataframe_datetime_group_by_pandas_python.txt
Q: Python itertools.combinations: how to obtain the indices of the combined numbers The result created by Python's itertools.combinations() is the combinations of numbers. For example: a = [7, 5, 5, 4] b = list(itertools.combinations(a, 2)) # b = [(7, 5), (7, 5), (7, 4), (5, 5), (5, 4), (5, 4)] But I would like to ...
Python itertools.combinations: how to obtain the indices of the combined numbers
The result created by Python's itertools.combinations() is the combinations of numbers. For example: a = [7, 5, 5, 4] b = list(itertools.combinations(a, 2)) # b = [(7, 5), (7, 5), (7, 4), (5, 5), (5, 4), (5, 4)] But I would like to also obtain the indices of the combinations such as: index = [(0, 1), (0, 2), (0, 3), ...
[ "You can use enumerate:\n>>> a = [7, 5, 5, 4]\n>>> list(itertools.combinations(enumerate(a), 2))\n[((0, 7), (1, 5)), ((0, 7), (2, 5)), ((0, 7), (3, 4)), ((1, 5), (2, 5)), ((1, 5), (3, 4)), ((2, 5), (3, 4))]\n>>> b = list((i,j) for ((i,_),(j,_)) in itertools.combinations(enumerate(a), 2))\n>>> b\n[(0, 1), (0, 2), (0...
[ 26, 6, 0 ]
[]
[]
[ "python", "python_itertools" ]
stackoverflow_0027150990_python_python_itertools.txt
Q: Flask-login is able to log in user, but still AnonymousUserMixin for all subsequent requests I am able to successfully login and authenticate the user and I can access their info with current_user from the login method. But then when I make another API call and try to access current_user, I get an error and curren...
Flask-login is able to log in user, but still AnonymousUserMixin for all subsequent requests
I am able to successfully login and authenticate the user and I can access their info with current_user from the login method. But then when I make another API call and try to access current_user, I get an error and current_user is of type AnonymousUserMixin. I thought the issue may be with the load_user function, so I...
[ "I noticed your test route does not protect against anonymous access. according to flask-login docs 0.7..current_user would then be anonymous... Which means if you lock the test route to logged in users only current_user will then be populated!\n@app.route(\"/test\")\n@login_required\ndef test():\n print(current...
[ 0 ]
[]
[]
[ "flask", "flask_login", "python" ]
stackoverflow_0070415571_flask_flask_login_python.txt
Q: Evaluating pytorch pretrained model using a single image from a dataset Could someone help me in this problem: I try to evaluate pretraining an image with a ML model and i reveive the error state in the bottom of this post. As I understand the pytorch model want data to be in the following format: batch_channel, c...
Evaluating pytorch pretrained model using a single image from a dataset
Could someone help me in this problem: I try to evaluate pretraining an image with a ML model and i reveive the error state in the bottom of this post. As I understand the pytorch model want data to be in the following format: batch_channel, channel, Height, Lenght. I modify the tensor to be in this shape but I still g...
[ "Your model expects a 3-channel input, that's why you are getting an error. A naive and straightforward approach is to convert your grayscale image to rgb by repeating the channel dimension three times:\n>>> x = img_tensor.repeat(1,3,1,1) # assuming img_tensor shaped BCHW\n>>> y = model(x)\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "pytorch" ]
stackoverflow_0074164853_numpy_python_pytorch.txt
Q: How to merge two dataframes without generating extra rows in result? I am doing the following with two dataframes but it generates duplicates and does not get sorted as the first dataframe. import pandas as pd dict1 = { "time": ["15:09.123", "15:09.234", "15:10.123", "15:11.123", "15:12.123", "15:12.987"], ...
How to merge two dataframes without generating extra rows in result?
I am doing the following with two dataframes but it generates duplicates and does not get sorted as the first dataframe. import pandas as pd dict1 = { "time": ["15:09.123", "15:09.234", "15:10.123", "15:11.123", "15:12.123", "15:12.987"], "value": [10, 20, 30, 40, 50, 60] } dict2 = { "time": ["15:09", "15...
[ "Merge on column 'time' with preserved order\nAssumption: Data from df1 and df2 are in order of occurrence\nimport pandas as pd\n\ndict1 = {\n \"time\": [\"15:09.123\", \"15:09.234\", \"15:10.123\", \"15:11.123\", \"15:12.123\", \"15:12.987\"],\n \"value\": [10, 20, 30, 40, 50, 60]\n}\n\ndict2 = {\n \"time...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074173422_pandas_python.txt
Q: Calculate the first instance of a value in axis xarray? I have some input atmospheric model data of clouds in multi dimensions (3D): latitude , longitude and elevation. I'm trying to calculate cloud top height from this input data; so for each grid cell or column in model, I need to find the highest instance wher...
Calculate the first instance of a value in axis xarray?
I have some input atmospheric model data of clouds in multi dimensions (3D): latitude , longitude and elevation. I'm trying to calculate cloud top height from this input data; so for each grid cell or column in model, I need to find the highest instance where this input data is greater than a threshold. I found some r...
[ "TL;DR\nThe short answer is - you should broadcast the \"is cloud\" condition against the elevation dim itself so you get the elevations of valid clouds, then take the max:\nmax_cloud_elev = cloud.c.where(cloud > 0.6).max(dim=\"c\")\ncloud.sel(c=max_cloud_elev.fillna(0).astype(int)).where(max_cloud_elev.notnull())\...
[ 1 ]
[]
[]
[ "indexing", "python", "python_xarray" ]
stackoverflow_0074172428_indexing_python_python_xarray.txt
Q: Using json_to_record() to add a new row to a table PostgresSQL I have table_A with two columns: create table table_a(id int, data json); A row could be: insert into table_a values (1, '{"name": "kate", "cellphone": "000-000-0000", "address": "some text here"}'); I want to write a function that will take a row fr...
Using json_to_record() to add a new row to a table PostgresSQL
I have table_A with two columns: create table table_a(id int, data json); A row could be: insert into table_a values (1, '{"name": "kate", "cellphone": "000-000-0000", "address": "some text here"}'); I want to write a function that will take a row from table_A and insert a new row into table_B. Table_B has columns: i...
[ "You should use the function in a lateral join. A column definition list should be added as the function returns record.\nselect id, r.*\nfrom table_a\ncross join lateral \n json_to_record(data) \n as r(name varchar, cellphone varchar, address text, additional_info text)\n\n id | name | cellphone | addr...
[ 2, 0 ]
[]
[]
[ "database", "json", "postgresql", "pygresql", "python" ]
stackoverflow_0053787869_database_json_postgresql_pygresql_python.txt
Q: How do I find countries where the name has between 4 and 5 letters with regex in python list? How can I generate a list with regex in python for countries with 4 or 5 letters? names = ['Azerbaijan', 'Zimbabwe', 'Cuba', 'Cambodia', 'Somalia','Mali', 'Belarus', "Côte d'Ivoire", 'Venezuela', 'Syria', 'Kazakhstan', 'A...
How do I find countries where the name has between 4 and 5 letters with regex in python list?
How can I generate a list with regex in python for countries with 4 or 5 letters? names = ['Azerbaijan', 'Zimbabwe', 'Cuba', 'Cambodia', 'Somalia','Mali', 'Belarus', "Côte d'Ivoire", 'Venezuela', 'Syria', 'Kazakhstan', 'Austria', 'Malawi', 'Romania', 'Congo (Brazzaville)'] I was trying to do this but it returns an emp...
[ "if you need to use re then here is your answer find words of length 4 using regular expression\nif you dont need to use re just do\nn = [name for name in names if len(name) in (4,5)]\n", "You can use len(w).\n>>> names = ['Azerbaijan', 'Zimbabwe', 'Cuba', 'Cambodia', 'Somalia','Mali', 'Belarus', \"Côte d'Ivoire\...
[ 0, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0074174171_list_python_string.txt
Q: struct.error: unpack requires a buffer of 48000 bytes This is the error I am getting struct.error: unpack requires a buffer of 48000 bytes Is there anyway I can fix this without having to change the way I am trying to plot this? import wave import struct import matplotlib.pyplot as plt import numpy as np infile =...
struct.error: unpack requires a buffer of 48000 bytes
This is the error I am getting struct.error: unpack requires a buffer of 48000 bytes Is there anyway I can fix this without having to change the way I am trying to plot this? import wave import struct import matplotlib.pyplot as plt import numpy as np infile = "trumpet.wav" wav_file = wave.open(infile, "r") nchannels ...
[ "Never mind I figured it out. I needed to have my num_samples be half of the length of the data.\nframe_rate = 48000.0\ninfile = \"trumpet.wav\"\nnum_samples = 770246\nwav_file = wave.open(infile, 'r')\ndata = wav_file.readframes(num_samples)\nwav_file.close()\ndata = struct.unpack('{n}h'.format(n=num_samples), dat...
[ 0 ]
[]
[]
[ "python", "struct" ]
stackoverflow_0074166275_python_struct.txt
Q: Boundary problems using a numpy kernel and padding on a matrix within a C functions called from python I want to use an external c function a numpy kernel operation on an image. For this the goal is to go through the image image only within the padding so that the kernel does not go outside the image. In the follo...
Boundary problems using a numpy kernel and padding on a matrix within a C functions called from python
I want to use an external c function a numpy kernel operation on an image. For this the goal is to go through the image image only within the padding so that the kernel does not go outside the image. In the following debugging code, I first generate a matrix filled with 1 in the python script. I then pass this matrix w...
[ "Continuation of [SO]: How to write a function in C which takes as input two matrices as numpy array.\nThe problem is index calculation.\nWhen framing (centering) a (small) rectangle (inner), into a larger one (outer), the edge formula (on each axis (dimension)) is:\nedge = (outer_dim - inner_dim) / 2\n\ndll00.c:\n...
[ 1 ]
[]
[]
[ "arrays", "c", "matrix", "numpy", "python" ]
stackoverflow_0074171783_arrays_c_matrix_numpy_python.txt
Q: Define two global variables HOST and PORT and pass them to the .bind() method I'm a beginner and I can't quite get the task right. Here is the task: "According to the TCP flow diagram, now the .bind() method must be executed. The parameters of the .bind() method depend on the address family. In our case of IPv4 (s...
Define two global variables HOST and PORT and pass them to the .bind() method
I'm a beginner and I can't quite get the task right. Here is the task: "According to the TCP flow diagram, now the .bind() method must be executed. The parameters of the .bind() method depend on the address family. In our case of IPv4 (socket.AF_INET) it is a tuple consisting of two parameters: (host,port). For this, d...
[ "The basic server pattern:\nimport socket\n\nserver_socket = socket.socket() # defaults are IPv4 TCP\n\n# ONLY serves locally. Use '' to serve\n# on all available interfaces on the host.\nHOST = '127.0.0.1' # global\nPORT = 1337\n\nserver_socket.bind((HOST, PORT))\nserver_socket.listen() # default is fine\n\nwhile ...
[ 0 ]
[]
[]
[ "methods", "pycharm", "python", "sockets", "tcp" ]
stackoverflow_0074172636_methods_pycharm_python_sockets_tcp.txt
Q: I have 2 classes and its being put through some tests - I keep getting the error: __init__() missing 1 required positional argument: 'student_list' class Student: def __init__(self, first_name, last_name, id): self.first_name = first_name self.last_name = last_name self.id = id...
I have 2 classes and its being put through some tests - I keep getting the error: __init__() missing 1 required positional argument: 'student_list'
class Student: def __init__(self, first_name, last_name, id): self.first_name = first_name self.last_name = last_name self.id = id def __str__(self): return "{} {}, {}".format(self.first_name, self.last_name, self.id) class Course: def __init__(self, course_name, ...
[ "As noted in the comments, you’re not setting the value for the student_list variable. In this case you should provide a list. For example:\ncourse = Course(‘Programming’, [‘Alfred’, ‘Bob’, ‘Cynthia’])\n\nThen these variable values are assigned to the state of the object which you can check with course.course_name ...
[ 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0074173155_class_python.txt
Q: ImportError on pygame.base How do I fix this error? I'm trying to import and run a python game. A: In the screenshot you provided, it looks like Python might be corrupted or pygame might be corrupted. Try running pip install --upgrade --force-reinstall pygame, or pip3 install --upgrade --force-reinstall pygame. ...
ImportError on pygame.base
How do I fix this error? I'm trying to import and run a python game.
[ "In the screenshot you provided, it looks like Python might be corrupted or pygame might be corrupted.\nTry running pip install --upgrade --force-reinstall pygame, or pip3 install --upgrade --force-reinstall pygame.\nIf this doesn't work, you should reinstall Python using brew.\n" ]
[ 0 ]
[]
[]
[ "pycharm", "pygame", "python" ]
stackoverflow_0074174266_pycharm_pygame_python.txt
Q: Python - using strptime() to convert "20:52:30.0000000+02:00" into datetime I'm trying to do something like this this: time_str = "20:52:30.0000000+02:00" time = datetime.strptime(time_str, "%H:%M:%S.%f%z") But I'm getting the following error ValueError: time data '20:52:30.0000000+02:00' does not match format '%...
Python - using strptime() to convert "20:52:30.0000000+02:00" into datetime
I'm trying to do something like this this: time_str = "20:52:30.0000000+02:00" time = datetime.strptime(time_str, "%H:%M:%S.%f%z") But I'm getting the following error ValueError: time data '20:52:30.0000000+02:00' does not match format '%H:%M:%S.%f%z'. It's obvious that my format string is wrong, but I've gone through...
[ "%f handles values in range: 000000 - 999999 (https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)\nRemove one zero from input string and your code should work\nfrom datetime import datetime\n\ntime_str = \"20:52:30.000000+0200\"\ntime = datetime.strptime(time_str, \"%H:%M:%S.%f%z\")\n\nAnoth...
[ 2 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074174185_datetime_python.txt
Q: How can I implement Fastapi like Depends() without using any package or using raw python code? I want to implement my own Dependency Injection like Fastapi Depends() do actually without using external package or framework. What will be the approach? Code example will be helpful for me. Thanks in advance. from typi...
How can I implement Fastapi like Depends() without using any package or using raw python code?
I want to implement my own Dependency Injection like Fastapi Depends() do actually without using external package or framework. What will be the approach? Code example will be helpful for me. Thanks in advance. from typing import Callable, Optional, Any class Depends: def __init__(self, dependencies= Optional[Call...
[ "A starting point could be something like this, where we create a decorator that allows us to preempt any calls to the function and resolve any dependencies.\nfrom typing import Dict, Callable, Any\nfrom functools import wraps\nimport inspect\n\n\n# Our decorator which inspects the function and resolves any\n# depe...
[ 0 ]
[ "You can do something like this?\nasync def get_db(db_con=Depends(get_db_con)) -> AsyncIterable[Session]:\n session = Session(bind=db_con)\n try:\n yield session\n finally:\n session.close()\n\nThe get_db_con function could return the initialised database (or raise a connection error).\nHope ...
[ -1 ]
[ "dependencies", "dependency_injection", "fastapi", "python" ]
stackoverflow_0074167054_dependencies_dependency_injection_fastapi_python.txt
Q: Keep max value until ID and condition change in Pandas I have a dataframe that looks like this (link to csv) id time value approved 1 0:00 10 false 1 0:01 20 true 1 0:02 30 true 1 0:03 20 true 1 0:04 4...
Keep max value until ID and condition change in Pandas
I have a dataframe that looks like this (link to csv) id time value approved 1 0:00 10 false 1 0:01 20 true 1 0:02 30 true 1 0:03 20 true 1 0:04 40 false 1 0:05 35 false 1 ...
[ "The logic or output is not fully clear, but if I guess correctly, you can try:\ndf['td'] = pd.to_timedelta('0:'+df['time'])\n\ndf[['max_approved', 'max_time']] = (df\n .assign(value=df['value'].where(df['approved']),\n last_time=lambda d: d['td'].dt.total_seconds().where(df['approved']),\n )\n...
[ 2, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074150497_dataframe_pandas_python.txt
Q: Clear cached images in Jupyter Notebook I have a jupyter notebook that creates a local cache of images. I would like to clear the cache before I run a particular cell. Does anyone know how to do that? I tried: import gc gc.collect() But it had no effect. I also tried clear all the cookies and cache in chrome,...
Clear cached images in Jupyter Notebook
I have a jupyter notebook that creates a local cache of images. I would like to clear the cache before I run a particular cell. Does anyone know how to do that? I tried: import gc gc.collect() But it had no effect. I also tried clear all the cookies and cache in chrome, but that did work either.
[ "Try the following in a new cell of your Jupyter Notebook:\n%reset -f\n\nThe above will clear all variables without User Confirmation. If you want explicit user confirmation, just drop the -f.\n%reset_selective -f varName\n\nThe above will delete particular variable.\n\nIn case the Python version you are using is g...
[ 3, 1, 1, 0 ]
[ "The best and easiest solution is to first uninstall the Jupyter notebook then re-install it.\n" ]
[ -5 ]
[ "jupyter_notebook", "python" ]
stackoverflow_0049568038_jupyter_notebook_python.txt
Q: Assign a unique color to each distinct value in a pandas data frame How can a data frame like the below, but one whose values are unknown before runtime, be rendered with a unique color assigned to each distinct value? For example, in the below case, a valid solution would be to color cell A0 green, A1 red, B0 red...
Assign a unique color to each distinct value in a pandas data frame
How can a data frame like the below, but one whose values are unknown before runtime, be rendered with a unique color assigned to each distinct value? For example, in the below case, a valid solution would be to color cell A0 green, A1 red, B0 red, B1 blue, C0 yellow and C1 purple. A1 and B0 must have the same color, b...
[ "You can use seaborne.color_palette as a convenience to generate colors (alternatively any other method that gives you n unique colors), and factorize to map the unique values:\nimport seaborn as sns\n\ndef color_unique(df):\n # get unique values\n a, unique = pd.factorize(df.stack())\n\n # generate a colo...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074173601_pandas_python.txt
Q: Serialize 'csv' file as binary and append to file How is it possible to achieve the following at the same time in python 3: Serialize column names and numerical data as a binary file Reopen the file and append additional numerical data For example with the following data: import numpy as np columns = ['a', 'b',...
Serialize 'csv' file as binary and append to file
How is it possible to achieve the following at the same time in python 3: Serialize column names and numerical data as a binary file Reopen the file and append additional numerical data For example with the following data: import numpy as np columns = ['a', 'b', 'c'] data = np.linspace(0, 1, num=10*3).reshape((10, 3...
[ "import pickle\n\n\n\n# Write first df to pickle\ndata = {\n \"name\": [\"Joe\", \"Mike\", \"Tony\", \"Susan\"],\n \"course\": [\"Masters\", \"Doctorate\", \"Graduate\", \"Bachelors\"],\n \"age\": [27, 23, 21, 19],\n}\ndf = pd.DataFrame(data)\ndf.to_pickle(path)\n\n# Create new row df\nnew_row = {\"name\":...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python", "saving_data" ]
stackoverflow_0074174147_numpy_pandas_python_saving_data.txt
Q: Write list variable to file I have a .txt file of words I want to 'clean' of swear words, so I have written a program which checks each position, one-by-one, of the word list, and if the word appears anywhere within the list of censorable words, it removes it with var.remove(arg). It's worked fine, and the list is...
Write list variable to file
I have a .txt file of words I want to 'clean' of swear words, so I have written a program which checks each position, one-by-one, of the word list, and if the word appears anywhere within the list of censorable words, it removes it with var.remove(arg). It's worked fine, and the list is clean, but it can't be written t...
[ "write writes a string. You can not write a list variable, because, even though to humans it is clear that it should be written with spaces or semicolons between words, computers do not have the free hand for such assumptions, and should be supplied with the exact data (byte wise) that you want to write.\nSo you ne...
[ 2, 0 ]
[]
[]
[ "file_writing", "list", "python", "slice" ]
stackoverflow_0043701610_file_writing_list_python_slice.txt
Q: Django Model inheritance error "field ... clashes with the field" I'm having a problem when using multi-table inheritance in Django and I didn't find something that solved it. I have these two models: class Person(models.Model): id = models.CharField(primary_key=True, max_length=12, default="") name = mode...
Django Model inheritance error "field ... clashes with the field"
I'm having a problem when using multi-table inheritance in Django and I didn't find something that solved it. I have these two models: class Person(models.Model): id = models.CharField(primary_key=True, max_length=12, default="") name = models.CharField(max_length=12, default="") birthday = models.DateField...
[ "I believe mrcai have answered your question here:\nMark your class Person as an abstract class to avoid field clashing.\n\nYou can specify Profile is an abstract class. This will stop the check\nfrom being confused with your parent fields.\nclass Meta:\n abstract = True\n\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "one_to_one", "python" ]
stackoverflow_0070331562_django_django_models_one_to_one_python.txt
Q: Carla 0.9.13 Installation Issues I'm trying to install CARLA 0.9.13 on Python 3.10. on Windows 8. I'm following the steps mentioned in this guide. When I reach this point I'm having troubles with the following piece of instruction. Install Client Library Specifically with this piece of code: pip3 install carla Th...
Carla 0.9.13 Installation Issues
I'm trying to install CARLA 0.9.13 on Python 3.10. on Windows 8. I'm following the steps mentioned in this guide. When I reach this point I'm having troubles with the following piece of instruction. Install Client Library Specifically with this piece of code: pip3 install carla This always returns the following error....
[ "From the documentation Carla as a pip installable package is only available for python versions 2.7, 3.6, 3.7, and 3.8.\nThere is a github issue relating to getting it to build on 3.10.\nhttps://github.com/carla-simulator/carla/issues/5538\nBut that's for ubuntu not windows. Looks like it'll involve quite a bit of...
[ 0 ]
[]
[]
[ "carla", "pip", "python" ]
stackoverflow_0074136362_carla_pip_python.txt
Q: Extract file from fat image in python I have a fat32 partition image file dump, for example created with dd. how i can parse this file with python and extract the desired file inside this partition. A: As far as reading a FAT32 filesystem image in Python goes, the Wikipedia page has all the detail you need to wr...
Extract file from fat image in python
I have a fat32 partition image file dump, for example created with dd. how i can parse this file with python and extract the desired file inside this partition.
[ "As far as reading a FAT32 filesystem image in Python goes, the Wikipedia page has all the detail you need to write a read-only implementation.\nConstruct may be of some use. Looks like they have an example for FAT16 (https://github.com/construct/construct/blob/master/construct/formats/filesystem/fat16.py) which yo...
[ 1, 0 ]
[]
[]
[ "fat32", "python" ]
stackoverflow_0018233399_fat32_python.txt
Q: Load multiple images with incremental urls i have 1 problem i would like everyone to help. I need to download image files on 1 website, links https://acb.xyz.0001.jpg and the following files it similarly only change the number of extensions to https://acb.xyz.0002.jpg. Is there a way to use python to save those im...
Load multiple images with incremental urls
i have 1 problem i would like everyone to help. I need to download image files on 1 website, links https://acb.xyz.0001.jpg and the following files it similarly only change the number of extensions to https://acb.xyz.0002.jpg. Is there a way to use python to save those images. I tried to manually save each photo but it...
[ "Assuming you have already know how many image you need to download you can use this code.\nimport requests\n# Url to download content from \nURL = \"http://thuvien.hmu.edu.vn/pages/cms/TempDir/books/01419632-d344-4a8e-9f53-4e40be647c3a/2022/09/13/202209071405-e0309899-377b-43d1-9033-972aa96844b5/FullPreview/\"\n# ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074174379_python.txt
Q: Copy-on-write for large data in Python's ProcessPoolExecutor I want to leverage multiple cores for an expensive computation without copying the large data to all forked processes. In more detail: The large data is a large (networkx) graph plus certain edges cached in a dict. The expensive computation is a complex ...
Copy-on-write for large data in Python's ProcessPoolExecutor
I want to leverage multiple cores for an expensive computation without copying the large data to all forked processes. In more detail: The large data is a large (networkx) graph plus certain edges cached in a dict. The expensive computation is a complex path-finding algorithm, the input data is a list of vertices that ...
[ "When ProcessPoolExecutor forks its subprocesses, they will have a view of everything at module scope. Since you created large_graph before the subprocesses started, a function that accesses large_graph doesn't need to have the data passed in the futures call. The trick is to write a worker that knows the conventio...
[ 2 ]
[]
[]
[ "copy_on_write", "fork", "python", "python_multiprocessing" ]
stackoverflow_0074174299_copy_on_write_fork_python_python_multiprocessing.txt
Q: most occurrence of a two column combination enter image description hereI have two columns 'Start Station' and 'End Station' | Start Station | End Station | |:--------------|:------------| | A | C | | A | C | | B | D | | C | A ...
most occurrence of a two column combination
enter image description hereI have two columns 'Start Station' and 'End Station' | Start Station | End Station | |:--------------|:------------| | A | C | | A | C | | B | D | | C | A | | A | D | | C ...
[ "idxmax will return a tuple with the most frequent combination:\ndf.groupby(['Start Station', 'End Station']).value_counts().idxmax()\n\n", "Your question can be interpreted in many different ways (do you want all max? Does order of the route matter (A->C ≠ C->A?), etc.\nYou can use the first index of value_count...
[ 1, 0 ]
[]
[]
[ "combinations", "multiple_columns", "pandas", "python" ]
stackoverflow_0074174512_combinations_multiple_columns_pandas_python.txt
Q: Flask-Restful routes showing 404 I'm facing an issue where by in My Flask-Restful app, all the routes show 404 not found when I try to navigate too them. for example http://localhost:5000/api/v1/auth/login. In my App, all the routes are defined well but for some unclear reason all of them show 404. Upon searching ...
Flask-Restful routes showing 404
I'm facing an issue where by in My Flask-Restful app, all the routes show 404 not found when I try to navigate too them. for example http://localhost:5000/api/v1/auth/login. In my App, all the routes are defined well but for some unclear reason all of them show 404. Upon searching for an answer to this, I came across t...
[ "If you're using app factory, you need to add resources before calling api.init_app(app).\nSo:\n\napi = Api()\nauth_routes(api)\napi.init_app(app)\n\nThat should do the trick as it did for me just now. Also, for others looking into this, you can view current routes in the app by:\nIn flask shell: from flask import ...
[ 1 ]
[]
[]
[ "flask", "flask_restful", "python" ]
stackoverflow_0071464619_flask_flask_restful_python.txt
Q: Python psycopg2 LINE 1: CREATE TABLE IF NOT EXISTS HELLO fellow programmers today i present you with a bug that i have in my script the debugger tells me psycopg2.errors.SyntaxError: syntax error at or near "user" LINE 1: CREATE TABLE IF NOT EXISTS score (user VARCHAR(255),highscor... i dont understand what is ...
Python psycopg2 LINE 1: CREATE TABLE IF NOT EXISTS
HELLO fellow programmers today i present you with a bug that i have in my script the debugger tells me psycopg2.errors.SyntaxError: syntax error at or near "user" LINE 1: CREATE TABLE IF NOT EXISTS score (user VARCHAR(255),highscor... i dont understand what is wrong with my syntax , the url is removed for privacy re...
[ "You need to define, the table constraints. For example if they allow null or only unique values, so try this create variable instead.\ncreate=f\"CREATE TABLE IF NOT EXISTS {Nume} (user VARCHAR(255) NOT NULL, highscore VARCHAR(255) NOT NULL)\"\n\nReplace not null with null if you want to allow null.\n" ]
[ 0 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0074174549_psycopg2_python.txt
Q: How to concatenate string values in two lists without creating duplicates? I have two lists that I am trying to join. They two become one. A partial match between the values is used to merge the values. list1 = ["15:09.123", "15:09.234", "15:09.522", "15:09.621", "15:10.123", "15:11.123", "15:12.123", "15:12.987"]...
How to concatenate string values in two lists without creating duplicates?
I have two lists that I am trying to join. They two become one. A partial match between the values is used to merge the values. list1 = ["15:09.123", "15:09.234", "15:09.522", "15:09.621", "15:10.123", "15:11.123", "15:12.123", "15:12.987"] list2 = ["15:09", "15:09", "15:10", "15:14"] final = [] for each in list2: ...
[ "I might suggest using an iterator over list1 and consuming elements from it as you iterate over list2 (renaming these ms_list and s_list to make it easier to keep track of which is which):\n>>> ms_list = [\"15:09.123\", \"15:09.234\", \"15:09.522\", \"15:09.621\", \"15:10.123\", \"15:11.123\", \"15:12.123\", \"15:...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074174517_python_python_3.x.txt
Q: What does it mean when an array is used to index an array in python? I have a snippit of code as follows: y = np.array(self.unique_y) random_indices = self.random_generator.integers(0,len(self.unique_y), size=5) return y[random_indices] unique_y is simply an 1D array of [0 1 2]. My understanding of in...
What does it mean when an array is used to index an array in python?
I have a snippit of code as follows: y = np.array(self.unique_y) random_indices = self.random_generator.integers(0,len(self.unique_y), size=5) return y[random_indices] unique_y is simply an 1D array of [0 1 2]. My understanding of integers is that it produces an array, which is confirmed when I printed y a...
[ "Make a 1d array:\nIn [337]: y = np.arange(10)*10 \nIn [338]: y\nOut[338]: array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])\n\nand other array with values in the correct range (0 to 10):\nIn [339]: idx = np.array([2,5,0])\n\nSimply select the corresponding elements from y:\nIn [340]: y[idx]\nOut[340]: array([20, ...
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074174470_arrays_numpy_python.txt
Q: How to duplicate every occurrence of specific item in list A given list looks like this list = [1,2,3,4,5,6,4,0] I would like to duplicate every occurrence of 4 so the output looks like this: [1,2,3,4,4,5,6,4,4,0] I tried to do it like this: def dup(list): counter = 0 for value in list: if value ...
How to duplicate every occurrence of specific item in list
A given list looks like this list = [1,2,3,4,5,6,4,0] I would like to duplicate every occurrence of 4 so the output looks like this: [1,2,3,4,4,5,6,4,4,0] I tried to do it like this: def dup(list): counter = 0 for value in list: if value == 4: print(counter,value) list.insert(c...
[ "l = []\nfor n in nums:\n l.append(num)\n if n == 4:\n l.append(4)\n\nor inplace (you need to increment the counter twice)\ni = 0\nwhile i < len(nums):\n if nums[i] == 4:\n nums.insert(i, 4)\n i += 1\n i += 1\n\n" ]
[ 1 ]
[]
[]
[ "for_loop", "if_statement", "python" ]
stackoverflow_0074174583_for_loop_if_statement_python.txt
Q: 2-D list of strings in python? I need a 2D array to store strings of variable length. Numpy can do 2D arrays of strings but you need to pre-declare the length which is a bit of a hassle for the intended purpose. I thought that I can do x = [['']*rows]*columns but that does not work as intended, as illustrated by...
2-D list of strings in python?
I need a 2D array to store strings of variable length. Numpy can do 2D arrays of strings but you need to pre-declare the length which is a bit of a hassle for the intended purpose. I thought that I can do x = [['']*rows]*columns but that does not work as intended, as illustrated by the following snippet x = [['']*2]*...
[ "List comprehensions will work, they create unique lists:\nrows = 2\ncols = 2\nx = [['' for c in range(cols) ] for r in range(rows) ] \nprint(x)\nx[0][0] = 'a'\nprint(x)\n\nHere's the output:\n[['', ''], ['', '']]\n[['a', ''], ['', '']]\n\nThe problem with your code:\nx = [['']*rows]*columns\n\nis that the internal...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074174575_python_python_3.x.txt
Q: not sure what exactly is wrong I am new at python, probably as new as it gets. I am working on a simple python code for mpg and refactoring. I am not sure exactly what I am doing wrong. Its giving me a error on line 65, "in goodbye print("your miles per gallon:", mpg) name error name 'mpg' is not defined. any h...
not sure what exactly is wrong
I am new at python, probably as new as it gets. I am working on a simple python code for mpg and refactoring. I am not sure exactly what I am doing wrong. Its giving me a error on line 65, "in goodbye print("your miles per gallon:", mpg) name error name 'mpg' is not defined. any help would be appreciated. def main()...
[ "Your code has 2 problems.\n\nthe goodbye function needs to receive mpg as an argument\nyou need to do the inputs before calling goodbye(), and pass the function the mpg\n\nthe following lines of code should be before calling goodbye().\n# input\nmiles_driven = your_miles_driven()\ngallons_of_gas_used = gas_used()\...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074174468_python.txt
Q: Find duplicated word in string and in which two positions it appears I am fighting a bit with this problem. I want to write a code, which will find a duplicate word in a string from an input and print that word. Along with the word I also want to print the word positions in the given string. This is my code so far...
Find duplicated word in string and in which two positions it appears
I am fighting a bit with this problem. I want to write a code, which will find a duplicate word in a string from an input and print that word. Along with the word I also want to print the word positions in the given string. This is my code so far, but on the output I still get the word repeated. Any ideas how to fix it...
[ "\nI want to write a code, which will find a duplicate word in a string from an input and print that word. Along with the word I also want to print the word positions in the given string.\n\nTry the below\nfrom collections import defaultdict\n\ndata = defaultdict(list)\n_input = 'juice bread tea water apple tea car...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074174039_python.txt
Q: why is the blueprint route not found with a registered url_prefix I have a file that registers a blueprint and runs the app api/v1/app.py: #!/usr/bin/python3 """returns api status code""" from api.v1.views import app_views from flask import Flask from models import storage from os import getenv app = Flask(__nam...
why is the blueprint route not found with a registered url_prefix
I have a file that registers a blueprint and runs the app api/v1/app.py: #!/usr/bin/python3 """returns api status code""" from api.v1.views import app_views from flask import Flask from models import storage from os import getenv app = Flask(__name__) app.register_blueprint(app_views, url_prefix="/api/v1") @app.tea...
[ "You defined the prefix correctly. The problem here is because the file api/v1/views/index.py was never interpreted. If you add import api/v1/views/index.py in the file api/v1/app.py it will probably work\n" ]
[ 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074172756_flask_python.txt
Q: PyQt5 load only once an ui file I am generating QGroupBox on demand. To reduce the load in my disk and to save some time, I want to load the dataholder.ui after the first call from the disc into memory and after that always load that from memory. I already tried in my __init__ method to save the current instance i...
PyQt5 load only once an ui file
I am generating QGroupBox on demand. To reduce the load in my disk and to save some time, I want to load the dataholder.ui after the first call from the disc into memory and after that always load that from memory. I already tried in my __init__ method to save the current instance into a static variable, but I am getti...
[]
[]
[ "Ok tanks to @ekhumoro I was able to oad the .ui file into memory and setting up my gui with self.setupUi(self).\nIn ViewContainer.py\nfrom PyQt5.uic import loadUiType\n\nfrom Container import Container\n\nui_widget, _ = loadUiType(\"dataholder.ui\")\n\n\nclass ViewContainer(Container, ui_widget):\n def __init__...
[ -1 ]
[ "pyqt5", "python" ]
stackoverflow_0074173478_pyqt5_python.txt
Q: How can I best compare the frequency of categorical values from two datasets with Pandas? I am trying to compare two sets of data, each with a long list of categorical variables using Pandas and Matplotlib. I want to get and somehow store the frequency of values for each variable using the value_counts() method fo...
How can I best compare the frequency of categorical values from two datasets with Pandas?
I am trying to compare two sets of data, each with a long list of categorical variables using Pandas and Matplotlib. I want to get and somehow store the frequency of values for each variable using the value_counts() method for each data set so that I can later compare the two for statistically significant differences i...
[ "I think you could first transform your value_counts Series into a DataFrame and then merge it with the original.\nBelow you have an example of how to do that.\n\ntest_df = pd.DataFrame(\n {\n 'id': [1, 2, 3, 4],\n 'eye_colour': ['blue', 'brown', 'brown', 'green'],\n 'city': ['Paris', 'Paris...
[ 0 ]
[]
[]
[ "dataframe", "matplotlib", "pandas", "python" ]
stackoverflow_0074174473_dataframe_matplotlib_pandas_python.txt
Q: ADB Method freezes with python adb.devices() I have installed adb through android studio and connected bluestack properly, and if I run with cmd: adb shell input touchscreen swipe x x x x y its working fine . Now this is my code to connect to bluestack with my python app: from ppadb.client import Client adb = C...
ADB Method freezes with python adb.devices()
I have installed adb through android studio and connected bluestack properly, and if I run with cmd: adb shell input touchscreen swipe x x x x y its working fine . Now this is my code to connect to bluestack with my python app: from ppadb.client import Client adb = Client(host='127.0.0.1', port=5555) devices = adb.d...
[ "\nI also faced the same and then from this ticket\nhttps://github.com/Swind/pure-python-adb/issues/50\nI found ppadb\nlooks for 5037 port.\nSo I used subprocess to forward my memu port 21503 to 5037\n\nNote: to run adb command in subprocess you need to add adb path to your environment vairables path\nimport ppadb\...
[ 0 ]
[]
[]
[ "adb", "freeze", "python" ]
stackoverflow_0068521972_adb_freeze_python.txt
Q: Looping Through a List and a List of Lists in Parallel (Python) I'm trying to create a function that takes 2 parameters; the first one is a list of strings while the second parameter is a list of lists of strings. The aim of the function is to take nth index of the first parameter and creates a dictionary that ass...
Looping Through a List and a List of Lists in Parallel (Python)
I'm trying to create a function that takes 2 parameters; the first one is a list of strings while the second parameter is a list of lists of strings. The aim of the function is to take nth index of the first parameter and creates a dictionary that assigns the nth index of the first parameter as the key, and assigns it ...
[ "Use zip while iterating along each sublist.\ndef list_dic_gen(l1, l2):\n res = []\n for l in l2:\n res.append(dict(zip(l1, l)))\n return res\n\nexamples = (['One','Two'], [['First','Second']]), (['Second'], [['One'],['Third Fourth']])\nfor l1, l2 in examples:\n o = list_dic_gen(l1, l2)\n prin...
[ 1 ]
[]
[]
[ "list", "nested_lists", "python", "python_3.x" ]
stackoverflow_0074174218_list_nested_lists_python_python_3.x.txt
Q: For every pandas dataframe column with 'phone', remove non-numerals I have a python dataframe (df) created from a csv. I want to take every column name that contains 'PHONE' (or 'phone' or 'Phone') and change all their rows to be in the format of 5555555555. So: (555) 555-5555 would be 5555555555, 555-555-5555 wou...
For every pandas dataframe column with 'phone', remove non-numerals
I have a python dataframe (df) created from a csv. I want to take every column name that contains 'PHONE' (or 'phone' or 'Phone') and change all their rows to be in the format of 5555555555. So: (555) 555-5555 would be 5555555555, 555-555-5555 would be 5555555555, and so on. I tried the following, but got a syntax erro...
[ "Use filter to select the columns with \"phone\" (in a case-insensitive way using the (?i)phone regex) and apply with str.replace to remove the non-digits, finally update the DataFrame in place.\ndf.update(df.filter(regex='(?i)phone').apply(lambda s: s.str.replace(r'\\D+', '', regex=True)))\n\nExample:\n# before\n ...
[ 1, 1, 1 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074174606_csv_dataframe_pandas_python.txt
Q: Change days to int without pandas in python Is there any way to convert the resulting days into INT without pandas? Or use the number of days to do "for" loop? from datetime import datetime, timedelta d = datetime.today() - timedelta(days=10) date = datetime.today() - d print(date) Result: 10 days, 0:00:00 If...
Change days to int without pandas in python
Is there any way to convert the resulting days into INT without pandas? Or use the number of days to do "for" loop? from datetime import datetime, timedelta d = datetime.today() - timedelta(days=10) date = datetime.today() - d print(date) Result: 10 days, 0:00:00 If I try for loop, it doesn't work. for days in ran...
[ "When you subtract two datetime.datetime objects, the result is a datetime.timedelta. Check out the linked docs page for more information. From the docs:\n\nInstance attributes (read-only):\n\n\n\n\nAttribute\nValue\n\n\n\n\ndays\nBetween -999999999 and 999999999 inclusive\n\n\nseconds\nBetween 0 and 86399 inclusiv...
[ 1 ]
[ "You could try\n\"astype\"\ndate = date.astype(int)\n\n" ]
[ -1 ]
[ "datetime", "for_loop", "python" ]
stackoverflow_0074174622_datetime_for_loop_python.txt
Q: Deleting elements from an external JSON file in python I'm still learning python, and I'm writing a classic password manager app. It uses an external JSON file to store the data: { "info": [ { "website_url": "1", "username": "1", "password": "1" }, { "website_url": "2", ...
Deleting elements from an external JSON file in python
I'm still learning python, and I'm writing a classic password manager app. It uses an external JSON file to store the data: { "info": [ { "website_url": "1", "username": "1", "password": "1" }, { "website_url": "2", "username": "2", "password": "2" }, ...
[ "You have to deserialize your json file to a Python object, delete the entry from it and after serialize the object to the same file, so rewriting the content. In your case you json file does not coincide with a json array but it is an json object that contains a json array labelled with \"info\", so you have to ex...
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074174231_json_python.txt
Q: Sort filename (date and time) in increasing order I have the following list - ['ABC_20220816_21:50:07:UTC.pcap', 'ABC_20220816_17:05:23:UTC.pcap', 'ABC_20220816_18:06:10:UTC.pcap', 'ABC_20220816_17:10:23:UTC.pcap', 'ABC_20220816_16:45:05:UTC.pcap', 'ABC_20220816_19:07:30:UTC.pcap', 'ABC_20220816_21:19:08:UTC.pcap'...
Sort filename (date and time) in increasing order
I have the following list - ['ABC_20220816_21:50:07:UTC.pcap', 'ABC_20220816_17:05:23:UTC.pcap', 'ABC_20220816_18:06:10:UTC.pcap', 'ABC_20220816_17:10:23:UTC.pcap', 'ABC_20220816_16:45:05:UTC.pcap', 'ABC_20220816_19:07:30:UTC.pcap', 'ABC_20220816_21:19:08:UTC.pcap', 'ABC_20220816_19:37:48:UTC.pcap', 'ABC_20220816_20:13...
[ "use:\nimport dateutil.parser as dparser\nfrom datetime import datetime\na=['ABC_20220816_21:50:07:UTC.pcap', 'ABC_20220816_17:05:23:UTC.pcap', 'ABC_20220816_18:06:10:UTC.pcap', 'ABC_20220816_17:10:23:UTC.pcap', 'ABC_20220816_16:45:05:UTC.pcap', 'ABC_20220816_19:07:30:UTC.pcap', 'ABC_20220816_21:19:08:UTC.pcap', 'A...
[ 0 ]
[]
[]
[ "datetime", "python", "python_datetime", "sorting" ]
stackoverflow_0074174621_datetime_python_python_datetime_sorting.txt
Q: Generate colors of noise in Python I would like to use Python to generate different colors of noise, just like Wikipedia mentions : https://en.wikipedia.org/wiki/Colors_of_noise. For example, White, Pink, Brownian, Blue and Violet noise. And would like to have similar spectrums just like the website. It would be a...
Generate colors of noise in Python
I would like to use Python to generate different colors of noise, just like Wikipedia mentions : https://en.wikipedia.org/wiki/Colors_of_noise. For example, White, Pink, Brownian, Blue and Violet noise. And would like to have similar spectrums just like the website. It would be a great help if I could just adjust a few...
[ "Let's use numpy to compute the noise and matplotlib to plot the results\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef plot_spectrum(s):\n f = np.fft.rfftfreq(len(s))\n return plt.loglog(f, np.abs(np.fft.rfft(s)))[0]\n\n\nThis is a good use case for a python decorator\ndef noise_psd(N, psd = lam...
[ 11, 3, 0 ]
[]
[]
[ "audio", "python", "signal_processing" ]
stackoverflow_0067085963_audio_python_signal_processing.txt
Q: List files ONLY in the current directory In Python, I only want to list all the files in the current directory ONLY. I do not want files listed from any sub directory or parent. There do seem to be similar solutions out there, but they don't seem to work for me. Here's my code snippet: import os for subdir, dirs, ...
List files ONLY in the current directory
In Python, I only want to list all the files in the current directory ONLY. I do not want files listed from any sub directory or parent. There do seem to be similar solutions out there, but they don't seem to work for me. Here's my code snippet: import os for subdir, dirs, files in os.walk('./'): for file in files:...
[ "Just use os.listdir and os.path.isfile instead of os.walk.\nExample:\nimport os\nfiles = [f for f in os.listdir('.') if os.path.isfile(f)]\nfor f in files:\n # do something\n\n\nBut be careful while applying this to other directory, like\nfiles = [f for f in os.listdir(somedir) if os.path.isfile(f)]\n\nwhich wo...
[ 510, 85, 28, 15, 14, 7, 4, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0011968976_python.txt
Q: How do I set http errors in fast api for this code? I have created a table class and schema for sql table and I want to return an error with a status code. Can you tell me where I went wrong? @app.get("/employees", response_model=List[EmployeeSchema]) async def read_data(conn:LegacyCursorResult=Depends(get_db))...
How do I set http errors in fast api for this code?
I have created a table class and schema for sql table and I want to return an error with a status code. Can you tell me where I went wrong? @app.get("/employees", response_model=List[EmployeeSchema]) async def read_data(conn:LegacyCursorResult=Depends(get_db)): temp = conn.execute("select * from Employee;") re...
[ "How about using 404 insterad of status.HTTP_404_NOT_FOUND\n@app.get(\"/employees\", response_model=List[EmployeeSchema])\n async def read_data(conn:LegacyCursorResult=Depends(get_db)):\n temp = conn.execute(\"select * from Employee;\")\n results_as_dict = temp.mappings().all()\n print(results_as_dict)\n ...
[ 0 ]
[]
[]
[ "fastapi", "python" ]
stackoverflow_0074174702_fastapi_python.txt
Q: Finding subsets in list with specific value I have a list with values: i_have = [1,1,1,4,4,4,4,4,4,4,1,1,1,1,4,4,4,4,3,3,4,3] and I need to find the start and end indices for every chunk of the list with the value 4. If there's a 4 alone, like the second to last value of this list, its start and end indices shoul...
Finding subsets in list with specific value
I have a list with values: i_have = [1,1,1,4,4,4,4,4,4,4,1,1,1,1,4,4,4,4,3,3,4,3] and I need to find the start and end indices for every chunk of the list with the value 4. If there's a 4 alone, like the second to last value of this list, its start and end indices should be the same. i_need = [(3, 9), (14, 17), (20, 2...
[ "l = [1,1,1,4,4,4,4,4,4,4,1,1,1,1,4,4,4,4,3,3,4,3]\nu = []\nc = 0\nstart = None\nend = None\nfor num, item in enumerate(l):\n if item == 4:\n if c == 0:\n start = num\n c +=1\n if num == len(l)-1:\n end = num\n else:\n if c != 0:\n end = num- 1\n ...
[ 0, 0 ]
[]
[]
[ "algorithm", "list", "python" ]
stackoverflow_0074174515_algorithm_list_python.txt
Q: Wait until loader disappears python selenium <div id="loader-mid" style="position: absolute; top: 118.5px; left: 554px; display: none;"> <div class="a">Loading</div> <div class="b">please wait...</div> </div> And want to wait until it disappears. I have following code but it wait sometimes too long and at...
Wait until loader disappears python selenium
<div id="loader-mid" style="position: absolute; top: 118.5px; left: 554px; display: none;"> <div class="a">Loading</div> <div class="b">please wait...</div> </div> And want to wait until it disappears. I have following code but it wait sometimes too long and at some point of code it suddenly freeze all process...
[ "Reiterated your answer (with some error handling) to make it easier for people to find the solution :)\nImporting required classes:\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nConfigurat...
[ 36, 8, 1, 0 ]
[]
[]
[ "python", "selenium_webdriver" ]
stackoverflow_0026086965_python_selenium_webdriver.txt
Q: How to change range of xaxis in Plotly? I need to change the x-axis of this chart. The dataframe has time data per day, from 2012 to October 2022. I want to be able to see in the xaxis all the years and the chart shows me only every 2 years. import plotly.express as px fig = px.line(data_SPY, y=['Close'], line_s...
How to change range of xaxis in Plotly?
I need to change the x-axis of this chart. The dataframe has time data per day, from 2012 to October 2022. I want to be able to see in the xaxis all the years and the chart shows me only every 2 years. import plotly.express as px fig = px.line(data_SPY, y=['Close'], line_shape='linear', color_discrete_sequence=["#...
[ "You'd need to specify the dtick.\nfig.update_xaxes(dtick='Y1')\n\n" ]
[ 0 ]
[]
[]
[ "plotly", "plotly_python", "python" ]
stackoverflow_0074174571_plotly_plotly_python_python.txt
Q: How to compare one set of data to another and choose the smallest degree value? I have a code for determining some value by two methods. My data is in dataframe and I choose two time intervals and by changing the times within these two time intervals and find the smallest degree value. My data is in following form...
How to compare one set of data to another and choose the smallest degree value?
I have a code for determining some value by two methods. My data is in dataframe and I choose two time intervals and by changing the times within these two time intervals and find the smallest degree value. My data is in following form: It's just an example. df: epoch r1 r2 r3 2020-07-07T08:...
[ "Well, here are some pointers towards a mechanical answer to the question. It feels unsatisfying because I still don't fully understand what the higher objective function is that we want to optimize.\nMy understanding so far is that a df is given, containing a time series of points in 3 dimensions. The OP wants to ...
[ 2 ]
[]
[]
[ "dataframe", "loops", "pandas", "python" ]
stackoverflow_0074173731_dataframe_loops_pandas_python.txt
Q: Counting down the user inputs Basic python learning: I am asked to write a program that makes a list of 15 integer entries (size) the user inputs. For each input, the program should give the number of integers remaining to input. In the end, the program should list the 15 entries, and tell the user he is done. Wit...
Counting down the user inputs
Basic python learning: I am asked to write a program that makes a list of 15 integer entries (size) the user inputs. For each input, the program should give the number of integers remaining to input. In the end, the program should list the 15 entries, and tell the user he is done. With the code below, I get the list an...
[ "One thing to figure out is \"what to do if the user inputs something that is not a valid integer?\" You can solve that by keeping asking the user for an input until it's a valid number.\nYou can do that using a while loop with a boolean variable:\ngood_int = False\nwhile not good_int:\n try:\n num = int(...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074174637_loops_python.txt
Q: How can I check if an element is available, then click it? i just want the while statement displayed and selenium clicks selenium have to follow the below code, Thank you in advance. while (driver.find_element(By.CLASS_NAME, 'area is-available').click()): driver.find_element(By.XPATH, '/html/body/div[3]...
How can I check if an element is available, then click it?
i just want the while statement displayed and selenium clicks selenium have to follow the below code, Thank you in advance. while (driver.find_element(By.CLASS_NAME, 'area is-available').click()): driver.find_element(By.XPATH, '/html/body/div[3]/div[1]/div/div/article[1]/div/section[2]/label[2]/div[2]/span')...
[ "From what I've gathered, you're trying to check if the element is shown, your attempt was close, but not proper.\nHere is the proper way to check if an element exists, then click it. Only using your method.\nfrom selenium.common.exceptions import NoSuchElementException \n\ndef check_element_exists_by_class_name(fu...
[ 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074160978_python_selenium.txt
Q: How to allow a user a specified amount of time on a python program Im pretty independent when using oython since i wouldnt consider myself a beginner etc, but Iv been coding up a program that I want to sell. The problem is that I want the program to have a timer on it and when it runs out the program will no longe...
How to allow a user a specified amount of time on a python program
Im pretty independent when using oython since i wouldnt consider myself a beginner etc, but Iv been coding up a program that I want to sell. The problem is that I want the program to have a timer on it and when it runs out the program will no longer work. Giving the user a specified amount of time they have to use the ...
[ "You will want to run your program from another program using multithreading or asynchronous stuff. If you are looking for a single thing to send to your program (here, an interruption signal), then you should take a look at the signal built in package (for CPython).\n(based on this answer from another post)\n", ...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074174709_python.txt
Q: preparing ANOVA table in pandas Suppose I have a data frame df column A column B column C large prom2 34 large prom1 21 large prom1 12 large prom2 8 medium prom2 5 medium prom1 7 medium prom1 12 medium prom2 12 small prom1 16 small ...
preparing ANOVA table in pandas
Suppose I have a data frame df column A column B column C large prom2 34 large prom1 21 large prom1 12 large prom2 8 medium prom2 5 medium prom1 7 medium prom1 12 medium prom2 12 small prom1 16 small prom1 14 small prom2 1...
[ "You are looking for pd.DataFrame.pivot():\nWorking minimal example for your use case is:\ndf = pd.DataFrame([['large', 'prom2', 34], ['large', 'prom1', 21]], columns=['column A', 'column B', 'column C'])\ndf = df.pivot_table(index='column A', columns=['column B'], values='column C').reset_index().rename_axis(None,...
[ 0 ]
[]
[]
[ "anova", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074174524_anova_dataframe_group_by_pandas_python.txt
Q: Python: Loop to check if an input is valid or not line by line Given the following inputs that simulate a grid with the respective dimensions: totLines = int(input("Indicate the number os lines: ")) totColunms = int(input("Indicate the number of columns: ")) I want to check whether the input is valid or not (ever...
Python: Loop to check if an input is valid or not line by line
Given the following inputs that simulate a grid with the respective dimensions: totLines = int(input("Indicate the number os lines: ")) totColunms = int(input("Indicate the number of columns: ")) I want to check whether the input is valid or not (every digit must be between 0 and 20). The code should check each line o...
[ "I'd suggest putting the logic to get a valid list of moves in its own function, using all() to test all the values in the list (you don't need the current value of lin or anything else in the main loop to figure this out, and putting this task in its own function makes it easier to focus on it without accidentally...
[ 0, 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074174476_loops_python.txt
Q: Save python log in a file is not real time In bash I can run something like this .... ~> ping google.com >> log.txt In log.txt: PING google.com (216.239.38.120) 56(84) bytes of data. 64 bytes from any-in-2678.1e100.net (216.239.38.120): icmp_seq=1 ttl=104 time=64.2 ms 64 bytes from any-in-2678.1e100.net (216.239...
Save python log in a file is not real time
In bash I can run something like this .... ~> ping google.com >> log.txt In log.txt: PING google.com (216.239.38.120) 56(84) bytes of data. 64 bytes from any-in-2678.1e100.net (216.239.38.120): icmp_seq=1 ttl=104 time=64.2 ms 64 bytes from any-in-2678.1e100.net (216.239.38.120): icmp_seq=2 ttl=104 time=61.5 ms ... (r...
[ "It looks like stdout is not being flushed often enough. Usually it's not a big problem, but if it's important to you, try adding flush=True to your print calls or running python with -u flag to force stdin/stdout to be unbuffered.\nRelated question: How can I flush the output of the print function?\n" ]
[ 1 ]
[]
[]
[ "bash", "buffer", "io_redirection", "python" ]
stackoverflow_0074174603_bash_buffer_io_redirection_python.txt
Q: How to fix exception 404 in Django views? I'm following this tutorial:https://www.w3schools.com/django/django_views.php After copying all the code to create the members and admin views I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in...
How to fix exception 404 in Django views?
I'm following this tutorial:https://www.w3schools.com/django/django_views.php After copying all the code to create the members and admin views I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in myworld.urls, Django tried these URL patterns,...
[ "In your project urls.py you set the path to the members app to use 127.0.0.1:8000/members\nIn order to navigate to 127.0.0.1:8000/members using the default route, you need to change the path to look like this :\npath('', include('members.urls')),\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0074174813_django_django_views_python.txt
Q: 'str' object is not callable Django Rest Framework I'm trying to create an API view but I'm getting an error. Can anyone help? urls.py: app_name = 'ads' urlpatterns = [ # ex: /ads/ url(r'^$', views.ListBrand.as_view(), name='brand_list'), ] views.py: from rest_framework.views import APIView from rest_fram...
'str' object is not callable Django Rest Framework
I'm trying to create an API view but I'm getting an error. Can anyone help? urls.py: app_name = 'ads' urlpatterns = [ # ex: /ads/ url(r'^$', views.ListBrand.as_view(), name='brand_list'), ] views.py: from rest_framework.views import APIView from rest_framework.response import Response from . import models from...
[ "My problem was in my settings.py file:\nDiff:\n REST_FRAMEWORK = {\n- 'DEFAULT_AUTHENTICATION_CLASSES': {\n+ 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.SessionAuthentication',\n- }\n+ ),\n- 'DEFAULT_PERMISSION_CLASSES': {\n+ 'DEFAULT_P...
[ 19, 9, 1, 0 ]
[]
[]
[ "django", "django_rest_framework", "python", "python_3.x" ]
stackoverflow_0039923384_django_django_rest_framework_python_python_3.x.txt
Q: Why is my queue.get() stuck on infinite loop when I try to load for second time? I am trying to run two functions simultaneously, and return from them their outputs. I have written the following code, but it only works to retrieve the output from either q1 or q2 once, but when I try a second time, I get stuck on a...
Why is my queue.get() stuck on infinite loop when I try to load for second time?
I am trying to run two functions simultaneously, and return from them their outputs. I have written the following code, but it only works to retrieve the output from either q1 or q2 once, but when I try a second time, I get stuck on an infinite loop. I do not understand why. from threading import Thread from multiproce...
[ "You created 2 queues q1 and q2, and according to what you said you only do q1.get() and you try to do is twice while what you need to do is:\nprint(q1.get())\nprint(q2.get())\n\nOr you can use 1 queue and then you can do q1.get() twice.\n" ]
[ 1 ]
[]
[]
[ "multiprocessing", "multithreading", "python", "python_multiprocessing", "queue" ]
stackoverflow_0074174873_multiprocessing_multithreading_python_python_multiprocessing_queue.txt
Q: Histogram of sums using groupby (Pandas) I have a data frame of transactions that contains a customer ID and gross amount spent. I was able to see how much each unique customer has spent over their lifetime by using merged_df.gross.groupby(merged_df['customer_id']).sum() I would like to create a histoplot to see ...
Histogram of sums using groupby (Pandas)
I have a data frame of transactions that contains a customer ID and gross amount spent. I was able to see how much each unique customer has spent over their lifetime by using merged_df.gross.groupby(merged_df['customer_id']).sum() I would like to create a histoplot to see how many customers have spent xx amount of dol...
[ "Try adding as_index = False in the groupby, so that you have a new df with the customer_id and the gross sum like columns, like this:\nimport pandas as pd\ndata = {\n \"customer\": [1,2,3,4,2,1,3,1],\n \"gross\": [10,20,10,15,20,15,30,40]\n } \ndf = pd.DataFrame(data=data)\n# Here is where you add the as_...
[ 0 ]
[]
[]
[ "group_by", "matplotlib", "pandas", "python" ]
stackoverflow_0074174777_group_by_matplotlib_pandas_python.txt
Q: Why appending is returning None I'm trying to swap keys and values, and append the keys if the values are duplicated. But When trying to append the result is None. def swap_keys_and_values(d): new_d = {} for k, v in d.items(): if new_d.get(v): print(new_d.get(v), k) print(ne...
Why appending is returning None
I'm trying to swap keys and values, and append the keys if the values are duplicated. But When trying to append the result is None. def swap_keys_and_values(d): new_d = {} for k, v in d.items(): if new_d.get(v): print(new_d.get(v), k) print(new_d.get(v).append(k)) new...
[ ".append() is an in-place operation, it modifies the object it is called on.\nSome in-place operations will return the object itself (and this is desirable for allowing method-chaining), but the basic list methods of Python do not have this behaviour (favouring speed and minimalism over usability for programmers).\...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074174649_python.txt
Q: How can I record the score to a file and recall it with Python I'm doing a mini project for a short course and I've done all the required bits as well as some of the optional tasks. For something a little extra I wanted to work out how to write the score to a file and be able to recall it later. I'm just not sure ...
How can I record the score to a file and recall it with Python
I'm doing a mini project for a short course and I've done all the required bits as well as some of the optional tasks. For something a little extra I wanted to work out how to write the score to a file and be able to recall it later. I'm just not sure how I would go about this. Below is what i've got so far any help to...
[ "Apart from what @mkrieger1 has suggested about using internal Python Read and Write functions.\nI would suggest use Pandas library and export the data into csv like format\nimport pandas as pd\n\ndata = {\n'Your Stat': my_stat, \n'Your Score' : my_score,\n'Opponent Stat': opponent_stat,\n'Opponent Score': opponent...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074174824_python.txt
Q: generate list of length M=10000 with two randomly ordered variables i am a little confused on how to generate with the ramdom function in python a list of length 10000 that randomly repeats the same 2 variables. Suppose once the randomly generated list is [a,b,a,a,a,a,b,b....] and the next time it renders [b,a,b,b...
generate list of length M=10000 with two randomly ordered variables
i am a little confused on how to generate with the ramdom function in python a list of length 10000 that randomly repeats the same 2 variables. Suppose once the randomly generated list is [a,b,a,a,a,a,b,b....] and the next time it renders [b,a,b,b,a,a,b,b...]. Can anyone help me on this one?
[ "You can create a function the receives the desired length of the list and 2 characters, and randomly fills the list with the 2 characters.\nfor example:\nimport random\n\n\ndef generate_random_list(length: int, char1: str, char2: str) -> list[str]:\n return [char1 if random.randint(1, 2) == 1 else char2 for _ i...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074174623_python.txt
Q: Converting Set(float) into float/int I have this df and trying to clean it. How to convert irs_pop,latitude,longitude and fips in real floats and ints? The code below returns float() argument must be a string or a real number, not 'set' mask['latitude'] = mask['latitude'].astype('float64') mask['longitude'] = mas...
Converting Set(float) into float/int
I have this df and trying to clean it. How to convert irs_pop,latitude,longitude and fips in real floats and ints? The code below returns float() argument must be a string or a real number, not 'set' mask['latitude'] = mask['latitude'].astype('float64') mask['longitude'] = mask['irs_pop'].astype('float64') mask['irs_p...
[ "You would need to convert to tuple/list and to slice with str:\ndf['col'] = df['col'].agg(tuple).str[0]\n\nExample:\ndf = pd.DataFrame({'col': [{1},{2,3},{}]})\ndf['col2'] = df['col'].agg(tuple).str[0]\n\nOutput:\n col col2\n0 {1} 1.0\n1 {2, 3} 2.0 # this doesn't seem to be the case in your data\n2 ...
[ 0, 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074174781_dataframe_pandas_python_python_3.x.txt
Q: I want to make password generator loop with python I am trying to code a program which generates random passwords and saves it to a text file. I want program to keep running until it saves 100 random passwords to text file. I have created the password generator But whenever i try to save password its saves same pa...
I want to make password generator loop with python
I am trying to code a program which generates random passwords and saves it to a text file. I want program to keep running until it saves 100 random passwords to text file. I have created the password generator But whenever i try to save password its saves same password again and again. Can anyone help me to make a loo...
[ "You are probably using the same seed for your random function each time. Random functions in programming are deterministic: they will generate the same pseudo-random sequence every time you have the same starting conditions. To get a new sequence change the seed of the random function, which changes the starting c...
[ 0, 0 ]
[]
[]
[ "automation", "python" ]
stackoverflow_0074169277_automation_python.txt
Q: Python input() function is skipping a line on the first input I'am trying to make a text-adventure but i encountered a weird problem that I can't solve. I dont know what I've changed because I know it worked at some point but the startinput doesn't take the first user input and skipps to the next line so for examp...
Python input() function is skipping a line on the first input
I'am trying to make a text-adventure but i encountered a weird problem that I can't solve. I dont know what I've changed because I know it worked at some point but the startinput doesn't take the first user input and skipps to the next line so for example I want to write "start" but what appears is: "-> tart" This is t...
[ "It works fine (tested locally)\ndef logo():\n print(\"---------------------------------------------------------------------------------------------------------\\n ▄▄ \\n▀████▀ █ ▀███▀ ...
[ 0 ]
[]
[]
[ "input", "python", "user_input" ]
stackoverflow_0074174976_input_python_user_input.txt
Q: pyspark to_date convert returning null for invalid dates I am trying to convert a string column to date using to_date. Everything is working fine, however, my requirement is to fail the spark job if there is any bad data, that is, any malformed input for date. Currently, to_date is returning null, but not falling....
pyspark to_date convert returning null for invalid dates
I am trying to convert a string column to date using to_date. Everything is working fine, however, my requirement is to fail the spark job if there is any bad data, that is, any malformed input for date. Currently, to_date is returning null, but not falling. How to make sure that job will be failed in such scenario?
[ "The behavior of the to_date function is dependent on the spark.sql.ansi.enabled Spark option.\nWhen it is disabled (the default), Spark uses a Hive compliant dialect and returns null results instead of failing.\nConversely, if enabled, Spark will be ANSI compliant and will fail if the input is malformed as stated ...
[ 1 ]
[]
[]
[ "apache_spark", "date", "pyspark", "python", "python_3.x" ]
stackoverflow_0074174461_apache_spark_date_pyspark_python_python_3.x.txt
Q: Kivy canvas doesn't fit to the parent layout I am trying to make a trial canvas (having just yellow rectangle as bounding box) which should fit to the parent layout (in this case FloatLayout). At the beginning, the canvas is created at [0,0] of size [100,100]. 2) If I resize by dragging the App window corners, th...
Kivy canvas doesn't fit to the parent layout
I am trying to make a trial canvas (having just yellow rectangle as bounding box) which should fit to the parent layout (in this case FloatLayout). At the beginning, the canvas is created at [0,0] of size [100,100]. 2) If I resize by dragging the App window corners, the canvas resizes well. However, 3) & 4) if I maxim...
[ "The problem is that you want the rectangle size to follow the FloatLayout size, but your on_size() is triggered by changes in the size of TestOut. One easy fix is to just remove the canvas drawing from the python and put the rectangle in the kv, like this:\n FloatLayout:\n id: can\n canvas:\n ...
[ 1 ]
[]
[]
[ "kivy", "python" ]
stackoverflow_0074174545_kivy_python.txt
Q: Django Error: 'dict' object has no attribute 'availability' I have a cart view where I'm trying to check if the products added to the cart have even one item in the list that has product.availability set to False and work accordingly in Template, the problem is with accessing the product availability in cart objec...
Django Error: 'dict' object has no attribute 'availability'
I have a cart view where I'm trying to check if the products added to the cart have even one item in the list that has product.availability set to False and work accordingly in Template, the problem is with accessing the product availability in cart object list, So how do I check the availability of products that peopl...
[ "Instead of creating an ad-hoc dict that does have the necessary availability attribute, you should simply return a QuerySet of Product objects after filtering products by IDs:\ndef cookieCart(request):\n try:\n cart = json.loads(request.COOKIES['cart'])\n except:\n cart = {}\n return {\"item...
[ 1, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074137858_django_python.txt
Q: Inherit a custom user models fields from parent class to a child class between two different applications Hello kings and queens! I'm working on a project and got stuck on a (for me) complicated issue. I have one model (generalpage.models) where all the common info about the users is stored. In a different app (pr...
Inherit a custom user models fields from parent class to a child class between two different applications
Hello kings and queens! I'm working on a project and got stuck on a (for me) complicated issue. I have one model (generalpage.models) where all the common info about the users is stored. In a different app (profilesettings), I have an app where all profile page related functions will be coded. I tried to inherit the mo...
[ "Maybe i'm misunderstanding the issue at hand but to me it sounds like you would want to have a OneToOne key on your profilesettings.UserProfile to your generalpage.user. I'm assuming every user have their own unique profilesettings.\nfrom django.conf import settings \n\nclass UserProfile(User):\n user(mo...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074174619_django_django_models_python.txt
Q: How to Left Strip Only "one" Zero from string in Python I have a string of numbers in this format "IIDDDDDDDD" where "I" are the integers and "D" are the decimals and the string always contains 10 numbers. I need to format it as II.DDDDDDDD but some times after formatting the number is eg: 00.12345678. I tried usi...
How to Left Strip Only "one" Zero from string in Python
I have a string of numbers in this format "IIDDDDDDDD" where "I" are the integers and "D" are the decimals and the string always contains 10 numbers. I need to format it as II.DDDDDDDD but some times after formatting the number is eg: 00.12345678. I tried using .lstrip('0') but it removes both zeros before the decimal ...
[ "Although it's unclear why you'd choose a representation like this to begin with (perhaps you didn't and you just have to work with it), the problem is very straightforward and so can the solution be:\nif df_operacoes['PU Parte'][:2] == '00':\n df_operacoes['PU Parte'] = df_operacoes['PU Parte'][1:] \n\nThere's ...
[ 0 ]
[]
[]
[ "format", "python", "strip" ]
stackoverflow_0074175044_format_python_strip.txt
Q: Python multiprocessing write to file with starmap_async() I'm currently setting up a automated simulation pipeline for OpenFOAM (CFD library) using the PyFoam library within Python to create a large database for machine learning purposes. The database will have around 500k distinct simulations. To run this pipelin...
Python multiprocessing write to file with starmap_async()
I'm currently setting up a automated simulation pipeline for OpenFOAM (CFD library) using the PyFoam library within Python to create a large database for machine learning purposes. The database will have around 500k distinct simulations. To run this pipeline on multiple machines, I'm using the multiprocessing.Pool.star...
[ "First, when your with multiprocessing.Pool(processes=nProcs) as pool: exits, there will be an implicit call to pool.terminate(), which will kill all pool processes and with it any running or queued up tasks. There is no point in calling queue.put('complete') since nobody is listening.\nSecond, your 'listener\" tas...
[ 0 ]
[]
[]
[ "multiprocessing", "openfoam", "python" ]
stackoverflow_0074167830_multiprocessing_openfoam_python.txt
Q: How can i give a drop down to a cell of a table using aggrid in strealite app using python? How can i add a drop down to a cell of a table created with or without using aggird inside a streamlite environment (python). Can somebody help on this. I need a drop down as "Long" or "Short" in the "Long/Short" column of ...
How can i give a drop down to a cell of a table using aggrid in strealite app using python?
How can i add a drop down to a cell of a table created with or without using aggird inside a streamlite environment (python). Can somebody help on this. I need a drop down as "Long" or "Short" in the "Long/Short" column of the table rather than a manual text input. I've been struggling for hours, can somebody help. Tha...
[ "I have not find a way to do it with AgGrid. However, why don't you try using a selectbox like the one you are using with \"Number of cells\"? Catch the values in the column and then pass those values to the selectbox, like:\nfilter_list = list(df[\"Long_Short\"].unique())\nselector = st.selectbox(\"Long_Short\", f...
[ 0 ]
[]
[]
[ "ag_grid", "python", "streamlit", "web_frontend" ]
stackoverflow_0073918849_ag_grid_python_streamlit_web_frontend.txt
Q: What do squared brackets do in this context in Python? I'm trying to understand a script in Python for an assignment but I don't know what square brackets mean when used in a variable's name. This is the code: import numpy as np if __name__ == "__main__": epsilonff = 94.45 sigmaff = 3.575 del...
What do squared brackets do in this context in Python?
I'm trying to understand a script in Python for an assignment but I don't know what square brackets mean when used in a variable's name. This is the code: import numpy as np if __name__ == "__main__": epsilonff = 94.45 sigmaff = 3.575 delta = 0.01*sigmaff L = 10*sigmaff rhob = 0.004959169...
[ "Square brackets are used in Python to index into or slice list-like objects. NumPy extends the base index functionality and allows boolean expressions to select subsets of its array objects. In your case, you are modifying every value in the array that satisfies the mask condition.\nSee the Python documentation:\n...
[ 1 ]
[]
[]
[ "brackets", "python" ]
stackoverflow_0074175068_brackets_python.txt
Q: Download data from a jupyter server I'm using ipython notebook by connecting to a server I don't know how to download a thing (data frame, .csv file,... for example) programatically to my local computer. Because I can't specific declare the path like C://user//... It will be downloaded to their machine not mine A...
Download data from a jupyter server
I'm using ipython notebook by connecting to a server I don't know how to download a thing (data frame, .csv file,... for example) programatically to my local computer. Because I can't specific declare the path like C://user//... It will be downloaded to their machine not mine
[ "Run this in separate cell in one of the notebooks:\n!tar cvfz zipname.tar.gz *\n\nTo cover more folders up the tree, write ../ before the * for every step up the directory.\ntar cvfz zipname.tar.gz ../../*\n\nThe file zipname.tar.gz will be saved in the same folder as your notebook.\nAlso if files size is too larg...
[ 24, 15, 14, 7, 0 ]
[]
[]
[ "download", "ipython", "jupyter", "jupyter_notebook", "python" ]
stackoverflow_0041627247_download_ipython_jupyter_jupyter_notebook_python.txt
Q: Is there a way to filter out a frequency? np.argmax function returns the highest frequency value and I want to take that value out and then see what the second highest value is. import wave import struct import matplotlib.pyplot as plt import numpy as np There is some code here but that just defines the data of t...
Is there a way to filter out a frequency?
np.argmax function returns the highest frequency value and I want to take that value out and then see what the second highest value is. import wave import struct import matplotlib.pyplot as plt import numpy as np There is some code here but that just defines the data of the sound wave and has nothing to do with my que...
[ "np.argmax() gives you the indices of the maximum values along some axis, see the documentation.\nYou subtract the indices from the values with:\nfrequency1 = frequencies - np.argmax(frequencies)\n\nInstead, you wanted to remove the values at these indices, and the obtain the maximum value in the remaining data:\ni...
[ 0 ]
[]
[]
[ "argmax", "python" ]
stackoverflow_0074175024_argmax_python.txt
Q: Python : How to store output of each process during multiprocessing in a list listJobRunIds = [] def run_job(dataset_date): command = START_JOB_RUN.format(dataset_date=dataset_date) jobRunId = execute(command=command) print("jobRunId:"+jobRunId) listJobRunIds.append(jobRunId) print(listJo...
Python : How to store output of each process during multiprocessing in a list
listJobRunIds = [] def run_job(dataset_date): command = START_JOB_RUN.format(dataset_date=dataset_date) jobRunId = execute(command=command) print("jobRunId:"+jobRunId) listJobRunIds.append(jobRunId) print(listJobRunIds) time.sleep(60) return jobRunId pool = multiprocessing.Pool() pool...
[ "If you want to process in groups of 3, split the list and then map. You could count wanted indexes by 3 and use that to pull sections.\npool = multiprocessing.Pool()\npool = multiprocessing.Pool(processes=3)\n\nlistJobRunDates = ['2022-10-01','2022-10-02','2022-10-03','2022-10-04'...]\n\nfor i in range(0, len(list...
[ 2 ]
[]
[]
[ "python", "python_multiprocessing" ]
stackoverflow_0074174901_python_python_multiprocessing.txt
Q: Django queryset with matches for multiple related objects My Model: class Pattern(models.Model): name = CICharField("Pattern Name", max_length=200, unique=True) symptoms = models.ManyToManyField(Symptom, through='PatternSymptom', related_name='patterns') tongue_colour = models.ManyToManyField(Color, ve...
Django queryset with matches for multiple related objects
My Model: class Pattern(models.Model): name = CICharField("Pattern Name", max_length=200, unique=True) symptoms = models.ManyToManyField(Symptom, through='PatternSymptom', related_name='patterns') tongue_colour = models.ManyToManyField(Color, verbose_name="Tongue Body Colour", blank=True, related_name='patt...
[ "You can use a Q-object in order to do a query with OR.\nfrom django.db.models import Q \n\nqueryset = Pattern.objects.filter(\n Q(symptoms__id__in=symptom) |\n Q(tongue_shape__id__exact=tongue_shape) |\n Q(tongue_colour__id__in=tongue_colour))\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_cms", "django_queryset", "django_rest_framework", "python" ]
stackoverflow_0074174749_django_django_cms_django_queryset_django_rest_framework_python.txt
Q: Pyspark: Effcient way for searching correct and plausible measurement data and take them as a new Dataframe I have a huge amount of data where I have a column with multiple products and two signals "ID" & "Value". The signal "ID" increases from 1-40 several times a day. For each ID I have a value. In this example ...
Pyspark: Effcient way for searching correct and plausible measurement data and take them as a new Dataframe
I have a huge amount of data where I have a column with multiple products and two signals "ID" & "Value". The signal "ID" increases from 1-40 several times a day. For each ID I have a value. In this example the data comes in 3 Hz and I only write down the IDs from 1-3 to make the table not to long. Product Date ID ...
[ "You can try spark function groupby then first\nfrom pyspark.sql import functions as F\ndf.groupby(\"ID\", \"Value\").agg(F.first(\"product\"), F.first(\"Date\")).show(10, False)\n\nOutput:\n+---+-----+--------------+-------------------+\n|ID |Value|first(product)|first(Date) |\n+---+-----+--------------+---...
[ 0, 0 ]
[]
[]
[ "apache_spark", "databricks", "dataframe", "pyspark", "python" ]
stackoverflow_0074151045_apache_spark_databricks_dataframe_pyspark_python.txt
Q: SQL Server: How to replicate pandas merge? How can I replicate Pandas merge in SQL server? I want to do this: # merge and filter out rows that are in "both" dataframes df1 = pd.DataFrame([ ['A', 1, 'c', 'a'], ['A', 2, 'c', 'a'], ['B', 2, 'c', 'a'], ['B', 3, 'c', 'a'...
SQL Server: How to replicate pandas merge?
How can I replicate Pandas merge in SQL server? I want to do this: # merge and filter out rows that are in "both" dataframes df1 = pd.DataFrame([ ['A', 1, 'c', 'a'], ['A', 2, 'c', 'a'], ['B', 2, 'c', 'a'], ['B', 3, 'c', 'a'], ['C', 3, 'c', 'a'], [...
[ "It looks like you are trying to select the rows that are in df1 or df2, but not both. On SQL Server, you can use the UNION, EXCEPT, and INTERSECT operators like this:\n(SELECT * FROM TableA\nUNION\nSELECT * FROM TableB)\nEXCEPT\n(SELECT * FROM TableA\n INTERSECT\n SELECT * FROM TableB)\n\nThe first three rows perf...
[ 1 ]
[]
[]
[ "pandas", "python", "sql" ]
stackoverflow_0074144445_pandas_python_sql.txt
Q: How do I create a for loop per customer to find the aggregated weightage of each campaign? I have the following DataFrame 'Table1' below that is missing the weightage column: Table1 I have customers that e-visit my business via different channels and each customer is attributed to a channel based on the number vis...
How do I create a for loop per customer to find the aggregated weightage of each campaign?
I have the following DataFrame 'Table1' below that is missing the weightage column: Table1 I have customers that e-visit my business via different channels and each customer is attributed to a channel based on the number visits per channel. So each channel gets a weighted score per customer (see Weightage column). I wo...
[ "Considering the lack of a reproducible example, I'll assume you have a pandas dataframe called df.\nIn order to perform the desired operations, you should use groupby.\nFirst use a group by Customer ID to create Table 1:\ntable1 = df.assign(Weightage = lambda df_: \n df_['Visits']/df_.groupby('Customer ID')['Vi...
[ 0 ]
[]
[]
[ "aggregate", "dataframe", "pandas", "python" ]
stackoverflow_0074171964_aggregate_dataframe_pandas_python.txt
Q: Breaking out of a recursive loop in python I've used a recursive loop to find path between words formed by one-letter changes. For example: MAN-->CUT MAN CAN CAT CUT The recursive function uses while to look at the one-letter neighbors of a word and find the neighbor that is most like the goal word. Then using t...
Breaking out of a recursive loop in python
I've used a recursive loop to find path between words formed by one-letter changes. For example: MAN-->CUT MAN CAN CAT CUT The recursive function uses while to look at the one-letter neighbors of a word and find the neighbor that is most like the goal word. Then using that word it goes deeper, up to a depth of two mo...
[ "The problem you're having is that while break (or an exception that you catch outside the loop, but within the same function) can only break out of the single loop, not the whole chain of loops that exist in the recursive call stack.\nThe second version of your code that you put in an answer works because the exce...
[ 2, 0, 0 ]
[]
[]
[ "exception", "python", "recursion" ]
stackoverflow_0074174842_exception_python_recursion.txt
Q: use a function at the result of pandas .loc Hy peeps, I wold like to know if have some possibility to use a function at the result of pandas .loc or if exist some better way to do it. So what I'm trying to do is: If the value in this series is =!0, then get the values of other rows and use as parameters for one fu...
use a function at the result of pandas .loc
Hy peeps, I wold like to know if have some possibility to use a function at the result of pandas .loc or if exist some better way to do it. So what I'm trying to do is: If the value in this series is =!0, then get the values of other rows and use as parameters for one function (in this case, get_working_days_delta), af...
[ "Hard to give a good answer without an example.\nBut I think the problem is that you need to filter before using apply.\nTry\ndf[df[\"SERIES\"] != 0].apply(...)\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074166376_pandas_python.txt
Q: Why is this singleton implementation "not thread safe"? 1. The @Singleton decorator I found an elegant way to decorate a Python class to make it a singleton. The class can only produce one object. Each Instance() call returns the same object: class Singleton: """ A non-thread-safe helper class to ease impl...
Why is this singleton implementation "not thread safe"?
1. The @Singleton decorator I found an elegant way to decorate a Python class to make it a singleton. The class can only produce one object. Each Instance() call returns the same object: class Singleton: """ A non-thread-safe helper class to ease implementing singletons. This should be used as a decorator -...
[ "I suggest you choose a better singleton implementation. The metaclass-based implementation is the most elegant in my opinion.\nAs for for thread-safety, neither your approach nor any of the ones suggested in the above link are thread safe: it is always possible that a thread reads that there is no existing instanc...
[ 24, 10, 3, 1 ]
[]
[]
[ "multithreading", "python", "python_3.6", "python_3.x", "singleton" ]
stackoverflow_0050566934_multithreading_python_python_3.6_python_3.x_singleton.txt