content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python code that creates list of prime numbers
Trying to create a list of prime numbers in a fixed range. This is producing non-sensical list but the code makes sense to me.
for number in range(2,100,2):
k = 1
while k*k < number:
k += 2
if number % k == 0:
break
else:
... | Python code that creates list of prime numbers | Trying to create a list of prime numbers in a fixed range. This is producing non-sensical list but the code makes sense to me.
for number in range(2,100,2):
k = 1
while k*k < number:
k += 2
if number % k == 0:
break
else:
print(number)
| [
"there are several bugs in your code.\nfirst, you don't check its divisibility by even numbers, any even number to be exact (including 2)! if it is meant as an optimization approach, make it more generic by not checking the numbers who are known already not to be prime. its called the sieve of eratosthenes\nanother... | [
3,
1,
0
] | [] | [] | [
"primes",
"python"
] | stackoverflow_0074186291_primes_python.txt |
Q:
PDF.JS and QtWebEngineWidgets: adjust page and viewrect in pdf after loading
I want to display a pdf with PDF.js and PyQt5.QtWebEngineWidgets. After loading the view should automatically focus on a given rectangle on a given page. The page and the rectangle can differ between each time the pdf is loaded.
I am able... | PDF.JS and QtWebEngineWidgets: adjust page and viewrect in pdf after loading | I want to display a pdf with PDF.js and PyQt5.QtWebEngineWidgets. After loading the view should automatically focus on a given rectangle on a given page. The page and the rectangle can differ between each time the pdf is loaded.
I am able to jump to a specific page by adding the a function jumpToView to the QWebEngineV... | [
"Jumping to the y-value of the rect, works with scrollPageIntoView. Depending on what kind of coordinates you have, you have to subtract from the total height of the page. The total function looks like this:\ndef jumpToView(self, page, rect):\n y = rect[1]\n js_script = \"\"\"function jumpToView(desiredPage, ... | [
0
] | [] | [] | [
"javascript",
"pdf",
"pdf.js",
"python",
"qwebengineview"
] | stackoverflow_0074181880_javascript_pdf_pdf.js_python_qwebengineview.txt |
Q:
Flask-SQLAlchemy pagination with keywords returns an empty list
I have an issue with flask paginate. Upon advice here at Stackoverflow I solved an initial paginate typeerror by changed my code so the paginate takes keywords. This gave me a new issue, since my code now returns an empty list of tickers.
The issue se... | Flask-SQLAlchemy pagination with keywords returns an empty list | I have an issue with flask paginate. Upon advice here at Stackoverflow I solved an initial paginate typeerror by changed my code so the paginate takes keywords. This gave me a new issue, since my code now returns an empty list of tickers.
The issue seems to be related to the implementation of paginate with keywords and... | [
"Solved it by using filter instead of filter_by, so code that works is as below:\n tickers = Ticker.query.filter(Ticker.exchange.contains('CPH')).paginate(page=page, per_page=app.config['TICKERS_PER_PAGE'], error_out=False)\n\n"
] | [
0
] | [] | [] | [
"filter",
"pagination",
"python",
"sqlalchemy"
] | stackoverflow_0074145770_filter_pagination_python_sqlalchemy.txt |
Q:
How to dynamically define an SQLModel class
Context
SQLModel is heavily based on Pydantic. The latter has the create_model function allowing you to create/define a model class at runtime, by passing the field definitions as arbitrary keyword arguments.
There seems to be no special version of the create_model funct... | How to dynamically define an SQLModel class | Context
SQLModel is heavily based on Pydantic. The latter has the create_model function allowing you to create/define a model class at runtime, by passing the field definitions as arbitrary keyword arguments.
There seems to be no special version of the create_model function built into SQLModel and there is no mention o... | [
"The answer is yes!\nThe create_model function has the optional __base__ parameter (as mentioned in the docs), which accepts any subclass (or sequence of subclasses) of the Pydantic BaseModel. The SQLModel base class happens to directly inherit from BaseModel and can thus be passed here.\nHowever, this is not suffi... | [
0
] | [] | [] | [
"orm",
"pydantic",
"python",
"sqlmodel"
] | stackoverflow_0074186458_orm_pydantic_python_sqlmodel.txt |
Q:
Extract day from date string in a list
How can I extract only the day from a list such as this?
date_data = [None, None, None, None, '2014-01-05', '2014-01-06', '2014-01-07', None, None, '2014-01-10']
I've tried a few different lambda functions such as:
Date_List = [d for y, m, d in map(lambda x: str(x).split('-'... | Extract day from date string in a list | How can I extract only the day from a list such as this?
date_data = [None, None, None, None, '2014-01-05', '2014-01-06', '2014-01-07', None, None, '2014-01-10']
I've tried a few different lambda functions such as:
Date_List = [d for y, m, d in map(lambda x: str(x).split('-'), date_data) if y != None if m != None if d... | [
"Based on your initial run though you could do this:\nDate_List = [x.split('-')[2] if x else None for x in date_data] \n\nwhich goes through the list elements and appends a none if the element is a none to begin with and if its an element then you can get the day\n",
"Once you've used strptime to get a datetime o... | [
2,
0,
0
] | [] | [] | [
"datetime",
"list",
"python",
"python_3.x",
"string"
] | stackoverflow_0074186403_datetime_list_python_python_3.x_string.txt |
Q:
Making changes in objects permanent
I'm trying to create a bar program, It's based on user inputs, classes and inheritance. This is my current code for the part not having to do with user input.
class Bar:
def __init__(self, name, stock = []) -> None:
self.name = name
self.stock = stock
... | Making changes in objects permanent | I'm trying to create a bar program, It's based on user inputs, classes and inheritance. This is my current code for the part not having to do with user input.
class Bar:
def __init__(self, name, stock = []) -> None:
self.name = name
self.stock = stock
def fill_stock(self):
pass
... | [
"I have a bit of a re-design for you. I like what you were trying to do with your Liquor class adding all instances to a class list. But having a dictionary where the key is the name of the liquor and the value the actual instance would allow you to look up liquors by name.\nBut why stop there with just liquors. Ha... | [
0
] | [] | [] | [
"class",
"object",
"python",
"python_3.x"
] | stackoverflow_0074181248_class_object_python_python_3.x.txt |
Q:
How can I write FPS showing code in YOLOv5
I just started to learn YOLOv5. When I write --source 0 in cmd and see myself in the screen I got very excited. I want to add a FPS showing code. I searched it on the internet. I find a code that shows FPS on webcam but I couldn't make them work together with YOLOv5. How ... | How can I write FPS showing code in YOLOv5 | I just started to learn YOLOv5. When I write --source 0 in cmd and see myself in the screen I got very excited. I want to add a FPS showing code. I searched it on the internet. I find a code that shows FPS on webcam but I couldn't make them work together with YOLOv5. How should I put this code in Yolo?
The code that sh... | [
"You can use the time module to keep track of the FPS.\nfrom time import time\n\nand create a global variable called loop_time which will grab the current time\nloop_time = time()\n\nThen in your while loop you can print the FPS using the following:\nwhile True:\nif time() - loop_time > 0:\n print('FPS: {}'.form... | [
0
] | [] | [] | [
"python",
"yolov5"
] | stackoverflow_0072628463_python_yolov5.txt |
Q:
Tip calculator with different tips amount
Below is my code, I am trying to get tip amount with different tip option and tip amount should be a 2 decimal places but didn't get the result
bill_amount = float(input('How much is the bill? $'))
ten = float((bill_amount / 100) * 10)
fifteen = float((bill_amount / 100) *... | Tip calculator with different tips amount | Below is my code, I am trying to get tip amount with different tip option and tip amount should be a 2 decimal places but didn't get the result
bill_amount = float(input('How much is the bill? $'))
ten = float((bill_amount / 100) * 10)
fifteen = float((bill_amount / 100) * 15)
twenty = float((bill_amount / 100) * 20)
t... | [
"I think this is a good case to use a multiline f-string:\nbill_amount = float(input('How much is the bill? $'))\nten = float((bill_amount / 100) * 10)\nfifteen = float((bill_amount / 100) * 15)\ntwenty = float((bill_amount / 100) * 20)\ntip_option = input(f'''Tip Options: \n10% Tip amount is', {ten:.2f}\n15% Tip a... | [
2,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074186124_python.txt |
Q:
AppConfig.__init__() missing 1 required positional argument: 'app_module'
Just running my first app but facing this issue:
**AppConfig.__init__() missing 1 required positional argument: 'app_module'**
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 4.1.2
Exception Type: TypeError
Excepti... | AppConfig.__init__() missing 1 required positional argument: 'app_module' | Just running my first app but facing this issue:
**AppConfig.__init__() missing 1 required positional argument: 'app_module'**
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 4.1.2
Exception Type: TypeError
Exception Value:
AppConfig.__init__() missing 1 required positional argument: 'app... | [
"'base.apps.BaseConfig' is included in the wrong spot under templates under settings.py.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074132129_django_python.txt |
Q:
Package installed in conda but module not found. How is that possible?
It seems that many people struggle with this problem, but I can't find any answer that works.
I think that I am doing everything right but it still doesn't work.
I've built my own package and installed it in my conda environment.
When I do cond... | Package installed in conda but module not found. How is that possible? | It seems that many people struggle with this problem, but I can't find any answer that works.
I think that I am doing everything right but it still doesn't work.
I've built my own package and installed it in my conda environment.
When I do conda list, it turns up in the list, at the end (I've called it zzpackagerps):
.... | [
"One possible issue is that the package name may not be identical to the module name. If you locate the site-packages where the package is installed, you can try looking at the folder structure and where there are __init__.py files defined.\n",
"Cannot comment so asking here.\nDid you install the package as root?... | [
2,
0,
0
] | [] | [] | [
"conda",
"modulenotfounderror",
"python"
] | stackoverflow_0067734105_conda_modulenotfounderror_python.txt |
Q:
how to call the subclasses within the base_class?
I have problem and need some help towards object oriented
I want to create an graph dataset and some subclasses about modifying the base_graph dataset
my question how to call the subclasses within the base_class in order to remove/add nodes to the base_graph?
class... | how to call the subclasses within the base_class? | I have problem and need some help towards object oriented
I want to create an graph dataset and some subclasses about modifying the base_graph dataset
my question how to call the subclasses within the base_class in order to remove/add nodes to the base_graph?
class base_graph(Dataset):
def __init__(self, nodes, edg... | [
"By \"how to call Modifygraph_byAdding & Modifygraph_byDeleting\" do you mean to pass instances of those classes, or using them in combination with a user-defined call operator that executes some action?\nEither case, you will at least need to provide such instances, either as arguments to __getitem__, or by giving... | [
1
] | [] | [] | [
"oop",
"python",
"pytorch_geometric"
] | stackoverflow_0074186368_oop_python_pytorch_geometric.txt |
Q:
How to import a Pydantic model into SQLModel?
I generated a Pydantic model and would like to import it into SQLModel. Since said model does not inherit from the SQLModel class, it is not registered in the metadata which is why
SQLModel.metadata.create_all(engine)
just ignores it.
In this discussion I found a way ... | How to import a Pydantic model into SQLModel? | I generated a Pydantic model and would like to import it into SQLModel. Since said model does not inherit from the SQLModel class, it is not registered in the metadata which is why
SQLModel.metadata.create_all(engine)
just ignores it.
In this discussion I found a way to manually add models:
SQLModel.metadata.tables["h... | [
"As far as I know, it is not possible to simply convert an existing Pydantic model to an SQLModel at runtime. (At least as of now.)\nThere are a lot of things that happen during model definition. There is a custom meta class involved, so there is no way that you can simply substitute a regular Pydantic model class ... | [
0
] | [] | [] | [
"pydantic",
"python",
"sqlmodel"
] | stackoverflow_0074175111_pydantic_python_sqlmodel.txt |
Q:
Multiprocessing a loop
I have a script that loops over a pandas dataframe and outputs GIS data to a geopackage based on some searches and geometry manipulation. It works when I use a for loop but with over 4k records it takes a while. Since I have it built as it's own function that returns what I need based on a r... | Multiprocessing a loop | I have a script that loops over a pandas dataframe and outputs GIS data to a geopackage based on some searches and geometry manipulation. It works when I use a for loop but with over 4k records it takes a while. Since I have it built as it's own function that returns what I need based on a row iteration I tried to run ... | [
"if you are running on windows/macOS then it's going to use spawn to create the workers, which means that any child MUST find the function it is going to execute when it imports your main script.\nyour code has the function definition inside your if __name__=='__main__': so the children don't have access to it.\nsi... | [
2
] | [] | [] | [
"multiprocessing",
"pandas",
"python"
] | stackoverflow_0074185743_multiprocessing_pandas_python.txt |
Q:
AttributeError: module 'google.cloud.vision' has no attribute 'types'
I did the setup for using the Google Vision API via Python, but it doesn't work and I don't find any good solutions. No matter what I do, I always get "AttributeError: module 'google.cloud.vision' has no attribute 'types'"...
Here is an example ... | AttributeError: module 'google.cloud.vision' has no attribute 'types' | I did the setup for using the Google Vision API via Python, but it doesn't work and I don't find any good solutions. No matter what I do, I always get "AttributeError: module 'google.cloud.vision' has no attribute 'types'"...
Here is an example Code I use (Authentication etc. is done).
from __future__ import print_func... | [
"I think you should follow the official documentation:\nVision Client Libraries\nimport io\nimport os\n\n# Imports the Google Cloud client library\nfrom google.cloud import vision\n\n# Instantiates a client\nclient = vision.ImageAnnotatorClient()\n\n# The name of the image file to annotate\nfile_name = os.path.absp... | [
7,
5,
0
] | [] | [] | [
"api",
"python"
] | stackoverflow_0064226174_api_python.txt |
Q:
How can I store information of an edge with Python Networkx
I converted a dictionary into a graph using NetworkX. Apart from just information about source and destination of an edge, the dictionary contains metadata of that edge like a name of that edge and a probability value related to that edge. Also the graph ... | How can I store information of an edge with Python Networkx | I converted a dictionary into a graph using NetworkX. Apart from just information about source and destination of an edge, the dictionary contains metadata of that edge like a name of that edge and a probability value related to that edge. Also the graph contains parallel edges. This is the first first two key value pa... | [
"You can use add_edges_from to add multiple edges at once. And for parallel edges, please refer to MultiDiGraph—Directed graphs with self loops and parallel edges.\nimport networkx as nx\nimport matplotlib.pyplot as plt \nfrom pprint import pprint\n\nG = nx.MultiDiGraph()\n\n# For each edge, we should assign sour... | [
2,
0
] | [] | [] | [
"complex_networks",
"graph",
"networkx",
"python"
] | stackoverflow_0072043796_complex_networks_graph_networkx_python.txt |
Q:
Lifelines - CoxTimeVaryingFitter - 'numpy.float64' object has no attribute 'exp'
I am trying to use the CoxTimeVaryingFitter on my dataset, however there seems to be a type issue in baseline_cumulative_hazard_.
I attempted reducing the individual features to isolate the problem but was not able to fit on the datas... | Lifelines - CoxTimeVaryingFitter - 'numpy.float64' object has no attribute 'exp' | I am trying to use the CoxTimeVaryingFitter on my dataset, however there seems to be a type issue in baseline_cumulative_hazard_.
I attempted reducing the individual features to isolate the problem but was not able to fit on the dataset below. Is the issue with my data or the model? Thanks!
Code:
from lifelines import... | [
"Looks like it is trying to apply np.exp to a dataframe (or Series or array) with object dtype.\nFrom another question I have a simple pandas Series:\nIn [120]: a\nOut[120]: \n0 1\n1 3\n2 5\n3 7\n4 9\ndtype: int64\n\nWith int dtype, I can apply np.exp and get a float dtypes Series:\nIn [121]: np.exp(... | [
0
] | [] | [] | [
"lifelines",
"numpy",
"pandas",
"python",
"survival"
] | stackoverflow_0074186575_lifelines_numpy_pandas_python_survival.txt |
Q:
python-docx cannot read a table inserted from excel
I need to deal with tables in many word files. Some of them are created in word table format, which can be read using python-docx.
However, some of them are inserted from excel. I don't know why python-docx cannot read them. Here is piece of code I wrote for tes... | python-docx cannot read a table inserted from excel | I need to deal with tables in many word files. Some of them are created in word table format, which can be read using python-docx.
However, some of them are inserted from excel. I don't know why python-docx cannot read them. Here is piece of code I wrote for test. As you can see in the terminal, there is nothings in t... | [
"I'm fighting the same issue using Pages on OSX to create a .docx template. I've found that Format > Arrange > Object Placement needs to be set to Move with text for the table, changing it to have any alignment or formatting causes the tables to disappear in python and be read as paragraphs that contain nothing. Lo... | [
0
] | [] | [] | [
"python",
"python_docx"
] | stackoverflow_0073245329_python_python_docx.txt |
Q:
How could I save specific row ranges from csv-s?
So what my code does is merging same size (same numbers of columns and rows) csv-s horizontally.
The csv-s are quite big (1M rows each) so I want to save a file only from row 0-20 and 70-80 with an empty row between them. Is it possible?
Ideally the code wouldn't ev... | How could I save specific row ranges from csv-s? | So what my code does is merging same size (same numbers of columns and rows) csv-s horizontally.
The csv-s are quite big (1M rows each) so I want to save a file only from row 0-20 and 70-80 with an empty row between them. Is it possible?
Ideally the code wouldn't even merge the csv-s completely only the needed range fr... | [
"Bringing this down from the comments. Using iloc[np.r_[]] as suggested in the first comment works as expected:\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng()\ndf = pd.DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list('ABCD'))\ndf = df.iloc[np.r_[0:20,70:80]]\n\ndf2 = pd.DataFra... | [
1
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074186417_csv_pandas_python.txt |
Q:
How to strip a 3D numpy array saved in a .txt file when trying to reopen it?
I saved a bunch of 3D arrays into .txt files and would like to reopen them, however, I am having a ard time stripping them of the extra stuff and turning it back into a nparray. It seems to not be in the format to use any of the easier np... | How to strip a 3D numpy array saved in a .txt file when trying to reopen it? | I saved a bunch of 3D arrays into .txt files and would like to reopen them, however, I am having a ard time stripping them of the extra stuff and turning it back into a nparray. It seems to not be in the format to use any of the easier np.loadtxt from numpy. Here is what I get when I try to read the file...
['[[ 4.5177... | [
"Watch the format in which you store the array. Looks like you're actually saving a \"view\" of an array (a string) instead of the numerical data itself. Try this instead:\nmport numpy as np \n ... | [
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074186648_arrays_numpy_python.txt |
Q:
StaleElementReferenceException clicking a tag
I'm using this selenium code to download a file daily, but sometimes I get stale reference error.
How can I be sure to click element as soon as it is avaiable?
try:
btnMenu = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, 'TRANSFERÊNCIA'))... | StaleElementReferenceException clicking a tag | I'm using this selenium code to download a file daily, but sometimes I get stale reference error.
How can I be sure to click element as soon as it is avaiable?
try:
btnMenu = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, 'TRANSFERÊNCIA')))
# btnMenu = WebDriverWait(driver, 15).until(E... | [
"I would suggest using a while loop with a try-except block as following:\nsucceed = False\nwhile !succeed:\n try:\n btnMenu = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, 'TRANSFERÊNCIA')))\n driver.execute_script(\"arguments[0].click();\", btnMenu)\n succeed = T... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"staleelementreferenceexception",
"try_catch"
] | stackoverflow_0074186526_python_selenium_selenium_webdriver_staleelementreferenceexception_try_catch.txt |
Q:
I don't understand how python methods within a class work
So I'm new to programming and I'm trying to learn how to code in uni.
We just started learning classes in python and I can't solve this problem.
I need to create a method reflect-x so that the variable y is negative.
Here is the code I wrote
class Point:
... | I don't understand how python methods within a class work | So I'm new to programming and I'm trying to learn how to code in uni.
We just started learning classes in python and I can't solve this problem.
I need to create a method reflect-x so that the variable y is negative.
Here is the code I wrote
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
... | [
"You have to call two methods (reflect, print) separately.\nBut if you have instinct to do the in such way you can approach it like this\nclass Point:\n def __init__(self,x,y):\n self.x=x\n self.y=y\n\n def reflect_x(self):\n if self.y > 0:\n self.y = -abs(self.y)\n retu... | [
1,
1
] | [] | [] | [
"class",
"python"
] | stackoverflow_0074186793_class_python.txt |
Q:
Apply function on numpy array row-by-row incrementaly
How can I optimize the following code, or more specifically, how can I eliminate the for-loop?
array = np.zeros((x.shape[0], K), dtype=np.float128)
for k in range(K):
array[:, k] = np.prod((np.power(ms[k, :], x) * np.power(1 - ms[k, :], 1 - x)).astype('flo... | Apply function on numpy array row-by-row incrementaly | How can I optimize the following code, or more specifically, how can I eliminate the for-loop?
array = np.zeros((x.shape[0], K), dtype=np.float128)
for k in range(K):
array[:, k] = np.prod((np.power(ms[k, :], x) * np.power(1 - ms[k, :], 1 - x)).astype('float128'), axis=1)
where x is a two-dimensional array shape... | [
"With 2 arrays with smaller dimensions:\nIn [142]: K=5; x=np.arange(30*4).reshape(30,4); ms = np.arange(K*4).reshape(K,4)\n\nYour iterative solution looks like:\nIn [143]: np.array([np.power(ms[k,:],x) for k in range(K)]).shape\nOut[143]: (5, 30, 4)\n\nIn [144]: arr = np.array([np.power(ms[k,:],x) for k in range(K)... | [
0
] | [] | [] | [
"arrays",
"numpy",
"optimization",
"python"
] | stackoverflow_0074185462_arrays_numpy_optimization_python.txt |
Q:
Chrome driver not finding ID nor replacing them, what am I doing wrong?
I am trying to build my first python selenium bot that checks me into southwest automatically. I've got the code to open southwests' check-in site, but it doesn't type anything. Can anyone tell me what I am doing wrong?
from selenium import we... | Chrome driver not finding ID nor replacing them, what am I doing wrong? | I am trying to build my first python selenium bot that checks me into southwest automatically. I've got the code to open southwests' check-in site, but it doesn't type anything. Can anyone tell me what I am doing wrong?
from selenium import webdriver
driver = webdriver.Chrome('/Users/thomas****/chromedriver/chromedriv... | [
"I just checked, it is working. Your only issue is that '1234' is not a valid confirmation number. Look closely and it shows Enter valid confirmation #. under the Confirmation # field.\nReplace it with something like the following, for example, and you will see a bigger error.\nconf_num.send_keys(\"977089\")\n\n",
... | [
0,
0,
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver",
"webdriverwait"
] | stackoverflow_0074186012_python_selenium_selenium_chromedriver_selenium_webdriver_webdriverwait.txt |
Q:
Having trouble assigning different variables in the main module for an assignment I have
def GetEmpName():
empName = input("Enter employee name: ")
return empName
#write the GetHoursWorked function
def GetHoursWorked():
hrsWrkd = input("Enter hours worked: ")
return hrsWrkd
#write the GetHourlyRat... | Having trouble assigning different variables in the main module for an assignment I have | def GetEmpName():
empName = input("Enter employee name: ")
return empName
#write the GetHoursWorked function
def GetHoursWorked():
hrsWrkd = input("Enter hours worked: ")
return hrsWrkd
#write the GetHourlyRate function
def GetHourlyRate():
hrlyRate = input("Enter hourly rate: ")
return hrlyRat... | [
"After copying in your code and working through some syntax and indentation issues, I did a bit of code cleanup and correction to the code to allow for the entry of one or more employee time information. Following is a revised version of the code.\ndef GetEmpName():\n empName = input(\"Enter employee name: \")\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074185468_python.txt |
Q:
ValueError using vstack: all the input array dimensions for the concatenation axis must match exactly
I have a matrix epoch in which epoch[i][0] is a m x 5 array, where m varies for each i. For example,
epoch[0][0] = [[-5.50571416e-21, -5.92923063e-21, 4.23516474e-21,
-2.54109884e-21, -5.08219768e-21],
... | ValueError using vstack: all the input array dimensions for the concatenation axis must match exactly | I have a matrix epoch in which epoch[i][0] is a m x 5 array, where m varies for each i. For example,
epoch[0][0] = [[-5.50571416e-21, -5.92923063e-21, 4.23516474e-21,
-2.54109884e-21, -5.08219768e-21],
[-3.03901510e-06, -1.40172574e-06, -8.46450345e-07,
-3.90002708e-06, -5.56446205e-07],
... | [
"Fixed it by initializing\nX = np.zeros((1, 5))\n\n"
] | [
1
] | [] | [] | [
"for_loop",
"multidimensional_array",
"python",
"vstack"
] | stackoverflow_0074186408_for_loop_multidimensional_array_python_vstack.txt |
Q:
how can i know if the variable is defined or not in python?
i need to know if the variable is defined or not in python without making error because i am working on a project has a lot of variables and i need to know if the variable is defined to know if the operation has been do or not
is there method or way to kn... | how can i know if the variable is defined or not in python? | i need to know if the variable is defined or not in python without making error because i am working on a project has a lot of variables and i need to know if the variable is defined to know if the operation has been do or not
is there method or way to know if the variable defind or not without makeing error ?
now i us... | [
"You can check inside globals,\nif 'variable' in globals():\n print(\"this variable is defined\")\nelse:\n print(\"this variable is not defined\")\n\n"
] | [
2
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0074186984_python_variables.txt |
Q:
SpaCy install error -- ImportError: cannot import name remove_bilu_prefix
When installing language models for SpaCy using Conda, I keep getting the error:
ImportError: cannot import name remove_bilu_prefix
I have installed SpaCy using the conda install line:
conda install -c conda-forge spacy
And it appeared t... | SpaCy install error -- ImportError: cannot import name remove_bilu_prefix | When installing language models for SpaCy using Conda, I keep getting the error:
ImportError: cannot import name remove_bilu_prefix
I have installed SpaCy using the conda install line:
conda install -c conda-forge spacy
And it appeared to install fine, but now once I go to install the language models (en_core_web_s... | [
"I think I solved my problem. I installed SpaCy using another Conda install:\n\nconda install -c \"conda-forge/label/cf201901\" spacy\n\nThen I followed the directions to download the language models (en_core_web_sm) straight from huggingface. Go to https://huggingface.co/spacy then go to 'models', select your mode... | [
0
] | [] | [] | [
"conda",
"nlp",
"python",
"spacy"
] | stackoverflow_0074185493_conda_nlp_python_spacy.txt |
Q:
Python way of plotting a Tephigram and Hodograph
I am looking to plot a Tephigram using Python and so far I have noticed that there are no real ways of doing so and I do not have the meteorological training to start from a SkewT plot and customize it to a Tephigram. I am currently using MetPy to create plots like ... | Python way of plotting a Tephigram and Hodograph | I am looking to plot a Tephigram using Python and so far I have noticed that there are no real ways of doing so and I do not have the meteorological training to start from a SkewT plot and customize it to a Tephigram. I am currently using MetPy to create plots like the one below but I do not think it is a valid Tephigr... | [
"To be clear, there's no amount of customization you can do to a Skew-T to produce a Tephigram. Skew-T log-P diagrams plot pressure vs. temperature, with pressure on a logarithmic scale on the vertical, temperature rotated (nominally 45 degrees). Tephigrams fundamentally plot entropy (potential temperature) vs. tem... | [
1
] | [] | [] | [
"geospatial",
"matplotlib",
"metpy",
"python"
] | stackoverflow_0074183635_geospatial_matplotlib_metpy_python.txt |
Q:
Selenium error message "selenium.webdriver has no attribute execute script"
I am using selenium to scrape an infinite scrolling page.
I am trying to use this code:
import time
import pandas as np
import numpy as np
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdri... | Selenium error message "selenium.webdriver has no attribute execute script" | I am using selenium to scrape an infinite scrolling page.
I am trying to use this code:
import time
import pandas as np
import numpy as np
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
browser = webdriver.Chrome()
url = 'https://twitter.com/... | [
"webdriver is the name of the module, not your instance of it. In fact, you assigned the instance you created to the name browser with this line: browser = webdriver.Chrome()\nso instead of calling webdriver.execute_script() (which will give you an AttributeError), you must call it using your instance, like this: ... | [
8,
1,
1,
0
] | [] | [] | [
"driver",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0052084458_driver_python_selenium_selenium_webdriver.txt |
Q:
Issue using turbo_flask to refresh html content on python
I'm trying to run a thread function update_load every 5 second using python to refresh Html content using flask turbo and jinja
My issue
i'm not able to reload the Html using turbo.push it give me this error from browser console:
https://cdn.skypack.dev/-/@... | Issue using turbo_flask to refresh html content on python | I'm trying to run a thread function update_load every 5 second using python to refresh Html content using flask turbo and jinja
My issue
i'm not able to reload the Html using turbo.push it give me this error from browser console:
https://cdn.skypack.dev/-/@hotwired/turbo@v7.2.2-RBjb2wnkmosSQVoP27jT/dist=es2020,min/@hot... | [
"Problem solved in this issues/42\n"
] | [
0
] | [] | [] | [
"jinja2",
"python"
] | stackoverflow_0074165631_jinja2_python.txt |
Q:
using telebot in callback_query_handler with two filters func and state custom im trying to store state but i get TypeError: 'NoneType'
Using telebot in callback_query_handler with two filters func and state custom im trying to store state but i get TypeError: 'NoneType'
data['model'] = call.data
TypeError: 'NoneT... | using telebot in callback_query_handler with two filters func and state custom im trying to store state but i get TypeError: 'NoneType' | Using telebot in callback_query_handler with two filters func and state custom im trying to store state but i get TypeError: 'NoneType'
data['model'] = call.data
TypeError: 'NoneType' object does not support item assignment
I dont know why data is NoneType
...
state_storage = StateMemoryStorage()
MODELS = ['ROAD', 'S... | [
"i found problem. It was in block bot.retrieve_data(call.message.from_user.id, call.message.chat.id)\nI incorrectly accessed json elements\n"
] | [
0
] | [] | [] | [
"py_telegram_bot_api",
"python",
"telebot",
"telegram"
] | stackoverflow_0074185722_py_telegram_bot_api_python_telebot_telegram.txt |
Q:
My python blackjack game is not working as intended
The problems are:
Upon typing n to stand and winning, it doesnt ask the user again if they want to play a game of blackjack.
And upon winning it also does not ask the user if it wants to play, straight up just starts the game once again.
Please help me solve th... | My python blackjack game is not working as intended | The problems are:
Upon typing n to stand and winning, it doesnt ask the user again if they want to play a game of blackjack.
And upon winning it also does not ask the user if it wants to play, straight up just starts the game once again.
Please help me solve this, I lost all hope while debugging...
p.s. #clear and #a... | [
"\nUpon typing n to stand and winning, it doesnt ask the user again if they want to play a game of blackjack.\n\nThis line makes sure that the user will not be asked to play a game of blackjack if the user input is not y. Since n is not y, it will not ask the user again upon typing n:\nwhile input(\"Would you like... | [
0,
0
] | [] | [] | [
"blackjack",
"python",
"while_loop"
] | stackoverflow_0074186948_blackjack_python_while_loop.txt |
Q:
The unique() method must be invoked on this Result exception raised after SQLAlchemy Select
I have an issue with SQLAlchemy and I cannot figure out the cause of this error:
so my class definition is:
class PricingFrequency(enum.Enum):
month = 'month'
year = 'year'
class PlanPricing(Base):
__tablename... | The unique() method must be invoked on this Result exception raised after SQLAlchemy Select | I have an issue with SQLAlchemy and I cannot figure out the cause of this error:
so my class definition is:
class PricingFrequency(enum.Enum):
month = 'month'
year = 'year'
class PlanPricing(Base):
__tablename__ = "PlansPricing"
pricing_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.u... | [
"I misunderstood sqlalchemy's loading technique. Nevertheless, my request was not well formatted, so I changed it to be that way, and it is currently functioning. Thanks\n plan_pricing_aliased1 = aliased(PlanPricing)\n plan_pricing_aliased2 = aliased(PlanPricing)\n query = (\n s... | [
0
] | [] | [] | [
"fastapi",
"python",
"sqlalchemy"
] | stackoverflow_0074179020_fastapi_python_sqlalchemy.txt |
Q:
Resource stopwords not found in Python
I try to import the nltk package in Python 3.7.9 with the following code:
from nltk.corpus import stopwords
english_stop_words = set(stopwords.words('english'))
But when I run the above code, it shows me the following error:
LookupError:
***********************************... | Resource stopwords not found in Python | I try to import the nltk package in Python 3.7.9 with the following code:
from nltk.corpus import stopwords
english_stop_words = set(stopwords.words('english'))
But when I run the above code, it shows me the following error:
LookupError:
**********************************************************************
Resou... | [
"I fixed it with:\npython -m nltk.downloader stopwords.\nIf you are on windows10.\n"
] | [
0
] | [] | [] | [
"error_handling",
"nltk",
"python",
"python_3.7",
"python_3.x"
] | stackoverflow_0074009664_error_handling_nltk_python_python_3.7_python_3.x.txt |
Q:
Mocking a smart card response using pyscard
I'm trying to mock a response in a small function using some pyscard attributes.
My function:
def card_reader():
# request any card type
cardtype = AnyCardType()
cardrequest = CardRequest(timeout=25, cardType=cardtype)
cardservice = cardrequest.waitforcar... | Mocking a smart card response using pyscard | I'm trying to mock a response in a small function using some pyscard attributes.
My function:
def card_reader():
# request any card type
cardtype = AnyCardType()
cardrequest = CardRequest(timeout=25, cardType=cardtype)
cardservice = cardrequest.waitforcard()
# attach the console tracer
observer... | [
"I've always been intrigued by Mocks, MagicMocks and my apparent lack of knowledge about them , that's why I was curious about this.\nI could totally be wrong, but I think what is happening is the following:\n\nThe mocked class is CardRequest.\nAt a certain point, there's this cardservice = cardrequest.waitforcard(... | [
1
] | [] | [] | [
"mifare",
"pyscard",
"python"
] | stackoverflow_0074186760_mifare_pyscard_python.txt |
Q:
Creating New Column with value of other columns based on condition on a third Column in Pandas DataFrame
My dataframe looks like this
category value1 value2
A. 20. 30.
B. 40. 50.
A. 60. 70.
B. 80. 90.
C. 10. 10.
D. 20. 20.
I want to create a n... | Creating New Column with value of other columns based on condition on a third Column in Pandas DataFrame | My dataframe looks like this
category value1 value2
A. 20. 30.
B. 40. 50.
A. 60. 70.
B. 80. 90.
C. 10. 10.
D. 20. 20.
I want to create a new column that has the value of either value1 or value2 based on a condition relative to category.
For example... | [
"# np.select and define list of condition with corresponding values\ndf['value3']=(np.select([df['category'].eq('A.'), # condition #1\n df['category'].eq('B.')],# condition #2\n [df['value1'], # value when #1 is true\n df['value2']], ... | [
1,
1,
0
] | [] | [] | [
"dataframe",
"filter",
"mapping",
"pandas",
"python"
] | stackoverflow_0074187014_dataframe_filter_mapping_pandas_python.txt |
Q:
Pandas how to separate elements in order to create columns in this log file
I have a log file with lines like this :
2022-10-20 14:23:06,709 [12] INFO XXXX.XXXX.XXXX.XXXX - XXXX XXXX, Added XXXX in XXXX for thread: XX, XXXX exists: XXX
I would like to create 6 columns, like this :
Column 1 : 2022-10-20
Column 2 : ... | Pandas how to separate elements in order to create columns in this log file | I have a log file with lines like this :
2022-10-20 14:23:06,709 [12] INFO XXXX.XXXX.XXXX.XXXX - XXXX XXXX, Added XXXX in XXXX for thread: XX, XXXX exists: XXX
I would like to create 6 columns, like this :
Column 1 : 2022-10-20
Column 2 : 14:23:06,709
Column 3 : [12]
Column 4 : INFO
Column 5 : XXXX.XXXX.XXXX.XXXX
Colum... | [
"Here is one way about it\nwe need a rule to apply to the log file when reading here\nwe can split on spaces but only first 5 spaces\nlines=[]\n\n# open the log file\nwith open(\"csv2.txt\") as fi:\n for line in fi:\n line = re.split(r\"\\s+\", line, 5) # split only 5 times per line\n lines.append(... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074186882_pandas_python.txt |
Q:
Can I change variable name in Python
Can I change my variable name in Python? For example, I have a string x, and I want to change string x variable name to y, how can I do it?
A:
Python variables are references to objects, so you can simply create a second name pointing to the existing object and delete the ol... | Can I change variable name in Python | Can I change my variable name in Python? For example, I have a string x, and I want to change string x variable name to y, how can I do it?
| [
"Python variables are references to objects, so you can simply create a second name pointing to the existing object and delete the old name:\ny = x\ndel x\n\n",
"Ideally, the good approach will be renaming the variable, like y = x\nBut you can do this in weird approach with using globals()\nIn [1]: x = 10\n\nIn [... | [
3,
0
] | [] | [] | [
"python",
"variable_names"
] | stackoverflow_0074187195_python_variable_names.txt |
Q:
Where can I configure the browser behavior of Playwright in VSCode?
I'm starting to use Playwright with VSCode.
I have it running from Test in VSCode, but the browser is not showing up. I would like to get the browser to show up, but where can I configure the browser behavior?
A:
Not sure exactly if by "browser ... | Where can I configure the browser behavior of Playwright in VSCode? | I'm starting to use Playwright with VSCode.
I have it running from Test in VSCode, but the browser is not showing up. I would like to get the browser to show up, but where can I configure the browser behavior?
| [
"Not sure exactly if by \"browser to show up\" you refer at the fact that you need the browser to not run in headless mode.\nThere are two possible ways:\n\nInstall Playwright Test for VSCode as suggest by @MingJie-MSFT. You'll have a Show browser checkbox there in case you want to run your tests headless or not\nI... | [
1,
0
] | [] | [] | [
"playwright",
"python",
"visual_studio_code"
] | stackoverflow_0074104846_playwright_python_visual_studio_code.txt |
Q:
How do you run an loop that takes data from a certain file and adds it to the elements of an 2D array in PYTHON?
I am basically trying to read data from an excel file and I want to add it in an array. The excel file has multiple rows and multiple columns and I want them to be shown the exact same way in the array ... | How do you run an loop that takes data from a certain file and adds it to the elements of an 2D array in PYTHON? | I am basically trying to read data from an excel file and I want to add it in an array. The excel file has multiple rows and multiple columns and I want them to be shown the exact same way in the array too.
This data needs to be shown in an array
from importlib.resources import open_binary
import openpyxl
import numpy ... | [
"Implementing what I said in my comment,\nmatrix = []\nfor i in range(1,rowMax+1):\n row = []\n for j in range(1,columnMax+1):\n row.append( bus1.cell(i,j).value )\n matrix.append(row)\n\nOr\nmatrix = []\nfor i in range(1,rowMax+1):\n matrix.append( [bus1.cell(i,j+1).value for j in range(columnMax)] )\n\nOr ... | [
0
] | [] | [] | [
"arrays",
"multidimensional_array",
"python",
"sorting"
] | stackoverflow_0074187234_arrays_multidimensional_array_python_sorting.txt |
Q:
How to use multiple cases in Match (switch in other languages) cases in Python 3.10
I am trying to use multiple cases in a function similar to the one shown below so that I can be able to execute multiple cases using match cases in python 3.10
def sayHi(name):
match name:
case ['Egide', 'Eric']:
... | How to use multiple cases in Match (switch in other languages) cases in Python 3.10 | I am trying to use multiple cases in a function similar to the one shown below so that I can be able to execute multiple cases using match cases in python 3.10
def sayHi(name):
match name:
case ['Egide', 'Eric']:
return f"Hi Mr {name}"
case 'Egidia':
return f"Hi Ms {name}"
pr... | [
"According to\nWhat’s New In Python 3.10,\nPEP 636, and\nthe docs,\nyou use a | between patterns:\ncase 'Egide' | 'Eric':\n\n",
"You can use | (or) to replace ['Egide', 'Eric'] with 'Egide' | 'Eric', but you can also match elements belonging to iterables or containers with a guard, as follows:\nCONSTANTS = ['a','... | [
41,
5
] | [] | [] | [
"match",
"python",
"python_3.10",
"switch_statement"
] | stackoverflow_0069642889_match_python_python_3.10_switch_statement.txt |
Q:
Fill missing dates hourly per group with previous value in certain column using Pandas
I have the following dataframe (sample):
import pandas as pd
data = [['A', '2022-09-01 10:00:00', False, 2], ['A', '2022-09-01 14:00:00', False, 3],
['B', '2022-09-01 13:00:00', False, 1], ['B', '2022-09-01 16:00:00', T... | Fill missing dates hourly per group with previous value in certain column using Pandas | I have the following dataframe (sample):
import pandas as pd
data = [['A', '2022-09-01 10:00:00', False, 2], ['A', '2022-09-01 14:00:00', False, 3],
['B', '2022-09-01 13:00:00', False, 1], ['B', '2022-09-01 16:00:00', True, 4]]
df = pd.DataFrame(data = data, columns = ['group', 'date', 'indicator', 'value'])
... | [
"You can use:\ndf['date'] = pd.to_datetime(df['date'])\n\nout = (df\n .groupby('group', as_index=False, group_keys=False)\n .apply(lambda g: g.set_index('date')\n .reindex(pd.date_range(g['date'].min(),\n g['date'].max(),\n ... | [
3,
3,
1
] | [] | [] | [
"dataframe",
"date",
"pandas",
"python"
] | stackoverflow_0074182891_dataframe_date_pandas_python.txt |
Q:
How to have a Python script for a Django app that accesses models without using the manage.py shell?
I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running ./manage.py shell and then import myscript. I'm sure there's a better way. I'd... | How to have a Python script for a Django app that accesses models without using the manage.py shell? | I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running ./manage.py shell and then import myscript. I'm sure there's a better way. I'd like to be able to call a script from anywhere on my HD using python scriptname.py, and in the first few ... | [
"Since Django 1.4 you should avoid using setup_environ(settings) (post by Melug) because it is deprecated. Use the following instead and you will be able to access your model\nimport os\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"your_project_name.settings\")\n\n# your imports, e.g. Django models\nfrom y... | [
156,
136,
46,
40,
24,
10,
4,
2,
2,
2,
1,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008047204_django_django_models_python.txt |
Q:
Got must be real number, not BadRequest error when I am trying to return http error
I am building a python api using quart, and using foreman to run it. When I am trying to return some error code, it does not run correctly but returns a html and tells me it needs to be real number, not bad request.
My code looks l... | Got must be real number, not BadRequest error when I am trying to return http error | I am building a python api using quart, and using foreman to run it. When I am trying to return some error code, it does not run correctly but returns a html and tells me it needs to be real number, not bad request.
My code looks like this for getting all info of a game from DB
@app.route("/games/info/<int:game_id>", m... | [
"I figured it out.\nChanging\nreturn {\"error\": str(e)}, 400\n\nto\nreturn {\"error\": e.description}, 400\n\ncan solve the issue. Seems this error happens because str has some issue with converting werkzeug.exceptions class object to string.\n"
] | [
0
] | [] | [] | [
"backend",
"foreman",
"python",
"quart"
] | stackoverflow_0074178680_backend_foreman_python_quart.txt |
Q:
Python - search dict value from list of strings
I have a list of strings that represent specific error codes my code needs to filter out.
DMS_WARNING_STOP_REASONS = ["Stop Reason RECOVERABLE_ERROR",
"Stop Reason FATAL_ERROR",
"Stop Reason STOPPED_DUE_TO_LOW_... | Python - search dict value from list of strings | I have a list of strings that represent specific error codes my code needs to filter out.
DMS_WARNING_STOP_REASONS = ["Stop Reason RECOVERABLE_ERROR",
"Stop Reason FATAL_ERROR",
"Stop Reason STOPPED_DUE_TO_LOW_MEMORY",
"Stop Reason STO... | [
"I had to re-use.get() as it modifies the dict in-fly without inserting the key into the dict.\nWorking solution based of @ILS code:\nif (any(stop_reason in x.get(\"StopReason\", \"Stop Reason FAILED\")\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074183457_python.txt |
Q:
Simple "get letter of the alphabet via number" code doesn't work for "z"?
I'm newly learning Python for school, I have wrote this code as training; it works fine except for the last letter "z".
Ther code is this:
alpha = "abcdefghijklmnopqrstuvwxyz"
letter = int(input('Input number of letter needed from alphabet ... | Simple "get letter of the alphabet via number" code doesn't work for "z"? | I'm newly learning Python for school, I have wrote this code as training; it works fine except for the last letter "z".
Ther code is this:
alpha = "abcdefghijklmnopqrstuvwxyz"
letter = int(input('Input number of letter needed from alphabet (between 1 and 26): '))
if 0 < letter < len(alpha):
print(alpha[letter - 1... | [
"you have to change if 0 < letter < len(alpha): to if 0 < letter <= len(alpha): as this drops the case where letter = len(alpha), which is for the letter 'z'\nbonus: you can write a one-liner for it if you know what ASCII is (assuming the input is valid though)\nprint(chr(96 + int(input())))\n\n",
"You must inclu... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074187333_python.txt |
Q:
How to efficiently plot many lines in a 3D matplotlib graph
I have some edges between nodes that I need to graph in a 3D matplotlib graph. One example of an edge would be from coordinates (0,0,0) to coordinates (5,2,1).
I can't graph all the edges with one plot call because then it would connect nodes together tha... | How to efficiently plot many lines in a 3D matplotlib graph | I have some edges between nodes that I need to graph in a 3D matplotlib graph. One example of an edge would be from coordinates (0,0,0) to coordinates (5,2,1).
I can't graph all the edges with one plot call because then it would connect nodes together that don't have an edge. I could call a separate plot function for e... | [
"It seems you are looking for LineCollections\nimport matplotlib.pyplot as plt\nfrom random import *\nimport numpy as np\nfrom mpl_toolkits.mplot3d.art3d import Line3DCollection\n\ndef generateDummyData(size):\n data = []\n for i in range(size):\n nodeA = (randrange(-10,10),randrange(-10,10),randrange(... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074186827_matplotlib_python.txt |
Q:
Issue with Python displaying all available color pairs with Curses
I am running Python 3.10 and I am having an issue with curses, specifically when trying to utilize the full range of color pairs
curses.COLORS returns 256
curses.COLOR_PAIRS returns 65536
curses.has_extended_color_support() returns True
But when I ... | Issue with Python displaying all available color pairs with Curses | I am running Python 3.10 and I am having an issue with curses, specifically when trying to utilize the full range of color pairs
curses.COLORS returns 256
curses.COLOR_PAIRS returns 65536
curses.has_extended_color_support() returns True
But when I initialize a color pair of 256, 512, 768, 1024, etc... the color pair se... | [
"You would have to use the extended interface, as noted in the release announcement for ncurses 6.1:\n\nThe motivation for making this extension came from noticing that termcap applications could (though not realistically) use larger numbers than would fit in 16-bits, and the fact that the number of color pairs for... | [
0
] | [] | [] | [
"curses",
"ncurses",
"python",
"python_3.x",
"python_curses"
] | stackoverflow_0074186123_curses_ncurses_python_python_3.x_python_curses.txt |
Q:
Parallelize 20K requests + filter & concat results into 1 dataframe
I need to make around 20K API calls, each one returns a CSV file and then on that file I have to perform some operations, finally, concatenate all the results into a single dataframe.
I've completed this task sequentially, but the issue is that ea... | Parallelize 20K requests + filter & concat results into 1 dataframe | I need to make around 20K API calls, each one returns a CSV file and then on that file I have to perform some operations, finally, concatenate all the results into a single dataframe.
I've completed this task sequentially, but the issue is that each API Call lasts around 1sec and it takes around 6h to complete. So, I w... | [
"Alternatively, you could use dask.dataframe, which gives an API much like that of pandas and handles parallelization over multiple threads, processes, or physical servers:\nimport dask\nimport dask.distributed\nimport dask.dataframe\nimport pandas as pd\n\n# start a dask client\nclient = dask.distributed.Client()\... | [
0,
0
] | [] | [] | [
"api",
"pandas",
"python"
] | stackoverflow_0074186893_api_pandas_python.txt |
Q:
ValueError: could not convert string to float: 'registration'
I am doing vehicle registration plate detection using YOLOv4 in colab. When I ran !python \convert_annotations.py file I got following error
Currently in subdirectory: validation
Converting annotations for class: Vehicle registration plate
0% 0/30 [0... | ValueError: could not convert string to float: 'registration' | I am doing vehicle registration plate detection using YOLOv4 in colab. When I ran !python \convert_annotations.py file I got following error
Currently in subdirectory: validation
Converting annotations for class: Vehicle registration plate
0% 0/30 [00:00<?, ?it/s]
Traceback (most recent call last):
File "convert_a... | [
"Brian, the solution to your problem :\nWith your terminal, go to your directory, for example :\nyolov4/OIDv4_ToolKit\n\nTo get 15 images for the training data:\npython3 main.py downloader --classes Vehicle_registration_plate --type_csv train --limit 15\n\nTo get 3 images for the validation:\npython3 main.py downlo... | [
0
] | [
"remove apostrophes in 'Vehicle registration plate' and run it.\nif the issue is not solved, then try running pip install -r requirements.txt before running this command\n"
] | [
-2
] | [
"python",
"yolov4"
] | stackoverflow_0071808755_python_yolov4.txt |
Q:
How can I split a dictionary by commas and make a correct csv file with it in Python?
I'm trying to make a csv file that contains a dictionary:
dict={"Steps" : [], "x" : []}
The problem is that the code of making csv is below and the data in "Steps" and "x" is this: Steps = {1, 2, 3, 4, 5, etc...}, x = {-1, ... | How can I split a dictionary by commas and make a correct csv file with it in Python? | I'm trying to make a csv file that contains a dictionary:
dict={"Steps" : [], "x" : []}
The problem is that the code of making csv is below and the data in "Steps" and "x" is this: Steps = {1, 2, 3, 4, 5, etc...}, x = {-1, 5, 2, 6, 73, 23, etc...}
I want to separate those numbers by commas and write down those v... | [
"there is no need to make complex multi-level functions for this task. a simple loop and file I/O is sufficient:\ndictionary = {\"steps\" : [1, 2, 3, 5], \"x\" : [-1, 5, 2, 6]}\n\nfile = open(\"data.csv\", \"w\")\nfile.write(\"steps,x\\n\")\nfor index in range(len(dictionary[\"steps\"])):\n file.write(str(dictio... | [
0,
0
] | [] | [] | [
"csv",
"dictionary",
"python"
] | stackoverflow_0074185913_csv_dictionary_python.txt |
Q:
finding corresponding data points in python pandas
My data set contains a "score" containing floats and a "score phrase",a string describing the score. how do i use python/pandas to sort out and show me the score/scores that correspond to each Possible phrase?
below is the code i currently have to load the data fr... | finding corresponding data points in python pandas | My data set contains a "score" containing floats and a "score phrase",a string describing the score. how do i use python/pandas to sort out and show me the score/scores that correspond to each Possible phrase?
below is the code i currently have to load the data from the excel file and filter it to just those two column... | [
"Given the data in your comment, you can use groupby, nunique and to_list to get a list of all unique combinations.\ndf.groupby([\"score_phrase\", \"score\"]).nunique().index.to_list()\n\n[('Disaster', 0.5), ('Disaster', 0.7), ('Disaster', 0.8), ('Masterpiece', 10.0), ('Unbearable', 1.0)]\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074186065_pandas_python.txt |
Q:
Python dict to show values of different dict
I wanted to create dictionary that will show if actors were in the same movies.
I have dict of actors:
actors = {'1': 'John', '2': 'Richard', '3': 'Lisa', '4': 'Jennifer'}
and list of actors (keys from dictionary actors) that were in the same movie
was_in_movie = [(1,2... | Python dict to show values of different dict | I wanted to create dictionary that will show if actors were in the same movies.
I have dict of actors:
actors = {'1': 'John', '2': 'Richard', '3': 'Lisa', '4': 'Jennifer'}
and list of actors (keys from dictionary actors) that were in the same movie
was_in_movie = [(1,2), (1,3), (3,4)]
I am creating new dict using def... | [
"You can do with mapping function here,\ndef mapping(k):\n actors.get(str(k))\n\nnew_dict = defaultdict(set)\nfor element1, element2 in was_in_movie:\n for a, b in was_in_movie:\n new_dict[mapping(a)].add(mapping(b))\n new_dict[mapping(b)].add(mapping(a))\n\nResult,\ndefaultdict(<class 'set'>, {... | [
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074187425_dictionary_python.txt |
Q:
Python port forwarding with dynamic SOCKs
I has been trying to create a port forwarding session including a dynamic socks with paramiko and pysocks, I already do it with plink using this:
plink -ssh -D 10100 -L 25000:PrivateServerIP:1494 user@RemoteServerIP
I am trying this but isn't working:
import paramiko
from ... | Python port forwarding with dynamic SOCKs | I has been trying to create a port forwarding session including a dynamic socks with paramiko and pysocks, I already do it with plink using this:
plink -ssh -D 10100 -L 25000:PrivateServerIP:1494 user@RemoteServerIP
I am trying this but isn't working:
import paramiko
from getpass import getpass
import socks
USERNAME= ... | [
"I run plink command in background using subprocess and QNetworkProxy for my app:\nimport sys\nfrom PyQt5.QtWidgets import QMainWindow\nfrom PyQt5 import QtNetwork \nfrom subprocess ... | [
0
] | [] | [] | [
"paramiko",
"portforwarding",
"proxy",
"pysocks",
"python"
] | stackoverflow_0074031906_paramiko_portforwarding_proxy_pysocks_python.txt |
Q:
Caesar Cypher Issue
Currently learning Python, and working on a Caesar Cypher... I can't seem to figure out why my decryption is spitting out the wrong text; currently it does this...
Plain text: Hello
Distance: 65
Encrypt: *&..0
Decrypt: gckkm
I've looked through other posts, but don't seem to find any that have ... | Caesar Cypher Issue | Currently learning Python, and working on a Caesar Cypher... I can't seem to figure out why my decryption is spitting out the wrong text; currently it does this...
Plain text: Hello
Distance: 65
Encrypt: *&..0
Decrypt: gckkm
I've looked through other posts, but don't seem to find any that have the same issue with decry... | [] | [] | [
"I have debugged the code you posted.\nlets take for example the input 'm' and distance 20.\nthe code will be 1 and in the ascii table this means 'SOH' - start of heading.\nwhen trying to copy the output text in the Console and paste it, it didn't know that kind of input.\ntherefor, you should separate the encrypti... | [
-1,
-1
] | [
"caesar_cipher",
"python",
"python_3.x"
] | stackoverflow_0074184737_caesar_cipher_python_python_3.x.txt |
Q:
Extract paragraphs with beautiful soup without getting excess html?
I am undergoing a project to web scrape the facts off the following website: https://holypython.com/100-python-tips-tricks/
Thanks to the response of a user in a previous query, I have been able to get the titles from this website, but am struggli... | Extract paragraphs with beautiful soup without getting excess html? | I am undergoing a project to web scrape the facts off the following website: https://holypython.com/100-python-tips-tricks/
Thanks to the response of a user in a previous query, I have been able to get the titles from this website, but am struggling to get paragraphs below the title. Using the following code I have att... | [
"You can iterate through the soup.select(\"div.elementor-widget-wrap\") and select paragraphs,\nparagraphs = [para.text for div in soup.select(\"div.elementor-widget-wrap\")\n for para in div.find_all('p')]\n\nResult, print(paragraphs[:5])\n['Python is cool, no doubt about it. But, there are ... | [
1
] | [] | [] | [
"html",
"python",
"web_scraping"
] | stackoverflow_0074187498_html_python_web_scraping.txt |
Q:
using a dictionary function to call a df column
I have a dictionary that has a list of all of the df column names and maps them to function names.
import pandas as pd
data= [["john","","","English","","","","","","","","",""]]
df= pd.DataFrame(data,columns=['firstName', 'lastName', 'state', 'Communication_Langua... | using a dictionary function to call a df column | I have a dictionary that has a list of all of the df column names and maps them to function names.
import pandas as pd
data= [["john","","","English","","","","","","","","",""]]
df= pd.DataFrame(data,columns=['firstName', 'lastName', 'state', 'Communication_Language__c', 'country', 'company', 'email', 'industry', 'S... | [
"Try something like this:\nimport pandas as pd\n \ndata= [[\"john\",\"\",\"\",\"English\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]]\ndf= pd.DataFrame(data,columns=['firstName', 'lastName', 'state', 'Communication_Language__c', 'country', 'company', 'email', 'industry', 'System_Type__c', 'AccountType', 'custome... | [
0,
0
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python"
] | stackoverflow_0074187441_dataframe_dictionary_pandas_python.txt |
Q:
Running multiple processses asynchronously
So I have a main() function which needs to continously start >20 different processes every 5 seconds without waiting them to finish as some might take over 5 minutes to finish.
I’ve used threads so far (without joining them) but GIL eventually halts the execution as numbe... | Running multiple processses asynchronously | So I have a main() function which needs to continously start >20 different processes every 5 seconds without waiting them to finish as some might take over 5 minutes to finish.
I’ve used threads so far (without joining them) but GIL eventually halts the execution as number of active threads increases.
Could I maybe use... | [
"You can try to use concurrent.future.ProcessPoolExecutor to asynchronously run functions in multiple processes without overloading your pc:\nimport time\nfrom concurrent.futures import ProcessPoolExecutor\n\n\ndef background_func(task):\n time.sleep(task)\n return task\n\n\nwith ProcessPoolExecutor(max_worke... | [
1
] | [] | [] | [
"asynchronous",
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0074179655_asynchronous_multiprocessing_multithreading_python.txt |
Q:
correct path for files with PIL after compiling with pyinstaller
I'm using auto-py-to-exe which is based on pyinstaller, trying to make an executable with --onefile, using pystray to make a tray app, but after compiling I get an error that the icon file cannot be found.
See that in the code I tried to use os.path ... | correct path for files with PIL after compiling with pyinstaller | I'm using auto-py-to-exe which is based on pyinstaller, trying to make an executable with --onefile, using pystray to make a tray app, but after compiling I get an error that the icon file cannot be found.
See that in the code I tried to use os.path to get the most specific path possible, even so it is not possible to ... | [
"For future readers, the path of pyinstaller must be relative after the build, so it is necessary to add the function that creates a temporary file for the icon...\nBundling data files with PyInstaller (--onefile)\nthe solution found was to add the patch to this function and within the auto-py-to-exe set the icon f... | [
0
] | [] | [] | [
"pyinstaller",
"pystray",
"python"
] | stackoverflow_0074187387_pyinstaller_pystray_python.txt |
Q:
Concatenating images in a channel dimension from a for loop
I have a path file with 13 different images (.tiff format) and I want to concatenate all of them into an array of (13, 224, 224). I am getting the shape for all the 13 values but I still struggling to get them into the desired array. Is there a way to con... | Concatenating images in a channel dimension from a for loop | I have a path file with 13 different images (.tiff format) and I want to concatenate all of them into an array of (13, 224, 224). I am getting the shape for all the 13 values but I still struggling to get them into the desired array. Is there a way to concatenate them from the for loop?
imgs = os.listdir(path) #images... | [
"Your problem is that you are overwriting the contents of image inside your loop. One way to solve this is to build a list of the images and then convert that to an array after the loop:\nimages = []\nfor i in imgs:\n image = cv2.imread(os.path.join(path, i))\n #\n # ...\n #\n image = np.uint8(image)\n ... | [
0
] | [] | [] | [
"concatenation",
"for_loop",
"image",
"multidimensional_array",
"python"
] | stackoverflow_0074187485_concatenation_for_loop_image_multidimensional_array_python.txt |
Q:
how to remove all old versions and dependencies in azure-cli to COMPLETELY START FRESH
So i'm using azure-cli at the moment and it refuses to work with az interactive.
I'm not sure how to accomplish this correctly/completely however;
I want to REMOVE EVERYTHING and COMPLETELY re-install FRESH.
How can I get this d... | how to remove all old versions and dependencies in azure-cli to COMPLETELY START FRESH | So i'm using azure-cli at the moment and it refuses to work with az interactive.
I'm not sure how to accomplish this correctly/completely however;
I want to REMOVE EVERYTHING and COMPLETELY re-install FRESH.
How can I get this done so azure-cli will hopefully decide to work correctly again?
| [
"Just run it from a Docker container. That way each time you pull it's fresh as a daisy.\nhttps://learn.microsoft.com/en-us/cli/azure/run-azure-cli-docker\nWindows\nYou uninstall the Azure CLI from the Windows \"Apps and Features\" list. To uninstall:\n\nRemove its data from C:\\Users\\<username>\\.azure\\msal_tok... | [
0
] | [] | [] | [
"azure",
"azure_cli",
"python"
] | stackoverflow_0074187274_azure_azure_cli_python.txt |
Q:
How to use the feature_names_out with scikit's FunctionTransformer
I am trying the use feature_names_out on scikit's FunctionTransformer to get the same feature names but I get this error:
Code:
from sklearn.preprocessing import FunctionTransformer
X = pd.Series(data=[1, 2, 3], name='numbers')
transformer = Funct... | How to use the feature_names_out with scikit's FunctionTransformer | I am trying the use feature_names_out on scikit's FunctionTransformer to get the same feature names but I get this error:
Code:
from sklearn.preprocessing import FunctionTransformer
X = pd.Series(data=[1, 2, 3], name='numbers')
transformer = FunctionTransformer(np.log, feature_names_out='one-to-one')
Error:
TypeError... | [
"Please check the version of scikit-learn. feature_names_out was added only in version 1.1 so you may need to update scikit-learn.\nFrom the official documentation:\n\nfeature_names_out : callable, ‘one-to-one’ or None, default=None\nNew in version 1.1.\n\nYou can check the version with the following code:\nimport ... | [
0
] | [] | [] | [
"preprocessor",
"python",
"scikit_learn",
"scikit_learn_pipeline"
] | stackoverflow_0074186299_preprocessor_python_scikit_learn_scikit_learn_pipeline.txt |
Q:
Loop to create multiple lists, with different naming
I would like to create a loop that creates multiple lists, named differently.
I have a dataframe that contains an excel file that I am trying to filter through depending on the month. (ideally the list should be 1, 2 , 3, etc.)
Each month should create a list
In... | Loop to create multiple lists, with different naming | I would like to create a loop that creates multiple lists, named differently.
I have a dataframe that contains an excel file that I am trying to filter through depending on the month. (ideally the list should be 1, 2 , 3, etc.)
Each month should create a list
In the end I need to loop through those lists again to count... | [
"Creating lists with different names can be totally wrong idea.\nYou should rather create single list with sublisst (and indexes instead of names) or single dictinary with names as keys. Or even better you should create single DataFrame with all values (in rows or columns). It will be more useful for next calculati... | [
1
] | [] | [] | [
"conditional_statements",
"list",
"loops",
"pandas",
"python"
] | stackoverflow_0074186254_conditional_statements_list_loops_pandas_python.txt |
Q:
Making PySpark UDF access instance variable inside a Python Class
I am trying to apply a PySpark UDF to add a new column to a PySpark DataFrame inside a class. The Spark UDF has to be a static method in order to be used inside a class. The dummy example Case 1 below works fine.
The problem is that once the UDF is... | Making PySpark UDF access instance variable inside a Python Class | I am trying to apply a PySpark UDF to add a new column to a PySpark DataFrame inside a class. The Spark UDF has to be a static method in order to be used inside a class. The dummy example Case 1 below works fine.
The problem is that once the UDF is defined as static method, I cannot use any instance variable inside it... | [
"Spark UDF is meant to be self contained and is serialized and executed on the worker and not on the driver thats why it is meant to be static.\nSo, you can try the below alternative,\nYou can may be pass the variable increase to the udf as an argument like below.\n\n@staticmethod\n@udf(returnType=IntegerType())\nd... | [
1
] | [] | [] | [
"class",
"dataframe",
"pyspark",
"python",
"user_defined_functions"
] | stackoverflow_0074183680_class_dataframe_pyspark_python_user_defined_functions.txt |
Q:
Rearrange Data frame to have subcolumns in python
hey I am trying to rearrange a dataframe into one line with columns and subcolumns but i am having some trouble doing it.
I have input statistics code that looks like this :
Characteristic Total Male Female
0 Total popula... | Rearrange Data frame to have subcolumns in python | hey I am trying to rearrange a dataframe into one line with columns and subcolumns but i am having some trouble doing it.
I have input statistics code that looks like this :
Characteristic Total Male Female
0 Total population by age groups 105145.0 50080.0 55060.0
1 ... | [
"Honestly not sure if thats the best way, but you can use a combination of pivot and then reindex your df.\ndf[\"key\"] = 0 # create a common key\ncharacteristics = df[\"Characteristic\"].to_list() # save original order of Characteristic\n\n(df.pivot(index=\"key\", columns=\"Characteristic\") # pivot (create one... | [
2
] | [] | [] | [
"data_science",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074187497_data_science_dataframe_pandas_python.txt |
Q:
Find And Replace Character In Python
For the get_letter_from_user function, while using the while loop for validation, it keeps repeating the invalid input; I want to make sure that it is a single letter and lower case, and I want to make sure that it doesn't equal the second parameter of the function. I'm not sur... | Find And Replace Character In Python | For the get_letter_from_user function, while using the while loop for validation, it keeps repeating the invalid input; I want to make sure that it is a single letter and lower case, and I want to make sure that it doesn't equal the second parameter of the function. I'm not sure what I'm doing wrong, though. (and how t... | [
"To replace a letter or sequence of letters in a string, you might want to take a look at the string.replace() function:\ntext = input('Enter some text: ')\nfind = input('Enter a letter to replace: ')\nreplace_with = input(f'Enter a letter to replace \\'{find}\\' with: ')\nreplaced = text.replace(find, reolace_with... | [
0,
0,
0
] | [] | [] | [
"alphabetical",
"function",
"isalpha",
"python",
"replace"
] | stackoverflow_0074187478_alphabetical_function_isalpha_python_replace.txt |
Q:
How can I combine multiple rows (transactions) if the following transactions are closed within 30 days after the 1st transaction
this is my first post and I will try my best to describe the problem.
I have a table below to help illustrate. I am trying to combine some transactions for each Account ID. The logic I w... | How can I combine multiple rows (transactions) if the following transactions are closed within 30 days after the 1st transaction | this is my first post and I will try my best to describe the problem.
I have a table below to help illustrate. I am trying to combine some transactions for each Account ID. The logic I want is: Account AAAAA had their 1st transaction "Close Date" on 2019-12-16, if their following transactions are "closed" within 1 mont... | [
"I was able to figure it out myself using below codes, but if there is a better way, I would love to know as well.\nfrom dateutil.relativedelta import relativedelta\n\ngrouped = initial_df.groupby(by=['Account ID'])\nwindow_list = []\nfor a, b in grouped:\n window_end_date = list(b['Close Date'])[0] + dateutil.rel... | [
0
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074116671_group_by_pandas_python.txt |
Q:
ImportError: No module named 'twilio.rest.api.v2010.account.sip.domain.auth_types...'
I just registered for a Twilio account, and I installed it using pip. I am running python 3.10. I am simply trying to send a text message to myself.
My code:
from twilio.rest import Client
client = Client('my twilio account SID'... | ImportError: No module named 'twilio.rest.api.v2010.account.sip.domain.auth_types...' | I just registered for a Twilio account, and I installed it using pip. I am running python 3.10. I am simply trying to send a text message to myself.
My code:
from twilio.rest import Client
client = Client('my twilio account SID', 'my twilio auth token')
message = client.messages \
.create(
... | [
"It's because I hadn't fully installed the Twilio package using pip. After running this again to make sure I had truly installed everything:\npip install twilio\n\nI was greeted with an error\nCould not install packages due to an OSError: [Errno 2] No such file or directory\n\nUpon googling this error, it turns out... | [
0
] | [] | [] | [
"python",
"twilio",
"twilio_api"
] | stackoverflow_0074187519_python_twilio_twilio_api.txt |
Q:
How to sort nested dict based on second value
I have a dict like this: (More than 1000 records)
{"Device1": [["Device1", "TenGigabitEthernet1/0/12", "SHUT", "", "", "IDF03"], ["Device1", "TenGigabitEthernet1/0/11", "SHUT", "", "", "IDF03", "#f76f6f"]], "Device2": [["Device2", "TenGigabitEthernet1/0/12", "SHUT", ""... | How to sort nested dict based on second value | I have a dict like this: (More than 1000 records)
{"Device1": [["Device1", "TenGigabitEthernet1/0/12", "SHUT", "", "", "IDF03"], ["Device1", "TenGigabitEthernet1/0/11", "SHUT", "", "", "IDF03", "#f76f6f"]], "Device2": [["Device2", "TenGigabitEthernet1/0/12", "SHUT", "", "", "IDF03"], ["Device2", "TenGigabitEthernet1/0/... | [
"You can do this,\nwith open(\"data-dic.txt\", 'r') as dic:\n data = json.load(dic)\n d2 = OrderedDict(sorted(data.items(), key=lambda x:int(x[1][0][1].rsplit('/', 1)[-1])))\n print(d2)\n\nSorting based on the value.first_row.second_element.rsplit('/', 1)[-1]\nNB:\ndataDic = ast.literal_eval(json.dumps(dat... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074187149_python.txt |
Q:
Time before full counter with percent python
how to calculate based on timestamp and get the progress before the max full value?
def full_energy():
time_now = 1666650096 #changes every update
time_end = 1666679529
max_energy = 50
diff = datetime.utcfromtimestamp(time_now) - datetime.utcfromt... | Time before full counter with percent python | how to calculate based on timestamp and get the progress before the max full value?
def full_energy():
time_now = 1666650096 #changes every update
time_end = 1666679529
max_energy = 50
diff = datetime.utcfromtimestamp(time_now) - datetime.utcfromtimestamp(time_end)
secs = diff.total_seconds(... | [
"Something like this will work. You need to provide the start time to compute percent completed. Not sure how you want the display to function:\nfrom datetime import datetime, timedelta\nimport time\n\ndef full_energy(start, now, end):\n max_energy = 50\n percent = (now - start) / (end - start)\n current... | [
1
] | [] | [] | [
"django",
"math",
"python"
] | stackoverflow_0074187568_django_math_python.txt |
Q:
python package for traversing data structures
I spent hours trying to figure out how to subclass and modify json.JSONEncoder to override how it encodes enum.Enum instances before learning that it literally wasn't possible, and that the only solution is to traverse my data structure and convert the enums myself in ... | python package for traversing data structures | I spent hours trying to figure out how to subclass and modify json.JSONEncoder to override how it encodes enum.Enum instances before learning that it literally wasn't possible, and that the only solution is to traverse my data structure and convert the enums myself in a pre-processing step.
Then I tried finding an exis... | [
"You didn't provide an example of what you're trying to achieve, but from the description, it appears you were after something like this:\nfrom json import JSONEncoder, dumps\nfrom enum import Enum\n\n\nclass Color(Enum):\n RED = 1\n GREEN = 2\n BLUE = 3\n\n\nd = {'c': Color.RED, 'xs': [1, 3.14, Color.BLUE... | [
1
] | [] | [] | [
"encoding",
"json",
"jsonencoder",
"python",
"recursion"
] | stackoverflow_0074187706_encoding_json_jsonencoder_python_recursion.txt |
Q:
Apply str title to df columns values from dictionary values
I have a dictionary that maps column names to a function name. I have wrote a function that should capitalize the values in the df column with str.title()
import pandas as pd
data= [["English","john","smith","ohio","united states","","","manufacturing",... | Apply str title to df columns values from dictionary values | I have a dictionary that maps column names to a function name. I have wrote a function that should capitalize the values in the df column with str.title()
import pandas as pd
data= [["English","john","smith","ohio","united states","","","manufacturing","National","Residental","","",""]]
df= pd.DataFrame(data,columns=... | [
"Normally you would use apply for this, e.g.\ncols_to_capitalize = list(parsing_map.keys())\ndf[cols_to_capitalize] = df[cols_to_capitalize].apply(lambda x: x.str.title())\n\nIf you want to keep your method dictionary, I would suggest that you write the methods to act on a column, not on the dataframe. Something li... | [
2,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074187723_dataframe_pandas_python.txt |
Q:
spaCy nlp pipeline order of operations
Does anyone have a chronological list of operations performed by
import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
I can see the major components with nlp.pipe_names
['tagger', 'parser', 'ner']
and an alphabetical list of factory operations with nlp.factories
... | spaCy nlp pipeline order of operations | Does anyone have a chronological list of operations performed by
import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
I can see the major components with nlp.pipe_names
['tagger', 'parser', 'ner']
and an alphabetical list of factory operations with nlp.factories
{'merge_entities': <function spacy.language.... | [
"The answer to your question is more complicated than I originally thought, but now I will explain it in detail.\nSpaCy lemmatization usually is performed based on a lookup table. That means that is independent on the pipeline components and it lemmatization happens before the pipe. However, English language and Gr... | [
2,
1
] | [] | [] | [
"lemmatization",
"nlp",
"python",
"spacy"
] | stackoverflow_0052557058_lemmatization_nlp_python_spacy.txt |
Q:
Tkinter + MultiProcessing: Tkinter Keeps Opening Windows
I have written this code to basically opens a GUI made in Tkinter and also runs the scheduler both together every thing is working fine as long as i am running this code on PyCharm...
Now if I convert the code to exe using "PyInstaller", After i run the code... | Tkinter + MultiProcessing: Tkinter Keeps Opening Windows | I have written this code to basically opens a GUI made in Tkinter and also runs the scheduler both together every thing is working fine as long as i am running this code on PyCharm...
Now if I convert the code to exe using "PyInstaller", After i run the code the GUI keeps opening again and again until I terminate the t... | [
"This is happening because you are trying to use multiprocessing in an executable. I am assuming you are using a Windows OS as well. All you need to do is add a call to freeze_support from the multiprocessing module.\nFor example:\nfrom multiprocessing import Process, freeze_support # <-- added this\nimport tkint... | [
2
] | [] | [] | [
"multiprocessing",
"pyinstaller",
"python",
"tkinter"
] | stackoverflow_0074186441_multiprocessing_pyinstaller_python_tkinter.txt |
Q:
Detecting Keys in a Column of Strings
I have a dictionary with key and value pairs. I also have a data frame with a column containing strings that contain the various keys. If a key appears in the column in the data frame, I'd like to append the corresponding value in the adjacent column
my_dict = {'elon' : 'is ... | Detecting Keys in a Column of Strings | I have a dictionary with key and value pairs. I also have a data frame with a column containing strings that contain the various keys. If a key appears in the column in the data frame, I'd like to append the corresponding value in the adjacent column
my_dict = {'elon' : 'is awesome', 'jeff' : 'is not so awesome, but ... | [
"Below an approach using .apply() for creating the additional column. In addition to if also looping over the words of Name (Key) column values is necessary to create multiple items in the lists being values of the new DataFrame column.\nimport pandas as pd\ndf = pd.DataFrame({'Name (Key)' : ['elon musk', 'jeff bez... | [
0
] | [] | [] | [
"apply",
"dictionary",
"if_statement",
"pandas",
"python"
] | stackoverflow_0074187627_apply_dictionary_if_statement_pandas_python.txt |
Q:
Check if a set of puzzle pieces is forms a valid puzzle
I have a set of puzzle pieces (triangles and squares) of e.g. the form
{[1, 2, 3, 4], [2, 4, 5], [1 , 3, 6]}
Now, I want to check if these pieces can be put together on a grid.
A valid layout would e.g be:
A set of puzzles that would not have a valid mapping ... | Check if a set of puzzle pieces is forms a valid puzzle | I have a set of puzzle pieces (triangles and squares) of e.g. the form
{[1, 2, 3, 4], [2, 4, 5], [1 , 3, 6]}
Now, I want to check if these pieces can be put together on a grid.
A valid layout would e.g be:
A set of puzzles that would not have a valid mapping would be
{[1, 2, 3, 4], [2, 4, 5], [1 , 5, 6]}
My first ansat... | [
"I hesitate to post this, because it doesn't completely meet your requirements, but perhaps this can be a start.\nThis does as I suggested in my comments, by building up a big polygon through accretion of the individual pieces. For triangles, this is easy, but if the points of the squares are not in rotational ord... | [
0,
0,
0
] | [] | [] | [
"graph",
"planar_graph",
"python"
] | stackoverflow_0074000380_graph_planar_graph_python.txt |
Q:
Loading compressed baboon interaction data in Python
I am interested in reading the observational data and wearable sensor data available here into Python. Specifically, I would like to get them into Pandas dataframes, but even getting them into a more familiar form would effectively answer the question.
Both file... | Loading compressed baboon interaction data in Python | I am interested in reading the observational data and wearable sensor data available here into Python. Specifically, I would like to get them into Pandas dataframes, but even getting them into a more familiar form would effectively answer the question.
Both files are *.txt.gz files. I have tried to read them like this:... | [
"You're over-complicating things, pandas.read_csv will read zipped files without having to unzip them.~\ndf = pd.read_csv('http://www.sociopatterns.org/wp-content/uploads/2020/12/OBS_data.txt.gz', sep='\\t')\nprint(df.head())\n\ndf2 = pd.read_csv('http://www.sociopatterns.org/wp-content/uploads/2020/12/RFID_data.tx... | [
1
] | [] | [] | [
"byte",
"dataframe",
"gzip",
"pandas",
"python"
] | stackoverflow_0074187882_byte_dataframe_gzip_pandas_python.txt |
Q:
how to upload reels to facebook with graph api using python
I am trying to upload reel with Graph Api using Python.
I'm getting an error every time I try to upload video.
Error :
{"debug_info":{"retriable":false,"type":"NotAuthorizedError","message":"User not authorized to perform this request"}}
Note: I have giv... | how to upload reels to facebook with graph api using python | I am trying to upload reel with Graph Api using Python.
I'm getting an error every time I try to upload video.
Error :
{"debug_info":{"retriable":false,"type":"NotAuthorizedError","message":"User not authorized to perform this request"}}
Note: I have given every possible permission to my app and page.
code:
import re... | [
"Your Upload code seem bit wrong if you refer on documentation\ndef Upload(vidid, size, filedata):\n url = f\"https://rupload.facebook.com/video-upload/v13.0/{vidid}\"\n payloadUp = {\n 'Authorization': 'OAuth ' + page_access_token,\n 'offset': \"0\",\n 'file_size': str(size),\n }\n\n ... | [
0
] | [] | [] | [
"api",
"facebook",
"python",
"upload",
"video"
] | stackoverflow_0074098634_api_facebook_python_upload_video.txt |
Q:
How can I upgrade Python version and packages in pyenv virtualenv?
I used pyenv, pyenv-virtualenv for managing python virtual environment.
I have a project working in Python 3.4 virtual environment.
So all installed packages(pandas, numpy etc) are not newest version.
What I want to do is to upgrade Python version ... | How can I upgrade Python version and packages in pyenv virtualenv? | I used pyenv, pyenv-virtualenv for managing python virtual environment.
I have a project working in Python 3.4 virtual environment.
So all installed packages(pandas, numpy etc) are not newest version.
What I want to do is to upgrade Python version from 3.4 to 3.6 as well as upgrade other package version to higher one.
... | [
"Here is how you can switch to 3.9.0 for a given virtual environement venv-name:\npip freeze > requirements-lock.txt\npyenv virtualenv-delete venv-name\npyenv virtualenv 3.9.0 venv-name\npip install -r requirements-lock.txt\n\nOnce everything works correctly you can safely remove the temporary requirements lock fil... | [
26,
13,
1
] | [
"If you use anaconda, just type \nconda install python==$pythonversion$\n"
] | [
-4
] | [
"pyenv",
"python",
"virtualenv"
] | stackoverflow_0044692668_pyenv_python_virtualenv.txt |
Q:
Using Pandas, I need to merge 2 dataframes, from the second df I need only the values with the nearest timestamp...?
I'm sorry if this is confusing. Newbie here. I have 2 data frames that contain data from different patients.
The first dataframe (df1) contains results for testA, the results are recorded many times... | Using Pandas, I need to merge 2 dataframes, from the second df I need only the values with the nearest timestamp...? | I'm sorry if this is confusing. Newbie here. I have 2 data frames that contain data from different patients.
The first dataframe (df1) contains results for testA, the results are recorded many times per day:
Patient TestA Time(A)
0 1 617.0 2019-12-07 13:21:15.22415... | [
".merge_of is what you need. Make sure Time columns are datetime and sorted prior to merging.\ndf1[\"Time(A)\"] = pd.to_datetime(df1[\"Time(A)\"])\ndf1 = df1.sort_values([\"Time(A)\"], ascending=[1])\ndf2[\"Time(B)\"] = pd.to_datetime(df2[\"Time(B)\"])\ndf2 = df2.sort_values([\"Time(B)\"], ascending=[1])\n\nmerged ... | [
3,
2
] | [] | [] | [
"merge",
"pandas",
"python"
] | stackoverflow_0074187735_merge_pandas_python.txt |
Q:
Why is torch.clamp in pytorch not working?
When I was training my nn, something really wired happened.
res = torch.clamp(res_not_clamp, 0.0, 1.0)
if torch.isnan(res).any() or res.max()> 1.0 :
raise ValueError("NAN! Stop Training")
Here torch.clamp is supposed to limit the value of res, but it still raises th... | Why is torch.clamp in pytorch not working? | When I was training my nn, something really wired happened.
res = torch.clamp(res_not_clamp, 0.0, 1.0)
if torch.isnan(res).any() or res.max()> 1.0 :
raise ValueError("NAN! Stop Training")
Here torch.clamp is supposed to limit the value of res, but it still raises the ValueError.
I insert a breakpoint here at the ... | [
"torch.clamp does not modify the possible nan values in your data, they will still be nan after the clamp.\nSo what's probably happening is that the first part of your if (torch.isnan(res).any()) is triggering the raise of the ValueError.\n"
] | [
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074183588_python_pytorch.txt |
Q:
ValueError: need at least one array to concatenate
I am having issues with
ValueError: need at least one array to concatenate
Below is the whole error message.
Training mode
Traceback (most recent call last):
File "bcf.py", line 342, in <module>
bcf.train()
File "bcf.py", line 321, in train
sel... | ValueError: need at least one array to concatenate | I am having issues with
ValueError: need at least one array to concatenate
Below is the whole error message.
Training mode
Traceback (most recent call last):
File "bcf.py", line 342, in <module>
bcf.train()
File "bcf.py", line 321, in train
self._learn_codebook()
File "bcf.py", line 142, in _learn... | [
"the problem comes from the lenght of your array. Check if your array/list is longer than to 0 print(len(feats_sc)).\nDon't forget to checkout the documentation numpy.concatenate — NumPy v1.16 Manual\n",
"The problem seems to be in np.concatenate where it expects an array of arrays and it's not receiving that.\nR... | [
3,
1,
1
] | [] | [] | [
"python",
"valueerror"
] | stackoverflow_0054967688_python_valueerror.txt |
Q:
google sheets api error: Details: "Invalid values[1][0]: list_value
Friends, I ask for help to make changes to google sheets. I need to write the following list in column B:
list = ['14.588,61\n224.715,38\n2.994,21\n308.782,90\n , 24.588,61\n324.715,38\n5.994,21\n508.782,90']
But it returns the following error.
<... | google sheets api error: Details: "Invalid values[1][0]: list_value | Friends, I ask for help to make changes to google sheets. I need to write the following list in column B:
list = ['14.588,61\n224.715,38\n2.994,21\n308.782,90\n , 24.588,61\n324.715,38\n5.994,21\n508.782,90']
But it returns the following error.
<HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadshee... | [
"At \"Method: spreadsheets.values.update\", values is required to be 2 dimensional array. In your script, it is 3 dimensional array by valores_adicionar.append(q), because q is 2 dimensional array. I thought that this is the reason for your current issue of Invalid values[1][0].\nAbout when I change range=\"B2:B\" ... | [
2
] | [] | [] | [
"google_sheets",
"google_sheets_api",
"python",
"python_requests"
] | stackoverflow_0074187547_google_sheets_google_sheets_api_python_python_requests.txt |
Q:
Pyinstaller: Why some command actions don't work?
I designed a simple Python GUI with Tkinter. It includes a button which performs an action when it is pressed. Originally, it opens a new subprocess in order to run an external software. The code works fine when ran like a script, but when I converted into an appli... | Pyinstaller: Why some command actions don't work? | I designed a simple Python GUI with Tkinter. It includes a button which performs an action when it is pressed. Originally, it opens a new subprocess in order to run an external software. The code works fine when ran like a script, but when I converted into an application using Pyinstaller it doesn't work. No errors or ... | [
"tkinter.messagebox is a module and needs to be imported separately and explicitly with the rest of your imports in order to use it.\nTo solve your problem all you need to do is add an import statement:\nimport sys\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport tkinter.messagebox # <-- added this\nfrom t... | [
1
] | [] | [] | [
"pyinstaller",
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0074182175_pyinstaller_python_python_3.x_tkinter.txt |
Q:
Python requests: POST request dropping Authorization header
I'm trying to make an API POST request using the Python requests library. I am passing through an Authorization header but when I try debugging, I can see that the header is being dropped. I have no idea what's going on.
Here's my code:
access_token = get... | Python requests: POST request dropping Authorization header | I'm trying to make an API POST request using the Python requests library. I am passing through an Authorization header but when I try debugging, I can see that the header is being dropped. I have no idea what's going on.
Here's my code:
access_token = get_access_token()
bearer_token = base64.b64encode(bytes("'Bearer {}... | [
"TLDR\nThe url you are requesting redirects POST requests to a different host, so the requests library drops the Authoriztion header in fear of leaking your credentials. To fix that you can override the responsible method in requests' Session class.\nDetails\nIn requests 2.4.3, the only place where reqeuests remove... | [
20,
2,
0,
0,
0,
0
] | [
"you can try to use a custom authorization in headers.\nDefine a custom authentication class:\nclass MyAuth(requests.auth.AuthBase):\ndef __init__(self, bearer_token):\n self.username = None\n self.bearer_token = bearer_token\n\ndef __call__(self, r):\n r.headers['Authorization'] = self.bearer_token\n r... | [
-1,
-1
] | [
"authorization_header",
"http",
"http_headers",
"python",
"python_requests"
] | stackoverflow_0060358216_authorization_header_http_http_headers_python_python_requests.txt |
Q:
How do I make my image recourses synchronize for clients when they change on the host?
I am currently working with pyramid and have a png that changes as users interact with the site. I would like it to update on the client when it is modified on the server. As of now you have to refresh the page to see the newest... | How do I make my image recourses synchronize for clients when they change on the host? | I am currently working with pyramid and have a png that changes as users interact with the site. I would like it to update on the client when it is modified on the server. As of now you have to refresh the page to see the newest version but I would like this to be automatic. My current project has the relevant code sta... | [
"\"Normal\" web is one-way: the client requests a resource from the server, the server returns a response, done. The server in this model is always passive - there's no way for the server to initiate a connection to the client, it only responds to requests. So, in this model your only option is to periodically poll... | [
1
] | [] | [] | [
"pyramid",
"python",
"reactive_programming"
] | stackoverflow_0074183812_pyramid_python_reactive_programming.txt |
Q:
Matrix size incompatible: ln[0] : [1:43264], ln[16,512]
I want to build a model that classifies and predicts words from the users lips. With adverb a total of 142657 images that have been preproccessed using the dataset of videos of individual speakers but I get this error when running the model and doesnt even g... | Matrix size incompatible: ln[0] : [1:43264], ln[16,512] | I want to build a model that classifies and predicts words from the users lips. With adverb a total of 142657 images that have been preproccessed using the dataset of videos of individual speakers but I get this error when running the model and doesnt even get past the first epoch
heres my code
import os
from silence_... | [
"Seems like you have two matrices (one 1x43265 and one 16x512). You try to multiply them but its product is mathematically not defined. You need one matrix to be a (a x b) matrix and the other to be a (b x c) matrix. Thats why your program can't run. If your images are a test dataset try to follow the instructions ... | [
0,
0
] | [] | [] | [
"deep_learning",
"keras",
"python",
"tensorflow"
] | stackoverflow_0074187600_deep_learning_keras_python_tensorflow.txt |
Q:
how to count how many lines each function has in a Python file?
I'm doing research on software engineering.
I need to measure how many lines each function or class has in each file.
Another interesting metric would be the number of functions and the cyclomatic complexity of each one.
A:
You can do something like... | how to count how many lines each function has in a Python file? | I'm doing research on software engineering.
I need to measure how many lines each function or class has in each file.
Another interesting metric would be the number of functions and the cyclomatic complexity of each one.
| [
"You can do something like this\nimport inspect\n\ndef test(param1, param2):\n print(param1, param2)\n print(1+1)\n\ninspect.getsource(test)\n# 'def test(param1, param2):\\n print(param1, param2)\\n print(1+1)\\n'\n\ninspect.getsource(test).count(\"\\n\")\n# 3\n\n"
] | [
0
] | [] | [] | [
"architecture",
"metrics",
"performance",
"python",
"software_quality"
] | stackoverflow_0074187983_architecture_metrics_performance_python_software_quality.txt |
Q:
How to open a trade requests to BingX API
I'm working on Python to make some connections with te BingX API for Perpetual Futures an the documentation in
https://github.com/BingX-API/BingX-swap-api-doc/blob/master/Perpetual_Swap_API_Documentation.md
My problem is when I try to open a possition, my signature to the ... | How to open a trade requests to BingX API | I'm working on Python to make some connections with te BingX API for Perpetual Futures an the documentation in
https://github.com/BingX-API/BingX-swap-api-doc/blob/master/Perpetual_Swap_API_Documentation.md
My problem is when I try to open a possition, my signature to the API is already ok because the others endpoints ... | [
"that's not a code issue. it seems like your fund is not in perpetual trading account. I assume either it's in standard future account or fund account.\n"
] | [
0
] | [] | [] | [
"exchange_server",
"python",
"signature"
] | stackoverflow_0074166290_exchange_server_python_signature.txt |
Q:
detatch option using chromedriver in Python
detatch doesn't seem to work at all. The script I have (when ran in command prompt as opposed to idle) closes the window when done. I thought adding detach as an option would prevent this.
What can I do to prevent this chromedriver window from closing when finished? why ... | detatch option using chromedriver in Python | detatch doesn't seem to work at all. The script I have (when ran in command prompt as opposed to idle) closes the window when done. I thought adding detach as an option would prevent this.
What can I do to prevent this chromedriver window from closing when finished? why doesnt this work?
Code:
from selenium.webdriver.s... | [
"Instead of adding the argument you need to add an experimental_option as follows:\nimport selenium.webdriver.chrome.options as Options\n\nchrome_options = Options()\nchrome_options.add_experimental_option(\"detach\", True)\n\n",
"\"undetected Selenium\" is correct to a point, however the way it is exampled, does... | [
0,
0
] | [] | [] | [
"detach",
"google_chrome",
"python",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0071940292_detach_google_chrome_python_selenium_selenium_chromedriver.txt |
Q:
how do I get the slurm job id?
#!/bin/bash
#SBATCH -N 1 # nodes requested
#SBATCH -n 1 # tasks requested
#SBATCH -c 4 # cores requested
#SBATCH --mem=10 # memory in Mb
#SBATCH -o outfile # send stdout to outfile
#SBATCH -e errfile # send stderr to errfile
#SBATCH -t 0:01:00 # time requested in h... | how do I get the slurm job id? | #!/bin/bash
#SBATCH -N 1 # nodes requested
#SBATCH -n 1 # tasks requested
#SBATCH -c 4 # cores requested
#SBATCH --mem=10 # memory in Mb
#SBATCH -o outfile # send stdout to outfile
#SBATCH -e errfile # send stderr to errfile
#SBATCH -t 0:01:00 # time requested in hour:minute:second
module load anaco... | [
"You can just read it from environment variable, slurm will set SLURM_JOB_ID for the batch script.\nmodule load anaconda\npython hello.py $SLURM_JOB_ID\n\nFor all the environment variables that are available in the batch script, you can find them here: OUTPUT ENVIRONMENT VARIABLES\n",
"You can use squeue. Followi... | [
2,
1
] | [] | [] | [
"bash",
"linux",
"python",
"sbatch",
"slurm"
] | stackoverflow_0073186840_bash_linux_python_sbatch_slurm.txt |
Q:
Python pygame not installing
C:\Users\matth>pip3 install pygame
Collecting pygame
Using cached pygame-2.1.2.tar.gz (10.1 MB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error
× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [80 lines of output]
WARNING, No "Setup"... | Python pygame not installing | C:\Users\matth>pip3 install pygame
Collecting pygame
Using cached pygame-2.1.2.tar.gz (10.1 MB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error
× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [80 lines of output]
WARNING, No "Setup" File Exists, Running "buildconfig... | [
"Short answer\npip install pygame --pre is necessary right now due to your Python version\nLong answer\nYour traceback shows you are using Python 3.11, which was just released earlier today. Pygame is a \"C extension\" and needs to re-release itself with new \"wheels\" (binaries) for every new minor release of Pyth... | [
14
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074188013_pygame_python.txt |
Q:
In Python, how to efficiently extract sublist from a list based on a list of 0/1, where locations with 1 is selected?
I have a list called all=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], and another list called sub=[1, 0, 1, 0, 1, 1, 0, 0, 0, 0], I want to create a new list based on all by extracting only elements whose corre... | In Python, how to efficiently extract sublist from a list based on a list of 0/1, where locations with 1 is selected? | I have a list called all=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], and another list called sub=[1, 0, 1, 0, 1, 1, 0, 0, 0, 0], I want to create a new list based on all by extracting only elements whose corresponding value in the list named sub is 1, i.e., I want to generate aa=[0,2,4,5]. It would be great if this could be done a... | [
"You could do it with a simple list comprehension:\naa = [x for x,s in zip(lst,sub) if s == 1]\n\nYou would need to time it to see if it is fast enough for your needs.\n(As an aside using all as the list name overwrites the built-in function with the same name).\n"
] | [
1
] | [] | [] | [
"boolean",
"list",
"python"
] | stackoverflow_0074187977_boolean_list_python.txt |
Q:
Generating skewed float random variables distribution in the domain [0,1]
I want to generate random float variables in python with the following characteristics:
The domain is [0,1] (or very close to it)
The mean isn't always 0.5, and it should be between [0,1]
Clearly, it's definitely a skewed distribution. I'... | Generating skewed float random variables distribution in the domain [0,1] | I want to generate random float variables in python with the following characteristics:
The domain is [0,1] (or very close to it)
The mean isn't always 0.5, and it should be between [0,1]
Clearly, it's definitely a skewed distribution. I've experimented with scaled skewed normal distributions in scipy without gettin... | [
"I'm not sure if this is exactly what you're looking for, but you could try using random.triangular. According to the documentation, the default arguments result in a symmetric distribution with values between 0 and 1. However, if we change mode, we can generate a skewed distribution:\ndef generate_random(m, length... | [
1
] | [] | [] | [
"python",
"random"
] | stackoverflow_0074187891_python_random.txt |
Q:
Using a dict comprehension transform dataframe columns into dict
I've got this DataFrame:
country
city
Argentina
Buenos Aires
Bangladesh
Dhaka
Brasil
Sao Paulo, Rio de Janeiro
I would like to get a dictionary using a dict comprehension:
{Argentina:[Buenos Aires], Bangladesh:[Dhaka], Brasil:[Sao Paulo, Rio de ... | Using a dict comprehension transform dataframe columns into dict | I've got this DataFrame:
country
city
Argentina
Buenos Aires
Bangladesh
Dhaka
Brasil
Sao Paulo, Rio de Janeiro
I would like to get a dictionary using a dict comprehension:
{Argentina:[Buenos Aires], Bangladesh:[Dhaka], Brasil:[Sao Paulo, Rio de Janeiro]}
x = {k : column.values() for k, column in df.to_... | [
"Here's a trick to split and clean the values lists.\nnew_dict = {row['country']:list(map(lambda x: x.strip(), row['city'].split(','))) for _, row in df.iterrows()}\n\n"
] | [
1
] | [] | [] | [
"dictionary",
"dictionary_comprehension",
"pandas",
"python"
] | stackoverflow_0074187981_dictionary_dictionary_comprehension_pandas_python.txt |
Q:
Can anyone tell me how can I change mask the foreground if I know the color range of background in RGB?
all of you,
Here is the image;
The exact background color is in RGB; (246, 46, 100)
I have tried several methods but those are too slow, one of the methods is below;
new_image = Image.open("image-from-rawpixel-... | Can anyone tell me how can I change mask the foreground if I know the color range of background in RGB? | all of you,
Here is the image;
The exact background color is in RGB; (246, 46, 100)
I have tried several methods but those are too slow, one of the methods is below;
new_image = Image.open("image-from-rawpixel-id-6649116-original.png")
img_up = np.asarray(new_image)
for ind1, i in enumerate(tqdm(img_up)):
for ind... | [
"First you could read image using cv2.imread() and you get directly numpy.array.\nYou can use numpy image[ mask ] = [0,0,0] to assign value to many pixels in milliseconds.\nFor exact color you can create mask using img == (100, 46, 247).\ncv2 keeps image as BGR instead of RGB so it needs (100,46,247) instead of (24... | [
3,
2
] | [] | [] | [
"image_preprocessing",
"opencv",
"python",
"python_imaging_library"
] | stackoverflow_0074186362_image_preprocessing_opencv_python_python_imaging_library.txt |
Q:
how to divide between values in inline dictionary
I have studied here and here, but still fail too.
this is my code:
d1 = {"Overall_Value" : 21600, "Unit_Number": 48}
i just want to divide value in dictionary 21600/48
The output I want is: 450.
Thank you
Any help will be highly appreciated.
A:
If I am understan... | how to divide between values in inline dictionary | I have studied here and here, but still fail too.
this is my code:
d1 = {"Overall_Value" : 21600, "Unit_Number": 48}
i just want to divide value in dictionary 21600/48
The output I want is: 450.
Thank you
Any help will be highly appreciated.
| [
"If I am understanding your question correctly you actually do not need to use a dictionary comprhension here, just simple dictionary access and division.\nTry this runnable example:\n\n\n#!/usr/bin/env python\n\nd1 = {\"Overall_Value\" : 21600, \"Unit_Number\": 48}\nr = d1[\"Overall_Value\"]/d1[\"Unit_Number\"]\np... | [
3
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074188107_dictionary_python.txt |
Q:
How could I modify a variable inside of a function? **SOLVED**
May be a little bit different than it sounds. I'm trying to make a function that takes a variable, a string, and an output variable. It should look and see if the string is in the variable, and it works perfectly (I used different code where it would j... | How could I modify a variable inside of a function? **SOLVED** | May be a little bit different than it sounds. I'm trying to make a function that takes a variable, a string, and an output variable. It should look and see if the string is in the variable, and it works perfectly (I used different code where it would just print an output string if the target string is found), except fo... | [
"You do not have to input the variable into the function parameters in order to modify it, although I do not recommend doing this. Here is the answer to your problem:\ndef IfIn(var, string):\n global output\n if string in var:\n output = True\n return output\n\noutput = False\nstring = \"Banana\... | [
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074188145_function_python.txt |
Q:
I have a question about my coding homework about lists and dictionaries. Can anyone help explain what to do?
I have a question about my coding homework about lists and dictionaries. I understand up until question 4, and that is where I get stuck. Can anyone help explain what to do?
Creates a list.
Alters the con... | I have a question about my coding homework about lists and dictionaries. Can anyone help explain what to do? | I have a question about my coding homework about lists and dictionaries. I understand up until question 4, and that is where I get stuck. Can anyone help explain what to do?
Creates a list.
Alters the contents of the list.
Extracts one item from the list and saves it as a variable.
Stores the value in a dictionary ... | [
"You can get the horse item by specifying only it's index, there is no need to use slicing like you did:\nhorse = animals[3]\n\nA dictionary in python is simply a key-value pair container which associates each unique key with only one value for example:\ndictionary = dict()\ndictionary['animal'] = horse\n\nHere we ... | [
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074188115_dictionary_python.txt |
Q:
How to find common items across dictionaries where values can be lists
I have multiple dictionaries of varying size in a list which I want to find common items across.
Some of these dictionaries can have a list of dictionaries as some of the values.
Order does not matter so two sets of dictionary items are common ... | How to find common items across dictionaries where values can be lists | I have multiple dictionaries of varying size in a list which I want to find common items across.
Some of these dictionaries can have a list of dictionaries as some of the values.
Order does not matter so two sets of dictionary items are common regardless of order of keys. Two lists are common as long as the set of valu... | [
"def extract_common_values(d1, d2):\n common = {}\n for key in d1:\n v1 = d1[key]\n v2 = d2.get(key)\n if isinstance(v1, list) and isinstance(v2, list):\n if all(x in v1 for x in v2) and all(x in v2 for x in v1):\n common[key] = v1\n elif v1 == v2:\n ... | [
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074188083_dictionary_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.