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:
Drawing a huge graph with networkX and matplotlib
I am drawing a graph with around 5K nodes in it using networkX and matplotlib. The GTK window by matplotlib has tools to zoom and visualise the graph.
Is there any way, I can save a magnified version for proper visualisation later?
import matplotlib.pyplot as plt
... | Drawing a huge graph with networkX and matplotlib | I am drawing a graph with around 5K nodes in it using networkX and matplotlib. The GTK window by matplotlib has tools to zoom and visualise the graph.
Is there any way, I can save a magnified version for proper visualisation later?
import matplotlib.pyplot as plt
import networkx as nx
pos=nx.spring_layout(G) #G is ... | [
"You have two easy options:\nUp the DPI\nplt.savefig(\"graph.png\", dpi=1000)\n\n(larger image file size)\nSave as a PDF\nplt.savefig(\"graph.pdf\")\n\nThis is the best option, as the final graph is not rasterized. In theory, you should be able to zoom in indefinitely. \n",
"While not in GTK, you might want to ch... | [
33,
2,
1,
0
] | [] | [] | [
"graph",
"matplotlib",
"networkx",
"python"
] | stackoverflow_0009402255_graph_matplotlib_networkx_python.txt |
Q:
Python Libraries are not importing into Pycharm
I am using Pycharm and I have the latest versions, I reinstalled everything today.
I want to install requests and BeautifulSoup and I do it with Pycharm settings and Python Interpreter. I add them there and click OK. I handle the path and all, but it keeps showing my... | Python Libraries are not importing into Pycharm | I am using Pycharm and I have the latest versions, I reinstalled everything today.
I want to install requests and BeautifulSoup and I do it with Pycharm settings and Python Interpreter. I add them there and click OK. I handle the path and all, but it keeps showing my import is unused or does not exist.
When I type: imp... | [
"It's not an error, it's only a warning. Pycharm is telling you that you have imported a library but you're not using this library (request). If you use the library the warning disappears\n"
] | [
0
] | [] | [] | [
"import",
"pip",
"python",
"python_idle",
"shared_libraries"
] | stackoverflow_0074657661_import_pip_python_python_idle_shared_libraries.txt |
Q:
Create a new storj bucket with uplink-Python
I'm trying to create a new storj bucket with uplink-python
Does anyone know this error ?
Thank you
class Storage:
def __init__(self, api_key: str, satellite: str, passphrase: str, email: str):
"""
account Storj
"""
self.api_key = api_key
self.sa... | Create a new storj bucket with uplink-Python | I'm trying to create a new storj bucket with uplink-python
Does anyone know this error ?
Thank you
class Storage:
def __init__(self, api_key: str, satellite: str, passphrase: str, email: str):
"""
account Storj
"""
self.api_key = api_key
self.satellite = satellite
self.email = email
sel... | [
"Solved:\nan upper case letter in the bucket name causes the internal error...\nreplace\nstorage.create_bucket(\"Hello\")\n\nwith\nstorage.create_bucket(\"hello\")\n\n:)\nEDIT:\nthat's why:\nhttps://forum.storj.io/t/bucket-name-uppercase/20554/2?u=mike1\n"
] | [
0
] | [] | [] | [
"amazon_s3",
"go",
"python"
] | stackoverflow_0074649328_amazon_s3_go_python.txt |
Q:
Using .expr() and arithmetics: how to add multiple (calculated) columns to dataframe within one expression
So I have a spark dataframe with some columns and I want to add some new columns which are the product of the initial columns: new_col1 = col_1 * col_2 & new_col2 = col_3 * col_4.
See the data frames below a... | Using .expr() and arithmetics: how to add multiple (calculated) columns to dataframe within one expression | So I have a spark dataframe with some columns and I want to add some new columns which are the product of the initial columns: new_col1 = col_1 * col_2 & new_col2 = col_3 * col_4.
See the data frames below as an example.
df=
| id | col_1| col_2| col_3| col_4|
|:---|:----:|:-----|:-----|:-----|
|1 | a | x | d1... | [
"I don't think that expr can do what you are trying to do. However, you don't have to concatenate all your expressions and use a single expr, instead you can do something like this\ndf_new = (\n df\n .select(\n *(col_lst + [expr(nc) for nc in new_col_list])\n ) \n\n\n... | [
0
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"arithmetic_expressions",
"python"
] | stackoverflow_0074630581_apache_spark_apache_spark_sql_arithmetic_expressions_python.txt |
Q:
_tkinter.TclError: image "score6" doesn't exist
Hello so I've been trying to solve this problem but cant find anything I tried dictionaries and exec. How can I use string value as a variable name? I have a problem when I define a variable name in a string and try to make a button with the image it shows error - _t... | _tkinter.TclError: image "score6" doesn't exist | Hello so I've been trying to solve this problem but cant find anything I tried dictionaries and exec. How can I use string value as a variable name? I have a problem when I define a variable name in a string and try to make a button with the image it shows error - _tkinter.TclError: image "score6" doesn't exist, but if... | [
"You could do this using eval\nimg = eval('score' + str(correct))\n\nbut this is dangerous if correct is provided by the user. A better approach is to use a list\nimages = [ImageTk.PhotoImage(Image.open(\"scores/09.png\")),\n ImageTk.PhotoImage(Image.open(\"scores/19.png\")),\n ImageTk.PhotoImage... | [
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074656689_python_tkinter.txt |
Q:
How to add search other field in many2one?
HI I have a customer field and the default search is by name, and I want to add a search by barcode as well to the customer field
I have tried adding a barcode(partner_id.barcode) on the domain as below, but it still doesn't work (model = sale.order)
@api.model
def _... | How to add search other field in many2one? | HI I have a customer field and the default search is by name, and I want to add a search by barcode as well to the customer field
I have tried adding a barcode(partner_id.barcode) on the domain as below, but it still doesn't work (model = sale.order)
@api.model
def _name_search(self, name, args=None, operator='ili... | [
"The barcode field in res.partner is a property field and stored in ir.property model which name is Company Propeties in Odoo and you can access it with developer mode from Settings -> Technical -> Company Propeties.\nThe _name_search method for res.partner enable you to search in any Many2one partner relation fiel... | [
0
] | [] | [] | [
"erp",
"odoo",
"odoo_14",
"python"
] | stackoverflow_0074651848_erp_odoo_odoo_14_python.txt |
Q:
Python (NumPy): Memory efficient array multiplication with fancy indexing
I'm looking to do fast matrix multiplication in python, preferably NumPy, of an array A with another array B of repeated matrices by using a third array I of indices. This can be accomplished using fancy indexing and matrix multiplication:
f... | Python (NumPy): Memory efficient array multiplication with fancy indexing | I'm looking to do fast matrix multiplication in python, preferably NumPy, of an array A with another array B of repeated matrices by using a third array I of indices. This can be accomplished using fancy indexing and matrix multiplication:
from numpy.random import rand, randint
A = rand(1000,5,5)
B = rand(40000000,5,1... | [
"If you're open to another package, you could wrap it up with dask.\nfrom numpy.random import rand, randint\nfrom dask import array as da\n\nA = da.from_array(rand(1000,5,5))\nB = da.from_array(rand(40000000,5,1))\nI = da.from_array(randint(low=0, high=1000, size=40000000))\n\nfancy = A[I] @ B\n\n\nAfter finished m... | [
1
] | [] | [] | [
"memory",
"numpy",
"python",
"vectorization"
] | stackoverflow_0074657420_memory_numpy_python_vectorization.txt |
Q:
Mac run python script with double click
I'm trying to make an automator application to run a python script so I can double click the icon and start the script.
it doesn't give me an error but it does nothing.
#!/bin/bash
echo Running Script
python /Desktop/test.py
echo Script ended
I also tried with a Shell sc... | Mac run python script with double click | I'm trying to make an automator application to run a python script so I can double click the icon and start the script.
it doesn't give me an error but it does nothing.
#!/bin/bash
echo Running Script
python /Desktop/test.py
echo Script ended
I also tried with a Shell script .sh with the same code.
it was working ... | [
"A shell of Automator has different PATH, setopt, and other values from your shell in terminal. Therefore the script in your Automator won't work exactly the same in your shell.\nTo make it work, you need to use an absolute path of the python command.\nRun this command in your terminal to get the absolute path.\nwh... | [
0
] | [] | [] | [
"automator",
"macos",
"python"
] | stackoverflow_0074657989_automator_macos_python.txt |
Q:
Trying to apply fit_transofrm() function from sklearn.compose.ColumnTransformer class on array but getting "tuple index out of range" error
I am beginner in ML/AI and trying to do pre-proccesing on my dataset of digits that I've made myself. I want to apply OneHotEncoding on my categorical variable (which is a dep... | Trying to apply fit_transofrm() function from sklearn.compose.ColumnTransformer class on array but getting "tuple index out of range" error | I am beginner in ML/AI and trying to do pre-proccesing on my dataset of digits that I've made myself. I want to apply OneHotEncoding on my categorical variable (which is a dependent one,idk if it is important) but getting "tuple index out of range" error. I was searching on the internet and the only solution was to use... | [
"This is because ct = ColumnTransformer(transformers=[('encoder',OneHotEncoder(),[29])],remainder = 'passthrough') will one-hot encode the column of index 29.\nYou are fit-transforming y which only has 1 column. You can change the 29 to 0.\nct = ColumnTransformer(transformers=[('encoder',OneHotEncoder(),[0])],remai... | [
0
] | [] | [] | [
"artificial_intelligence",
"data_preprocessing",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074657678_artificial_intelligence_data_preprocessing_machine_learning_python_scikit_learn.txt |
Q:
How to real count repeated string in string in python?
I am sorry that I am not sure my question is correct or clear enough. However, I hope the example below can explain my question:
As what you see
print("abbbbbbc".count("bbb")) #–output is 2
But I want the result is 4, because bbbbbb has 6 characters and can b... | How to real count repeated string in string in python? | I am sorry that I am not sure my question is correct or clear enough. However, I hope the example below can explain my question:
As what you see
print("abbbbbbc".count("bbb")) #–output is 2
But I want the result is 4, because bbbbbb has 6 characters and can breakdown as below:
bbb---
-bbb--
--bbb-
---bbb
I couldn't fi... | [
"You can implement your own logic, like this:\na = \"abbbbbbc\"\nb = \"bbb\"\n\ncount = 0\nfor i in range(len(a) - len(b)):\n if a[i:i+len(b)] == b:\n count += 1\nprint(count)\n\nOR\ncount = 0\nfor i in range(len(a)):\n if a[i:].startswith(b):\n count += 1\nprint(count)\n\nOR\ncount = sum([1 if ... | [
1
] | [] | [] | [
"count",
"python",
"string"
] | stackoverflow_0074657986_count_python_string.txt |
Q:
Export SQL Script from SQLAlchemy
I am using SQLAlchemy with ORM and DeclarativeMeta to connect to my Database.
Is there a way to generate or export a .sql file that contains all the Create Tables Commands?
Thank you!
I tried to get that information from my Meta Object or even from my SQLAlchemy Engine but they do... | Export SQL Script from SQLAlchemy | I am using SQLAlchemy with ORM and DeclarativeMeta to connect to my Database.
Is there a way to generate or export a .sql file that contains all the Create Tables Commands?
Thank you!
I tried to get that information from my Meta Object or even from my SQLAlchemy Engine but they don't hold information like that.
Even th... | [
"Found an answers in the documentation of sqlalchemy.\nfrom sqlalchemy.schema import CreateTable\nprint(CreateTable(my_mysql_table).compile(mysql_engine))\n\nCREATE TABLE my_table (\nid INTEGER(11) NOT NULL AUTO_INCREMENT,\n...\n)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n\nSQLAlchemy Documentation!\n"
] | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074657665_python_sqlalchemy.txt |
Q:
How to remove margins from PDF? (Generated using WeasyPrint)
I am trying to render a PDF document within my Flask application. For this, I am using the following HTML template:
<!DOCTYPE html>
<html>
<head>
<style>
@page {
margin:0
}
h1 {
color:white;
}
.header{
backgro... | How to remove margins from PDF? (Generated using WeasyPrint) | I am trying to render a PDF document within my Flask application. For this, I am using the following HTML template:
<!DOCTYPE html>
<html>
<head>
<style>
@page {
margin:0
}
h1 {
color:white;
}
.header{
background: #0a0045;
height: 250px;
}
.center {
p... | [
"Maybe you forgot \" ; \" or/and \" mm \",\nit works:\n@page {\n size: A4; /* Change from the default size of A4 */\n margin: 0mm; /* Set margin on each page */\n }\n\n",
"The weasyprint uses 3 sources of css, one of them is default user agent stylesheet\n(https://doc.courtbouillon.org/weasypri... | [
13,
0
] | [] | [] | [
"flask",
"margin",
"pdf",
"python",
"weasyprint"
] | stackoverflow_0058175484_flask_margin_pdf_python_weasyprint.txt |
Q:
Count the digits in a number
I have written a function called count_digit:
# Write a function which takes a number as an input
# It should count the number of digits in the number
# And check if the number is a 1 or 2-digit number then return True
# Return False for any other case
def count_digit(num):
if (nu... | Count the digits in a number | I have written a function called count_digit:
# Write a function which takes a number as an input
# It should count the number of digits in the number
# And check if the number is a 1 or 2-digit number then return True
# Return False for any other case
def count_digit(num):
if (num/10 == 0):
return 1
e... | [
"convert the integer to a string, and then use the len() method on the converted string. Unless you also consider taking floats as input too, and not integers exclusively.\n",
"This is a Python3 behaviour. / returns float and not integer division.\nChange your code to:\ndef count_digit(num):\n if (num//10 == 0... | [
1,
1,
0,
0,
0
] | [] | [] | [
"count",
"filter",
"python"
] | stackoverflow_0070258942_count_filter_python.txt |
Q:
How can I create for each category a horizontal bar plot that consists of shares
I have the following df
type eur_d asia_d amer_d
0 cat1 0.58 0.30 0.12
1 cat2 0.50 0.29 0.21
2 cat3 0.50 0.30 0.20
3 cat4 0.42 0.31 0.27
4 cat5 0.42 0.37 0.20
5 cat6 ... | How can I create for each category a horizontal bar plot that consists of shares | I have the following df
type eur_d asia_d amer_d
0 cat1 0.58 0.30 0.12
1 cat2 0.50 0.29 0.21
2 cat3 0.50 0.30 0.20
3 cat4 0.42 0.31 0.27
4 cat5 0.42 0.37 0.20
5 cat6 0.60 0.21 0.19
6 cat7 0.26 0.50 0.24
7 cat8 0.54 0.17 0.... | [
"If you mean stacked horizontal bar chart, this can help.\ndf.plot.barh(x=\"type\", stacked=True, figsize=(10, 5))\nplt.show()\n\n\n"
] | [
2
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074658027_matplotlib_pandas_python.txt |
Q:
Django: python manage.py migrate does nothing at all
I just started learning django, and as i try to apply my migrations the first problem occurs. I start the server up, type
python manage.py migrate
and nothing happens. No error, no crash, just no response.
Performing system checks...
System check identified n... | Django: python manage.py migrate does nothing at all | I just started learning django, and as i try to apply my migrations the first problem occurs. I start the server up, type
python manage.py migrate
and nothing happens. No error, no crash, just no response.
Performing system checks...
System check identified no issues (0 silenced).
You have 13 unapplied migration(s)... | [
"Well, you say that you first start the server and then type in the commands. That's also what the terminal feed you shared shows. \nDo not run the server if you want to run management commands using manage.py.\nHit Ctrl+C to exit the server and then run your migration commands, it will work.\n",
"Try: \npython m... | [
12,
10,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"django",
"python",
"python_3.5",
"python_3.x"
] | stackoverflow_0043718536_django_python_python_3.5_python_3.x.txt |
Q:
pyqt5_tools designer.exe does not exist
I have installed PyQT5 by command pip install pyqt5 pyqt5-tools. Then I want to show path for designer.exe. However I could not found that in C:\Users\User\AppData\Local\Programs\Python\Python38\Lib\site-packages\pyqt5_tools directory. These are content of that folder.
A:
... | pyqt5_tools designer.exe does not exist | I have installed PyQT5 by command pip install pyqt5 pyqt5-tools. Then I want to show path for designer.exe. However I could not found that in C:\Users\User\AppData\Local\Programs\Python\Python38\Lib\site-packages\pyqt5_tools directory. These are content of that folder.
| [
"using the pip install pyqt5-tools method I found the designer on this path:\nC:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python39\\Lib\\site-packages\\qt5_applications\\Qt\\bin\n",
"On my system QT Designer is saved under C:\\Users\\User\\AppData\\Local\\Qt Designer\nEDIT:\nIt seems like I installed QT De... | [
10,
4,
2,
2,
1,
0,
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0065007143_pip_python.txt |
Q:
How can I iterate over a dataframe containing multiple conditions (using iterrows()) and flag columns based on these conditions using np.where?
I am trying to generate flags based on multiple conditions.
I would like to do the following in a more iterable way:
# sample dataframe
data = [[1, 1980.0, 2000.0]]
df = ... | How can I iterate over a dataframe containing multiple conditions (using iterrows()) and flag columns based on these conditions using np.where? | I am trying to generate flags based on multiple conditions.
I would like to do the following in a more iterable way:
# sample dataframe
data = [[1, 1980.0, 2000.0]]
df = pd.DataFrame(data, columns=["Item", "year1", "start_year"])
df
Item year1 year2
1 1980.0 2000.0
# assign flag based on condition
df = df.as... | [
"In my opinion, a number is expected, and the resulting value is a string. I tried removing the quotes in the conditions themselves. No errors occur. I also added one more line to the dataframe for verification. The flags are displayed as they should. The last line gives: False.\nimport pandas as pd\nimport numpy a... | [
0
] | [] | [] | [
"conditional_statements",
"dataframe",
"loops",
"pandas",
"python"
] | stackoverflow_0074636740_conditional_statements_dataframe_loops_pandas_python.txt |
Q:
Write the attributes of an object into a txt file
So i am trying to write to a text file with all the attributes of an object called item.
I was able to access the information with:
>>>print(*vars(item).values()])
125001 John Smith 12 First Road London N1 55 74
but when i try write it into the text file:
with ope... | Write the attributes of an object into a txt file | So i am trying to write to a text file with all the attributes of an object called item.
I was able to access the information with:
>>>print(*vars(item).values()])
125001 John Smith 12 First Road London N1 55 74
but when i try write it into the text file:
with open('new_student_data.txt', 'w') as f:
f.writelines(*... | [
"with open('new_student_data.txt', 'w') as f:\n for i in vars(item).values():\n f.write(f\"{i}\\n\")\n\nIf file.writelines only takes an iterable and doesn't support *args, you can always iterate over your list and write it with file.write.\n",
"You can just print as follows:\nwith open('new_student_dat... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0071604746_python.txt |
Q:
Finding max values in a text file read in using Python
I have a text file containing only numbers. There are gaps in the sets of numbers and the problem asks that the file is read through, adds the numbers within each group then finds the top three values in the list and adds them together.
I've found the way to r... | Finding max values in a text file read in using Python | I have a text file containing only numbers. There are gaps in the sets of numbers and the problem asks that the file is read through, adds the numbers within each group then finds the top three values in the list and adds them together.
I've found the way to read through the file and calculate the sum of the largest se... | [
"Create a list to store the group totals.\nRead the file a line at a time. Try to convert each line to int. If that fails then you're at a group separator so append zero to the group_totals list\nSort the list and print the last 3 items\nFILENAME = '/Users/dan/Desktop/day1 copy.txt'\n\ngroup_totals = [0]\n\nwith op... | [
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0074657939_file_python.txt |
Q:
Create Column Based On Aggregation of Other Columns - Pyspark
I want to create a column whose values are equal to another column's when certain conditions are met. I want the column first to have the value of the column share when the columns gender, week and type are the same.
I have the following dataframe:
+---... | Create Column Based On Aggregation of Other Columns - Pyspark | I want to create a column whose values are equal to another column's when certain conditions are met. I want the column first to have the value of the column share when the columns gender, week and type are the same.
I have the following dataframe:
+------+----+----+-------------+-------------------+
|gender|week|type|... | [
"I found the answer out so I will be posting it here.\nI used a window function:\nm_window = Window.partitionBy([\"gender\",\"week\",\"type\"]).orderBy(\"share\")\nThen I create a column using the function first and over window like this:\ndf.withColumn(\"first\", first(\"units\").over(m_window))\n"
] | [
1
] | [] | [] | [
"conditional_statements",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074655040_conditional_statements_dataframe_pyspark_python.txt |
Q:
Django, looping through openweather icons always displays the last icon instead of appended city icon
I am trying to build out a weather app using openweather api and what I want to do is replace the icon png's with my own customized icon set.
In order to do this, I have referenced the openweather api png codes as... | Django, looping through openweather icons always displays the last icon instead of appended city icon | I am trying to build out a weather app using openweather api and what I want to do is replace the icon png's with my own customized icon set.
In order to do this, I have referenced the openweather api png codes as seen here: https://openweathermap.org/weather-conditions. I have written some code that states if this cod... | [
" icon = weather['icon']\n\nThis sets a variable icon to reference the string inside the dictionary.\n icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/01d.svg'\n\nThis reassigns that variable to a URL string. It does NOT change the dictionary like you might think.\n cont... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074658135_django_python.txt |
Q:
What causes this arithmetic discrepancy between numpy and MATLAB and how can I force either behavior in Python?
I tried to normalize a probability distribution of the form $p_k := 2^{-k^2}$ for $k \in {1,\dots,n}$ for $n = 8$ in numpy/Python 3.8 along the following lines, using an equivalent of MATLAB's num2hex a ... | What causes this arithmetic discrepancy between numpy and MATLAB and how can I force either behavior in Python? | I tried to normalize a probability distribution of the form $p_k := 2^{-k^2}$ for $k \in {1,\dots,n}$ for $n = 8$ in numpy/Python 3.8 along the following lines, using an equivalent of MATLAB's num2hex a la C++ / Python Equivalent of Matlab's num2hex. The sums of the normalized distributions differ in Python and MATLAB ... | [
"According to the manual, numpy.sum uses pairwise summation to get more precision. Another common algorithm is Kahan summation.\nAnyway, I wouldn't count too much on Numpy and MATLAB giving the same result up to the last bit, as there might me operation reordering if computations are made in parallel. See this for ... | [
3
] | [] | [] | [
"ieee_754",
"matlab",
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074658068_ieee_754_matlab_numpy_python_python_3.x.txt |
Q:
I made a list which i wanted it to receive data in order
the server list only takes one input and use the for loop to duplicate that
Server starting [Listining] Server is listning to 192.168.129.254 NEW Connection - ('192.168.129.254', 64225) connected[ACTIVE CONNECTIONS] 1
['hello', 'hello', 'hello', 'hello', 'h... | I made a list which i wanted it to receive data in order | the server list only takes one input and use the for loop to duplicate that
Server starting [Listining] Server is listning to 192.168.129.254 NEW Connection - ('192.168.129.254', 64225) connected[ACTIVE CONNECTIONS] 1
['hello', 'hello', 'hello', 'hello', 'hello']
This 5 'hello' in the list came from one sent data fro... | [
"\nI want the list to save 5 different inputs sent from client\n\nThen you have to rearrange your code a bit:\n list1 = []\n while connected:\n msg_length = conn.recv(HEADER).decode(FORMAT)\n if msg_length:\n msg_length = int(msg_length)\n msg = conn.recv(msg_length).decode... | [
0
] | [] | [] | [
"list",
"python",
"server",
"sockets"
] | stackoverflow_0074656985_list_python_server_sockets.txt |
Q:
Python: converting timestamp to date time not working
I am requesting data from the api.etherscan.io website. For this, I require a free API key. I am getting information for the following wallet addresses 0xdafea492d9c6733ae3d56b7ed1adb60692c98bc5, 0xc508dbe4866528db024fb126e0eb97595668c288. Below is the code I a... | Python: converting timestamp to date time not working | I am requesting data from the api.etherscan.io website. For this, I require a free API key. I am getting information for the following wallet addresses 0xdafea492d9c6733ae3d56b7ed1adb60692c98bc5, 0xc508dbe4866528db024fb126e0eb97595668c288. Below is the code I am using:
wallet_addresses = ['0xdafea492d9c6733ae3d56b7ed1a... | [
"Here you go, it's working without an error:\npage_number = 0\ndf_main = pd.DataFrame()\nwhile True:\n for address in wallet_addresses:\n url=f'https://api.etherscan.io/api?module=account&action=txlist&address={address}&startblock=0&endblock=99999999&page={page_number}&offset=10&sort=asc&apikey={ether_api... | [
1
] | [] | [] | [
"dataframe",
"datetime",
"etherscan",
"pandas",
"python"
] | stackoverflow_0074657344_dataframe_datetime_etherscan_pandas_python.txt |
Q:
beginner troubles
making guessing game. I keep getting an attribute error trying to append my guess to the guesses list. following along in a course. I was prompted to say getting warmer if the current guess was closer than the last guess. i set guesses = 0 and and within the while loop i tried to append with (gue... | beginner troubles | making guessing game. I keep getting an attribute error trying to append my guess to the guesses list. following along in a course. I was prompted to say getting warmer if the current guess was closer than the last guess. i set guesses = 0 and and within the while loop i tried to append with (guesses.append(cg)) cg = c... | [
"You assign an integer to guesses here:\nguesses = 0\n\nSo the interpreter is right saying you CANNOT append to int. Define it as a list:\nguesses = []\n\nBut there's more:\n\nYou ask for input BEFORE the loop, so it happens only once, later the loop is infinite, cause no new input is ever provided\nIf you need onl... | [
0,
0
] | [] | [] | [
"error_handling",
"list",
"python"
] | stackoverflow_0074648333_error_handling_list_python.txt |
Q:
Pandas - Dataframe dates subtraction
I am dealing with a dataframe like this:
mydata['TS_START']
0 2022-11-09 00:00:00
1 2022-11-09 00:00:30
2 2022-11-09 00:01:00
3 2022-11-09 00:01:30
4 2022-11-09 00:02:00
...
I would like to create a new column where:
mydata['delta_t']
0 ... | Pandas - Dataframe dates subtraction | I am dealing with a dataframe like this:
mydata['TS_START']
0 2022-11-09 00:00:00
1 2022-11-09 00:00:30
2 2022-11-09 00:01:00
3 2022-11-09 00:01:30
4 2022-11-09 00:02:00
...
I would like to create a new column where:
mydata['delta_t']
0 2022-11-09 00:00:30 - 2022-11-09 00:00:... | [
"here is one way :\ndf['date'] = pd.to_datetime(df['date'])\n\ndf['delta_t'] = (df['date'] - df['date'].shift(1)).dt.total_seconds()\nprint(df)\n\noutput :\n>>\n date delta_t\n0 2022-11-09 00:00:00 NaN\n1 2022-11-09 00:00:30 30.0\n2 2022-11-09 00:01:00 30.0\n3 2022-11-09 00:01:30 3... | [
0
] | [] | [] | [
"dataframe",
"date",
"pandas",
"python"
] | stackoverflow_0074658022_dataframe_date_pandas_python.txt |
Q:
Convert string to List so square bracket will be eliminated and will be a list
'[1, 2]'
It is a string. How to I make it List [1,2]
So convertion from '[1, 2]' to [1,2]
A:
You have a couple of options
eval
eval('[1, 2]')
# [1, 2]
ast.literal_eval
import ast
ast.literal_eval('[1, 2]')
# [1, 2]
string parsing
... | Convert string to List so square bracket will be eliminated and will be a list | '[1, 2]'
It is a string. How to I make it List [1,2]
So convertion from '[1, 2]' to [1,2]
| [
"You have a couple of options\neval\neval('[1, 2]')\n# [1, 2]\n\nast.literal_eval\nimport ast\nast.literal_eval('[1, 2]')\n# [1, 2]\n\nstring parsing\nlist(map(int, '[1, 2]'.strip('[]').split(', ')))\n# [1, 2]\n\n"
] | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074658231_list_python.txt |
Q:
Save JPEG comment using Pillow
I need to save an Image in Python (created as a Numpy array) as a JPEG file, while including a "comment" in the file with some specific metadata. This metadata will be used by another (third-party) application and is a simple ASCII string. I have a sample image including such a "comm... | Save JPEG comment using Pillow | I need to save an Image in Python (created as a Numpy array) as a JPEG file, while including a "comment" in the file with some specific metadata. This metadata will be used by another (third-party) application and is a simple ASCII string. I have a sample image including such a "comment", which I can read out using Pil... | [
"To save the \"comment\" metadata in the JPEG file, you can use the Image.save() method with the save_all=True and exif=img.app arguments. This will preserve the metadata in the JPEG file.\nHere is an example:\nfrom PIL import Image\n\n# open the image\nimg = Image.open(path)\n\n# save the image with the comment me... | [
1,
1
] | [] | [] | [
"jpeg",
"python",
"python_imaging_library"
] | stackoverflow_0074653239_jpeg_python_python_imaging_library.txt |
Q:
Couldn't find ffmpeg or avconv - Python
I'm working on a captcha solver and I need to use ffmpeg, though nothing works. Windows 10 user.
Warning when running the code for the first time:
C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pydub\utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv ... | Couldn't find ffmpeg or avconv - Python | I'm working on a captcha solver and I need to use ffmpeg, though nothing works. Windows 10 user.
Warning when running the code for the first time:
C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pydub\utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
wa... | [
"As you can see by the error message, the issue is with ffprobe and not ffmpeg.\nMake sure that both ffprobe.exe and ffmpeg.exe are in the executable path.\n\nOne option is placing ffprobe.exe and ffmpeg.exe in the same folder as the Python script (D:\\Scripts\\captcha\\ in your case).\nOther option is adding the f... | [
0,
0
] | [] | [] | [
"ffmpeg",
"ffprobe",
"pydub",
"python",
"selenium"
] | stackoverflow_0074651215_ffmpeg_ffprobe_pydub_python_selenium.txt |
Q:
How to store a language in a database
I'm working with a couple volunteers on creating the first online dictionary for our language Tarifit (An Amazigh language spoken in Northern Morocco)
I'm still a CS student learning about Python and C# currently but I also know HTML/CSS/JS and my question was what is the best... | How to store a language in a database | I'm working with a couple volunteers on creating the first online dictionary for our language Tarifit (An Amazigh language spoken in Northern Morocco)
I'm still a CS student learning about Python and C# currently but I also know HTML/CSS/JS and my question was what is the best way to store all the words in a database a... | [] | [] | [
"1-) Classical solution: Rent a server, Deploy MySQL to server, Use bootstrap templates for web application design in which users add words, use PHP to connect MySQL database server (for adding and displaying words\n2-) Modern solution: Open 3 month free usage Google cloud account, create Firebase database, create ... | [
-1,
-1
] | [
"database",
"dictionary",
"javascript",
"python",
"web"
] | stackoverflow_0074658078_database_dictionary_javascript_python_web.txt |
Q:
How to fix the error name 'phi' is not defined?
I'm trying to solve the following laplace transform: f(t) = sen(ωt + φ)
I wrote the following code to solve the problem
import sympy as sym
from sympy.abc import s,t,x,y,z
from sympy.integrals import laplace_transform
from sympy.integrals import inverse_laplace_tran... | How to fix the error name 'phi' is not defined? | I'm trying to solve the following laplace transform: f(t) = sen(ωt + φ)
I wrote the following code to solve the problem
import sympy as sym
from sympy.abc import s,t,x,y,z
from sympy.integrals import laplace_transform
from sympy.integrals import inverse_laplace_transform
omega = sympy.Symbol('omega', real=True)
sin = ... | [
"add a import for phi\nfrom sympy.abc import phi\n\n"
] | [
2
] | [] | [] | [
"jupyter_notebook",
"math",
"python",
"python_3.x",
"symbolic_math"
] | stackoverflow_0074658323_jupyter_notebook_math_python_python_3.x_symbolic_math.txt |
Q:
How to get rid of the in place FutureWarning when setting an entire column from an array?
In pandas v.1.5.0 a new warning has been added, which is shown, when a column is set from an array of different dtype. The FutureWarning informs about a planned semantic change, when using iloc: the change will be done in-pla... | How to get rid of the in place FutureWarning when setting an entire column from an array? | In pandas v.1.5.0 a new warning has been added, which is shown, when a column is set from an array of different dtype. The FutureWarning informs about a planned semantic change, when using iloc: the change will be done in-place in future versions. The changelog instructs what to do to get the old behavior, but there is... | [
"I haven't found any better way than suppressing the warning using the warnings module:\nimport numpy as np\nimport pandas as pd\nimport warnings\n\ndf = pd.DataFrame({\"price\": [11.1, 12.2]}, index=[\"book1\", \"book2\"])\noriginal_prices = df[\"price\"]\nnew_prices = np.array([98, 99])\nwith warnings.catch_warni... | [
4,
0,
0
] | [
"I am just filtering all future warnings for now:\nimport warnings\nwarnings.simplefilter(\"ignore\", category=FutureWarning)\n\n"
] | [
-2
] | [
"pandas",
"python"
] | stackoverflow_0074057367_pandas_python.txt |
Q:
Manually place the ticks on x-axis, at the beginning, middle and end - Matplotlib
Is there a way to always place the ticks on x-axis of Matplotlib always at the beginning, middle and end of the axis instead of Matplotlib automatically placing them?For example, I have a plot shown below.
matplotlib plot
Is there a ... | Manually place the ticks on x-axis, at the beginning, middle and end - Matplotlib | Is there a way to always place the ticks on x-axis of Matplotlib always at the beginning, middle and end of the axis instead of Matplotlib automatically placing them?For example, I have a plot shown below.
matplotlib plot
Is there a way to always place 25 at the very beginning, 80 in the middle and 95 at the very end?... | [
"You need to split the set_xticks() to have only the number of entries - (0,1,2) and use set_xticklables() to give the text you want to display - (25,80,95). Note that I have used numpy's linspace to get the list of numbers based on length of percentile_value. Also, I have removed the pad=-15 as you have indicated ... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074657894_matplotlib_python.txt |
Q:
What have i do wrong?
File "F:\2д шутер на питоне\main.py", line 402, in <module>
world_data[x][y] = int(tile)
ValueError: invalid literal for int() with base 10: '-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-... | What have i do wrong? | File "F:\2д шутер на питоне\main.py", line 402, in <module>
world_data[x][y] = int(tile)
ValueError: invalid literal for int() with base 10: '-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t... | [
"It looks like you have tab delimiter, not comma, so replace\nreader = csv.reader(csvfile, delimiter=',')\n\nwith\nreader = csv.reader(csvfile, delimiter='\\t')\n\nI would note that you could replace this whole block with\nimport numpy as np\nworld_data = np.genfromtext(f'level{level}_data.csv', delimiter='\\t')\n\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074658374_python.txt |
Q:
Quarterly forecast Data across multiple departments
I want to forecast some data, here is an example of the csv table:
Time Period HR
Fin
Legal
Leadership
Overall
2021Q2
42
36
66
53
2021Q3
52
43
64
67
2021Q4
65
47
71
73
2022Q1
68
50
75
74
2022Q2
72
57
77
81
2022Q3
79
62
75
78
I want to make predictions for... | Quarterly forecast Data across multiple departments | I want to forecast some data, here is an example of the csv table:
Time Period HR
Fin
Legal
Leadership
Overall
2021Q2
42
36
66
53
2021Q3
52
43
64
67
2021Q4
65
47
71
73
2022Q1
68
50
75
74
2022Q2
72
57
77
81
2022Q3
79
62
75
78
I want to make predictions for every quarter until the end of Q4 2023.
I ... | [
"Looks like your \"y\" argument accepts only list [ele1, ele2], not a tuple(ele1, ele2). I changed the brackets to squares and I ran your code just fine:\n import plotly.express as px\n figure = px.line(df, x=\"Time Period\", \n y=[\"Fin\",\"Legal\",\"Leadership\",\"Overall\"],\n ... | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074658092_matplotlib_pandas_python.txt |
Q:
Snakemake not interpreting wildcard correctly?
I am trying to run a snakemake file but it is producing a weird result
refseq = 'refseq.fasta'
reads = '_R1_001'
reads2 = '_R2_001'
configfile: "config.yaml"
## Add config
def getsamples():
import glob
test = (glob.glob("*.fastq.gz"))
samples = []
fo... | Snakemake not interpreting wildcard correctly? | I am trying to run a snakemake file but it is producing a weird result
refseq = 'refseq.fasta'
reads = '_R1_001'
reads2 = '_R2_001'
configfile: "config.yaml"
## Add config
def getsamples():
import glob
test = (glob.glob("*.fastq.gz"))
samples = []
for i in test:
samples.append(i.rsplit('_', 2... | [
"It's a common problem due to {barcodes}{sample} pattern.\nSnakemake won't know where {barcodes} ends and where {sample} starts without a wildcard_constraint. Right now, snakemake is thinking that your sample wildcard is just a 0.\n"
] | [
1
] | [] | [] | [
"bash",
"bioinformatics",
"python",
"snakemake"
] | stackoverflow_0074658260_bash_bioinformatics_python_snakemake.txt |
Q:
Finding specific text with selenium
Okay, so I need to search in a search engine for (person's name) net worth and from the first 5 links get all the values and find the average one.
So... When I search for example Elon Musk net worth and open for example the first one which happens to be Wikipedia my thought proc... | Finding specific text with selenium | Okay, so I need to search in a search engine for (person's name) net worth and from the first 5 links get all the values and find the average one.
So... When I search for example Elon Musk net worth and open for example the first one which happens to be Wikipedia my thought process was to search example for a string th... | [
"I think you're going to have to use some sort of machine learning based text analysis to figure out if it's the context you're looking for.\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074657852_python_selenium_web_scraping.txt |
Q:
How to increase font size for Edge and Nodes using Diagrams
I'm using Diagrams as code which uses the Diagrams Python module. I'm trying to increase the font size for Edge labels but can't seem to figure out how to do it.
Edge only seems to accept attr instead of graph_attr so I've tried variations with no luck.
E... | How to increase font size for Edge and Nodes using Diagrams | I'm using Diagrams as code which uses the Diagrams Python module. I'm trying to increase the font size for Edge labels but can't seem to figure out how to do it.
Edge only seems to accept attr instead of graph_attr so I've tried variations with no luck.
Examples I've tried are:
Edge(style="dotted", label="patches", att... | [
"I'm not sure what I was doing wrong before but I was able to get the following variations working.\nEdge(color=\"black\", label=\"texthere\", fontsize=\"20\")\n\nfont = \"20\"\nEdge(color=\"black\", label=\"texthere\", fontsize=font)\n\nThere is also a head and tail label. See the following examples:\nEdge(color=\... | [
0
] | [] | [] | [
"diagram",
"python"
] | stackoverflow_0074648806_diagram_python.txt |
Q:
how to add a profile object by using objects.create method
simply my error is this
Exception has occurred: TypeError
User() got an unexpected keyword argument 'User'
here is the data I receive from the post request in view.py
if request.method == "POST":
student_surname = request.POST.get('student_surname')
... | how to add a profile object by using objects.create method | simply my error is this
Exception has occurred: TypeError
User() got an unexpected keyword argument 'User'
here is the data I receive from the post request in view.py
if request.method == "POST":
student_surname = request.POST.get('student_surname')
student_initials = request.POST.get('student_initials')
st... | [
"student_profile = Profile.objects.create( # Profile\n user=user, #user\n surname=student_surname,\n initials=student_initials,\n entrance_number=student_entrance,\n email=student_email,\n father=student_father,\n skills=student_other_skills,\n sports=student... | [
1
] | [] | [] | [
"authentication",
"django",
"django_models",
"python",
"python_3.x"
] | stackoverflow_0074658376_authentication_django_django_models_python_python_3.x.txt |
Q:
How does "Insert documentation comment stub" work in Pycharm for getting method parameters?
I have enabled Insert documentation comment stub within Editor | General |Smart keys :
But then how to get the method parameters type stubs? Adding the docstring triple quotes and then enter does open up the docstring - bu... | How does "Insert documentation comment stub" work in Pycharm for getting method parameters? | I have enabled Insert documentation comment stub within Editor | General |Smart keys :
But then how to get the method parameters type stubs? Adding the docstring triple quotes and then enter does open up the docstring - but with nothing in it:
def get_self_join_clause(self, df, alias1='o', alias2 = 'n'):
"""
... | [
"\nhow to get the method parameters type stubs?\n\nPyCharm does generate the docstring stub with the type placeholders, but the placeholders aren't currently (using PyCharm 2022.1) populated from the __annotations__ with the types. This has been marked with the state \"To be discussed\" in the JetBrains bugtracker,... | [
1
] | [] | [] | [
"docstring",
"pycharm",
"python"
] | stackoverflow_0074657042_docstring_pycharm_python.txt |
Q:
BeautifulSoup giving me many error lines when used
I've installed beautifulsoup (file named bs4) into my pythonproject folder which is the same folder as the python file I am running. The .py file contains the following code, and for input I am using this URL to a simple page with 1 link which the code is supposed... | BeautifulSoup giving me many error lines when used | I've installed beautifulsoup (file named bs4) into my pythonproject folder which is the same folder as the python file I am running. The .py file contains the following code, and for input I am using this URL to a simple page with 1 link which the code is supposed to retrieve.
URL used as url input: http://data.pr4e.or... | [
"Are you using python 3.10? Looks like beautifulsoup library is using removed deprecated aliases to Collections Abstract Base Classes. More info here: https://docs.python.org/3/whatsnew/3.10.html#removed\nA quick fix is to paste these 2 lines just below your imports:\nimport collections\ncollections.Callable = coll... | [
2,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0070677261_beautifulsoup_python.txt |
Q:
Why doesn't Element.attrib include namespace definitions?
I'd like to create a XML namespace mapping (e.g., to use in findall calls as in the Python documentation of ElementTree). Given the definitions seem to exist as attributes of the xbrl root element, I'd have thought I could just examine the attrib attribute ... | Why doesn't Element.attrib include namespace definitions? | I'd like to create a XML namespace mapping (e.g., to use in findall calls as in the Python documentation of ElementTree). Given the definitions seem to exist as attributes of the xbrl root element, I'd have thought I could just examine the attrib attribute of the root element within my ElementTree. However, the followi... | [
"As for the answer to your specific question, why the attrib list doesn't contain the namespace prefix decls, sorry for the unquenching answer: because they're not attributes.\nhttp://www.w3.org/XML/1998/namespace is a special schema that doesn't act like the other schemas in your userspace. In that representation,... | [
1
] | [] | [] | [
"elementtree",
"python",
"xml",
"xml_namespaces"
] | stackoverflow_0074337020_elementtree_python_xml_xml_namespaces.txt |
Q:
Get records for the nearest date if record does not exist for a particular date
I have a pandas dataframe of stock records, my goal is to pass in a particular 'day' e.g 8 and get the filtered data frame for the 8th of each month and year in the dataset.
I have gone through some SO questions and managed to get one ... | Get records for the nearest date if record does not exist for a particular date | I have a pandas dataframe of stock records, my goal is to pass in a particular 'day' e.g 8 and get the filtered data frame for the 8th of each month and year in the dataset.
I have gone through some SO questions and managed to get one part of my requirement that was getting the records for a particular day, however if ... | [
"Alternative 1\nResample to a daily resolution, selecting the nearest day to fill in missing values:\ndf2 = df.resample('D').nearest()\ndf2 = df2.loc[df2.index.day == 8]\n\nAlternative 2\nA more general method (and a tiny bit faster) is to generate dates/times of your choice, then use reindex() and method 'nearest'... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074657984_dataframe_pandas_python.txt |
Q:
ImportError: No module named wget
Please help me to find reason on MacOS why when I including library
import wget
I'm getting error
File "/Users/xx/python/import.py", line 4, in <module>
import wget
ImportError: No module named wget
This library is installed
xx$ pip3 install wget
Requirement already satisfied... | ImportError: No module named wget | Please help me to find reason on MacOS why when I including library
import wget
I'm getting error
File "/Users/xx/python/import.py", line 4, in <module>
import wget
ImportError: No module named wget
This library is installed
xx$ pip3 install wget
Requirement already satisfied: wget in /usr/local/lib/python3.6/site... | [
"Try pip install wget, maybe you’re using python 2\n",
"With pip3 you are installing module for python 3,\nIt can b that you have both versions of python 2 and 3 and you your environment is pointing default to python 2 \nCheck python version or install wget for python 2\npython -V \npip install wget\n\n",
"t... | [
14,
4,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"macos",
"python",
"wget"
] | stackoverflow_0051069716_macos_python_wget.txt |
Q:
django.db.utils.IntegrityError: (1062, "Duplicate entry '8d4d1c76950748619f93ee2bfffc7de5' for key 'request_id'")
I don't understand what kind of error is ? sometimes this code works and after 1-2 times submitting form then trying to submit form again with different details then i got this error,
django.db.utils.... | django.db.utils.IntegrityError: (1062, "Duplicate entry '8d4d1c76950748619f93ee2bfffc7de5' for key 'request_id'") | I don't understand what kind of error is ? sometimes this code works and after 1-2 times submitting form then trying to submit form again with different details then i got this error,
django.db.utils.IntegrityError: (1062, "Duplicate entry '8d4d1c76950748619f93ee2bfffc7de5' for key 'request_id'")
Here this is my views... | [
"Based on your comment.\nrequest_id = models.UUIDField(primary_key=False, default=uuid.uuid4().hex, editable=False, unique=True)\n\nYou assigned an instance of the UUID for the default value. In fact, you didn't set a function to generate a new UUID for each record. If you check the related migration file, you can ... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_views",
"mysql",
"python"
] | stackoverflow_0074652528_django_django_rest_framework_django_views_mysql_python.txt |
Q:
Django3 Paginator with function based view
class ProductList(ListView):
model = Product
paginate_by = 8
def company_page(request, slug):
...
product_list = Product.objects.filter(company=company).order_by('-pk')
paginator = Paginator(product_list, 4)
page_number = request.GET.get('page')
page_obj =... | Django3 Paginator with function based view | class ProductList(ListView):
model = Product
paginate_by = 8
def company_page(request, slug):
...
product_list = Product.objects.filter(company=company).order_by('-pk')
paginator = Paginator(product_list, 4)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return rende... | [
"Try this:\nviews.py\n# other views ...\n\ndef company_page(request, slug):\n product_list = Product.objects.filter(company=company).order_by('-pk')\n\n page = request.GET.get('page', 1)\n paginator = Paginator(product_list, 4)\n\n try:\n Products = paginator.page(page)\n except PageNotAnInteger:\n P... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074646099_django_python.txt |
Q:
Button is not clickable by Selenuim (Python)
I have a script that uses Selenium (Python).
I tried to make the code click a button that it acknowledges is clickable, but throws an error stating it;s not clickable.
Same thing happens again in a dropdown menu, but this time I'm not clicking, but selecting an option b... | Button is not clickable by Selenuim (Python) | I have a script that uses Selenium (Python).
I tried to make the code click a button that it acknowledges is clickable, but throws an error stating it;s not clickable.
Same thing happens again in a dropdown menu, but this time I'm not clicking, but selecting an option by value.
from selenium import webdriver
from webdr... | [
"When a web element is present in the HTML-DOM but it is not in the state that can be interacted. Other words, when the element is found but we can’t interact with it, it throws ElementNotInteractableException.\nThe element not interactable exception may occur due to various reasons.\n\nElement is not visible\nElem... | [
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074657899_python_selenium_web_scraping.txt |
Q:
best way to speed up multiprocessing code in python?
I am trying to mess around with matrices in python, and wanted to use multiprocessing to processes each row separately for a math operation, I have posted a minimal reproducible sample below, but keep in mind that for my actual code I do in-fact need the entire ... | best way to speed up multiprocessing code in python? | I am trying to mess around with matrices in python, and wanted to use multiprocessing to processes each row separately for a math operation, I have posted a minimal reproducible sample below, but keep in mind that for my actual code I do in-fact need the entire matrix passed to the helper function. This sample takes li... | [
"Your matrix has 1000 rows of 1000 elements each and you are summing each row 100 times. By my calculation, that is 100,000 tasks you are submitting to the pool passing a one-million element matrix each time. Ouch!\nNow I know you say that the worker function addMatrixRow must have access to the complete matrix. Fi... | [
3,
1
] | [] | [] | [
"matrix",
"multiprocessing",
"process_pool",
"python"
] | stackoverflow_0074646298_matrix_multiprocessing_process_pool_python.txt |
Q:
How to Finding USB port Address with dev/tty/usb.. format in raspberry pi 4 ver.b?
I had a problem for searching USB Address Port in Raspberry Pi. I'm using RIGOL DSE1102E Digital Oscilloscope, to acquiring data to my Raspberry Pi 4 Ver. b.
So, i'm connecting from Raspberry Pi 4 to my Oscilloscope USB Slave's port... | How to Finding USB port Address with dev/tty/usb.. format in raspberry pi 4 ver.b? | I had a problem for searching USB Address Port in Raspberry Pi. I'm using RIGOL DSE1102E Digital Oscilloscope, to acquiring data to my Raspberry Pi 4 Ver. b.
So, i'm connecting from Raspberry Pi 4 to my Oscilloscope USB Slave's port and i'm checking in my Raspberry terminal. So i'm typing
pi@raspberrypi:~$ lsusb
so, ... | [
"Instead of using /dev/ttyUSB0 I recommend using the symlinks provided by the kernel in /dev/serial/by-id. They contain a lot of info about the USB device, including the vendor ID and product ID, so you can be sure you are opening the right device. They also should be pretty stable, not depending on the USB port ... | [
0
] | [] | [] | [
"python",
"raspberry_pi4",
"usb"
] | stackoverflow_0074623554_python_raspberry_pi4_usb.txt |
Q:
How do I interchange two sets of elements in a string in python?
So, how can I interchange two sets of adjacent elements In a string.
Like lets take a string "abcd" I want to make it "cdab",another example would be "5089" I want to change this to "8950", The string is a large one and I want to apply the method thr... | How do I interchange two sets of elements in a string in python? | So, how can I interchange two sets of adjacent elements In a string.
Like lets take a string "abcd" I want to make it "cdab",another example would be "5089" I want to change this to "8950", The string is a large one and I want to apply the method throughout the string. Can you guys please suggest a way to do the same i... | [
"Use the slice notation\ndef swap(value):\n middle = len(value) // 2\n return value[middle:] + value[:middle]\n\nprint(swap(\"abcd\")) # cdab\nprint(swap(\"abcde\")) # cdeab\nprint(swap(\"1234567890\")) # 6789012345\n\n",
"s = \"abcdefghijklmn\"\n\nans = []\nn = 2\nflip = True\nfor i in range(0, len(s), ... | [
0,
0
] | [] | [] | [
"algorithm",
"python",
"string"
] | stackoverflow_0074658493_algorithm_python_string.txt |
Q:
FileNotFoundError: [Errno 2] No such file or directory: './iris.csv'
I'm getting this error for my Python code using the IDLE Shell and I'm not sure how to resolve it. I've tried downloading and adding the iris.csv file into the same place as the following .py file but it just gives me another set of errors like s... | FileNotFoundError: [Errno 2] No such file or directory: './iris.csv' | I'm getting this error for my Python code using the IDLE Shell and I'm not sure how to resolve it. I've tried downloading and adding the iris.csv file into the same place as the following .py file but it just gives me another set of errors like shown. If someone could help me it would be greatly appreciated!
----------... | [
"Looks like you are looking in the file path that ends with \\Lab 5 .py, which will just contain your python script. So you need to look one layer \"above\" your python script, which is the directory containing the script and the iris.csv-file.\nTry: iris_df = pd.read_csv('../iris.csv')\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074658611_python.txt |
Q:
Validation python, Using GUI
I am attempting to validate the text box field so that the user can only insert integers, although i have used a while loop to attempt and cannot figure it out I keep getting errors. Please help.
from tkinter import *
import tkinter as tk
from tkinter.tix import *
# setup the UI
root... | Validation python, Using GUI | I am attempting to validate the text box field so that the user can only insert integers, although i have used a while loop to attempt and cannot figure it out I keep getting errors. Please help.
from tkinter import *
import tkinter as tk
from tkinter.tix import *
# setup the UI
root = Tk()
# Give the UI a title
ro... | [
"define validation type and validatecommand. validate = key makes with every key input it runs validatecommand. It only types if that function returns true which is 'validate' function in this case.\nvcmd = (root.register(validate), '%P')\ntk.Entry(textvariable = e1,validate=\"key\", validatecommand=vcmd).grid(row=... | [
0
] | [] | [] | [
"interface",
"python",
"tkinter"
] | stackoverflow_0074650750_interface_python_tkinter.txt |
Q:
How make np.roll working faster for one dimension array?
I generate a two zero arrays by np.zero then i use np.roll to make circshifting array. But when i calling np.roll in cycle it works very slow. Is there any way to speed up my code?
Here is the code:
preamble_length = 256
threshold_level = 100... | How make np.roll working faster for one dimension array? | I generate a two zero arrays by np.zero then i use np.roll to make circshifting array. But when i calling np.roll in cycle it works very slow. Is there any way to speed up my code?
Here is the code:
preamble_length = 256
threshold_level = 100
sample_rate = 750e3
decimation_factor = 6
... | [
"So your roll are doing:\nIn [118]: x=np.arange(10)\nIn [119]: np.roll(x,-1)\nOut[119]: array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])\n\nYou can look at the np.roll code; it's probably more general, it has to, in one way or other, copy all the values of x to a new array. This might be a bit faster, since it doesn't try to... | [
0
] | [] | [] | [
"numpy",
"python",
"signal_processing"
] | stackoverflow_0074655749_numpy_python_signal_processing.txt |
Q:
Unable to install coursera-dl
I accidentally deleted a file I think called coursera-dl.exe from C:\python310\lib\site-packages. I tried to uninstall it using:
pip uninstall coursera-dl
it showed this warning:
WARNING: Ignoring invalid distribution -oursera-dl (c:\python310\lib\site-packages)
WARNING: Ignoring inv... | Unable to install coursera-dl | I accidentally deleted a file I think called coursera-dl.exe from C:\python310\lib\site-packages. I tried to uninstall it using:
pip uninstall coursera-dl
it showed this warning:
WARNING: Ignoring invalid distribution -oursera-dl (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -oursera-dl (c:\p... | [
"Try:\npip install --upgrade --force-reinstall coursera-dl\n\nor\npip install --ignore-installed coursera-dl\n\n"
] | [
0
] | [] | [] | [
"cmd",
"coursera_api",
"python"
] | stackoverflow_0074631073_cmd_coursera_api_python.txt |
Q:
python re unterminated character set at position 0
CODE:
import re
inp=input()
tup=tuple(map(str,inp.split(',')))
i=0
while i<len(tup):
x=tup[i]
a=re.search("[0-9a-zA-Z\$#@",x)
if a!="None":
break
else:
i=i+1
if a!="None" and len(tup[i])>=6 and len(tup[i])<=12:
print(tup[i])
els... | python re unterminated character set at position 0 | CODE:
import re
inp=input()
tup=tuple(map(str,inp.split(',')))
i=0
while i<len(tup):
x=tup[i]
a=re.search("[0-9a-zA-Z\$#@",x)
if a!="None":
break
else:
i=i+1
if a!="None" and len(tup[i])>=6 and len(tup[i])<=12:
print(tup[i])
else:
print("invalid")
INPUT:
ABd1234@1,a F1#,2w3E*,2W... | [
"The error stems from the invalid regular expression - specifically, you've omitted the right-bracket.\nHowever, even if you fix that, based on the code shown in the question, this isn't going to work for a couple of reasons.\n\nThe return value from re.search will always be unequal to 'None'\nThe final if test in ... | [
0,
0
] | [] | [] | [
"python",
"python_re",
"regex",
"search",
"tuples"
] | stackoverflow_0074658401_python_python_re_regex_search_tuples.txt |
Q:
How to easier to split csv data by substring using python
Finally I want to split clearly like this photo
*NOT replace, I want to SPLIT and not just using "," to split
MUST according to substring to split it
I have a csv like:
date, time, ID1, ID2, ID3, "Action=xxx, ProdCode=XXXX, Cmd=xxx, Price=xxxxx, Qty=xxx, Tr... | How to easier to split csv data by substring using python | Finally I want to split clearly like this photo
*NOT replace, I want to SPLIT and not just using "," to split
MUST according to substring to split it
I have a csv like:
date, time, ID1, ID2, ID3, "Action=xxx, ProdCode=XXXX, Cmd=xxx, Price=xxxxx, Qty=xxx, TradedQty=xxx, Validity=xxx, Status=xxx, AddBy=xxxxxx, TimeStamp=... | [
"Not sure I understand 100%, but let me try to help.\nThe focus points are:\n# import the pandas library and alias as pd\nimport pandas as pd\n\n# read a csv with the example data\ndf = pd.read_csv(\"data.csv\", sep=\",\", quoting=False, header = None)\n\n# replace any values that match the pattern \"something=valu... | [
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074658256_csv_pandas_python.txt |
Q:
How to deal with the categorical variable of more than 33 000 cities?
I work in Python. I have a problem with the categorical variable - "city".
I'm building a predictive model on a large dataset-over 1 million rows.
I have over 100 features. One of them is "city", consisting of 33 000 different cities.
I use e.... | How to deal with the categorical variable of more than 33 000 cities? | I work in Python. I have a problem with the categorical variable - "city".
I'm building a predictive model on a large dataset-over 1 million rows.
I have over 100 features. One of them is "city", consisting of 33 000 different cities.
I use e.g. XGBoost where I need to convert categorical variables into numeric. Dumm... | [
"XGBoost has also since version 1.3.0 added experimental support for categorical encoding.\nCopying my answer from another question.\nNov 23, 2020\nXGBoost has since version 1.3.0 added experimental support for categorical features. From the docs:\n\n1.8.7 Categorical Data\nOther than users performing encoding, XGB... | [
2,
1,
1,
0
] | [] | [] | [
"forecasting",
"python",
"xgboost"
] | stackoverflow_0061975690_forecasting_python_xgboost.txt |
Q:
spacy Can't find model 'en_core_web_sm' on windows 10 and Python 3.5.3 :: Anaconda custom (64-bit)
what is difference between spacy.load('en_core_web_sm') and spacy.load('en')? This link explains different model sizes. But i am still not clear how spacy.load('en_core_web_sm') and spacy.load('en') differ
spacy.load... | spacy Can't find model 'en_core_web_sm' on windows 10 and Python 3.5.3 :: Anaconda custom (64-bit) | what is difference between spacy.load('en_core_web_sm') and spacy.load('en')? This link explains different model sizes. But i am still not clear how spacy.load('en_core_web_sm') and spacy.load('en') differ
spacy.load('en') runs fine for me. But the spacy.load('en_core_web_sm') throws error
i have installed spacyas belo... | [
"Initially I downloaded two en packages using following statements in anaconda prompt.\npython -m spacy download en_core_web_lg\npython -m spacy download en_core_web_sm\n\nBut, I kept on getting linkage error and finally running below command helped me to establish link and solved error.\npython -m spacy download e... | [
156,
83,
40,
17,
15,
11,
5,
5,
5,
4,
4,
3,
3,
2,
2,
2,
2,
2,
2,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"nlp",
"python",
"python_3.x",
"spacy"
] | stackoverflow_0054334304_nlp_python_python_3.x_spacy.txt |
Q:
How do I get Python to send as many concurrent HTTP requests as possible?
I'm trying to send HTTPS requests as quickly as possible. I know this would have to be concurrent requests due to my goal being 150 to 500+ requests a second. I've searched everywhere, but get no Python 3.11+ answer or one that doesn't give ... | How do I get Python to send as many concurrent HTTP requests as possible? | I'm trying to send HTTPS requests as quickly as possible. I know this would have to be concurrent requests due to my goal being 150 to 500+ requests a second. I've searched everywhere, but get no Python 3.11+ answer or one that doesn't give me errors. I'm trying to avoid AIOHTTP as the rigmarole of setting it up was a ... | [
"It's quite unfortunate that you couldn't setup AIOHTTP properly because this is one of the most efficient way to do asynchronous requests in Python.\nSetup is not that hard:\nimport asyncio\nimport aiohttp\nfrom time import perf_counter\n\n\ndef urls(n_reqs: int):\n for _ in range(n_reqs):\n yield \"http... | [
1,
0,
0
] | [] | [] | [
"concurrency",
"http",
"https",
"python",
"python_3.x"
] | stackoverflow_0074567219_concurrency_http_https_python_python_3.x.txt |
Q:
What is the best way to pass an extra argument to a scipy.LowLevelCallable function?
I have a python script that creates a set of ctype input arguments to pass to scipy.LowLevelCallable(see the notes section) and uses it to make a call to scipy.generic_filter that only executes a single iteration for testing purpo... | What is the best way to pass an extra argument to a scipy.LowLevelCallable function? | I have a python script that creates a set of ctype input arguments to pass to scipy.LowLevelCallable(see the notes section) and uses it to make a call to scipy.generic_filter that only executes a single iteration for testing purposes. I also define an extra argument and pass it to the user_data void pointer as followin... | [
"@DavidRanieri's comment resolved my problem\n"
] | [
0
] | [] | [] | [
"c",
"ctypes",
"python",
"scipy",
"scipy.ndimage"
] | stackoverflow_0074658716_c_ctypes_python_scipy_scipy.ndimage.txt |
Q:
Binary Search Using a Recursive Function
taking an intro CS class on python and was met by this lab on my textbook. It calls for binary search using recursive functions. I have the rest of the program, I simply need to define the Binary Search function. Any help on this would be greatly appreciated.
Here is the pr... | Binary Search Using a Recursive Function | taking an intro CS class on python and was met by this lab on my textbook. It calls for binary search using recursive functions. I have the rest of the program, I simply need to define the Binary Search function. Any help on this would be greatly appreciated.
Here is the problem:
Binary search can be implemented as a r... | [
"Your error means that lower + upper is an odd number, which when you divide by 2 results in something like 3.5, 8.5, etc., which is an invalid index for a list.\nTo solve this, use floored division (rounding down) with the double slash // operator\nif target == nums[(lower+upper)//2]:\n\n",
"Once you've fixed th... | [
1,
0
] | [] | [] | [
"binary_search",
"python",
"recursion"
] | stackoverflow_0074658593_binary_search_python_recursion.txt |
Q:
Unhandled Exception due to failure importing database file. How to fix?
I have hosted a Flask website on pythonanywhere, but I keep getting the "Unhandled Exception" error when visiting the website. I checked the error logs, and the problem is with a database file, named finance.db. The exact text from the error l... | Unhandled Exception due to failure importing database file. How to fix? | I have hosted a Flask website on pythonanywhere, but I keep getting the "Unhandled Exception" error when visiting the website. I checked the error logs, and the problem is with a database file, named finance.db. The exact text from the error logs are below:
2022-04-26 07:23:21,225: Error running WSGI application
2022-0... | [
"You need to reference the database with the correct path: https://help.pythonanywhere.com/pages/NoSuchFileOrDirectory/\n",
"You should give the absolute path with one extra '/'\ndb = SQL(\"sqlite:////home/routsiddharth/mysite/finance.db\")\n\n"
] | [
2,
0
] | [] | [] | [
"flask",
"python",
"pythonanywhere"
] | stackoverflow_0072011386_flask_python_pythonanywhere.txt |
Q:
How to open a PDF file by clicking on it in TreeView
How do I open a file (ex. PDF) when I click on the row identify by its ID?
I'm trying to make the treeview that uses a GUI to better access and open these PDFs, but I can't figure out how to actually open files using anything but a button. Can someone please tel... | How to open a PDF file by clicking on it in TreeView | How do I open a file (ex. PDF) when I click on the row identify by its ID?
I'm trying to make the treeview that uses a GUI to better access and open these PDFs, but I can't figure out how to actually open files using anything but a button. Can someone please tell me how to use these to find a filepath and open a pdf? T... | [
"thanks for helping me out\nits done!\ndef treeview_click(self, event):\n iid = self.cuadro_blanco_facturas.focus() # id \n name = self.cuadro_blanco_facturas.item(iid)[\"values\"][2] #column name\n espacio = \" \"\n file = os.startfile(f\"facturas\\\\{iid}{espacio}{nombre}.pdf\")\n\n"
] | [
0
] | [] | [] | [
"python",
"tkinter",
"treeview"
] | stackoverflow_0074647514_python_tkinter_treeview.txt |
Q:
What could be the problem in To-do app using Streamlit in Python?
to-dos.py
import streamlit as st
import get_todos
todos = get_todos.getTodos()
def add_todos():
todo1 = st.session_state["new_todo"] + "\n"
todos.append(todo1)
get_todos.writeTodos(todos)
st.title("My TO-DO App")
...
get_todos.py
def... | What could be the problem in To-do app using Streamlit in Python? | to-dos.py
import streamlit as st
import get_todos
todos = get_todos.getTodos()
def add_todos():
todo1 = st.session_state["new_todo"] + "\n"
todos.append(todo1)
get_todos.writeTodos(todos)
st.title("My TO-DO App")
...
get_todos.py
def getTodos():
with open("docs.txt", "r") as file:
data = f... | [
"The main purpose of virtual environments or venv is to manage settings and dependencies of a particular project regardless of other Python projects. virtualenv tool comes bundled with PyCharm, so the user doesn't need to install it. It is always found in the project directory named venv which should be a unique fo... | [
1
] | [] | [] | [
"contextmanager",
"filenotfounderror",
"pycharm",
"python",
"streamlit"
] | stackoverflow_0074652347_contextmanager_filenotfounderror_pycharm_python_streamlit.txt |
Q:
Automating Facebook using Selenium Webdriver
driver = webdriver.Chrome('chromedriver')
driver.get('https://www.facebook.com/')
print("opened facebook")
I am using this code to open Facebook and the page opens.
driver.find_element(By.NAME, "email").send_keys("xxx")
sleep(1)
driver.find_element(By.NAME, "pass").s... | Automating Facebook using Selenium Webdriver | driver = webdriver.Chrome('chromedriver')
driver.get('https://www.facebook.com/')
print("opened facebook")
I am using this code to open Facebook and the page opens.
driver.find_element(By.NAME, "email").send_keys("xxx")
sleep(1)
driver.find_element(By.NAME, "pass").send_keys("xxx")
sleep(1)
driver.find_element(By.N... | [
"The program will exit after executing code. Add below statements to keep program running:\ntime.sleep(300) #300 seconds i.e. 5 minutes\n\n# close the browser window\ndriver.quit()\n\n",
"This will fix your problem\nfrom selenium.webdriver.chrome.options import Options\n\n# Stop Selenium from closing browser auto... | [
1,
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0073245674_python_selenium_selenium_webdriver.txt |
Q:
Camelot - detecting hyperlinks within table
I am using Camelot to extract tables from PDF files. While this works very well, it extracts the text only, it does not extract the hyperlinks that are embedded in the tables.
Is there a way of using Camelot or a similar package to extract table text and hyperlinks embed... | Camelot - detecting hyperlinks within table | I am using Camelot to extract tables from PDF files. While this works very well, it extracts the text only, it does not extract the hyperlinks that are embedded in the tables.
Is there a way of using Camelot or a similar package to extract table text and hyperlinks embedded within tables?
Thanks!
| [
"most applications such as tablular text extractors simply scrape the visible surface as plain text and actually hyperlinks are often stored elsewhere in the pdf which is NOT a WTSIWYG word processor file.\nSo, if you're lucky you can extract the co-ordinates (without their page allocation like this)\nC:\\Users\\lz... | [
0,
0
] | [] | [] | [
"pdf",
"python",
"python_camelot"
] | stackoverflow_0074655135_pdf_python_python_camelot.txt |
Q:
Keras category predictions always same distribution
New to Keras/Machine Learning. I figure I am making a dumb mistake but I don't know what.
I have 3 labels. The training data for each sequence of timesteps is labeled as [1, 0, 0] or [0, 1, 0], or [0, 0, 1].
I always get a distribution that looks something like t... | Keras category predictions always same distribution | New to Keras/Machine Learning. I figure I am making a dumb mistake but I don't know what.
I have 3 labels. The training data for each sequence of timesteps is labeled as [1, 0, 0] or [0, 1, 0], or [0, 0, 1].
I always get a distribution that looks something like this. You can't tell in the photo, but the numbers aren't ... | [
"It sounds like your model is overfitting to your training data. This means that it is performing well on the data it was trained on, but not generalizing well to new data.\nOne common cause of overfitting is using a model that is too complex for the amount of training data you have. In your case, using an LSTM wit... | [
0
] | [] | [] | [
"categorical",
"categories",
"keras",
"lstm",
"python"
] | stackoverflow_0074658705_categorical_categories_keras_lstm_python.txt |
Q:
Airflow Task Succeeded But Not All Data Ingested
I have an airflow task to extract data with this flow
PostgreSQL -> Google Cloud Storage -> BigQuery
The problem that I have is, it seems not all the data is ingested into BigQuery. on the PostgreSQL source, the table has 18M+ rows of data, but after ingested it on... | Airflow Task Succeeded But Not All Data Ingested | I have an airflow task to extract data with this flow
PostgreSQL -> Google Cloud Storage -> BigQuery
The problem that I have is, it seems not all the data is ingested into BigQuery. on the PostgreSQL source, the table has 18M+ rows of data, but after ingested it only has 4M+ rows of data.
When I check on production, t... | [
"PostgresToGCSOperator inherits from BaseSQLToGCSOperator(https://airflow.apache.org/docs/apache-airflow-providers-google/stable/_api/airflow/providers/google/cloud/transfers/sql_to_gcs/index.html)\nAccording to source code, approx_max_file_size_bytes=1900000000. So if you split your table into 10 parts (or workers... | [
0
] | [] | [] | [
"airflow",
"airflow_2.x",
"google_cloud_composer",
"python"
] | stackoverflow_0074650653_airflow_airflow_2.x_google_cloud_composer_python.txt |
Q:
Python module installation failing
My python wont install Time Module it was asking me to update my pip to newest, and I did.
I receive this error:
ERROR: Could not find a version that satisfies the requirement time (from versions: none) ERROR: No matching distribution found for time
My python verstion is the late... | Python module installation failing | My python wont install Time Module it was asking me to update my pip to newest, and I did.
I receive this error:
ERROR: Could not find a version that satisfies the requirement time (from versions: none) ERROR: No matching distribution found for time
My python verstion is the latest. Python 3.11.0
Pip version : 22.3.1
I... | [] | [] | [
"The time module is part of Python's standard library. It's installed along with the rest of Python, and you don't need to (nor can you!) install it with pip.\n\nI can import time in the Python Console\n\nYes, because it's already installed.\n\nbut not in my actual code\n\nI don't believe you. Show us the exact err... | [
-1
] | [
"module",
"pip",
"python",
"time"
] | stackoverflow_0074658997_module_pip_python_time.txt |
Q:
Going from a TensorArray to a Tensor
Given a TensorArray with a fixed size and entries with uniform shapes, I want to go to a Tensor containing the same values, simply by having the index dimension of the TensorArray as a regular axis.
TensorArrays have a method called "gather" which purportedly should do just tha... | Going from a TensorArray to a Tensor | Given a TensorArray with a fixed size and entries with uniform shapes, I want to go to a Tensor containing the same values, simply by having the index dimension of the TensorArray as a regular axis.
TensorArrays have a method called "gather" which purportedly should do just that. And, in fact, the following example wor... | [
"Per https://github.com/tensorflow/tensorflow/issues/30409#issuecomment-508962873 you have to:\n\nReplace arr.write(j, t) with arr = arr.write(j, t)\nThe issue is that tf.function executes as a graph. In eager mode the array will be updated (as a convenience), but you're really meant to use the return value to chai... | [
1,
0
] | [] | [] | [
"python",
"tensorflow",
"tensorflow2.0"
] | stackoverflow_0065889381_python_tensorflow_tensorflow2.0.txt |
Q:
How to write dataframe to csv for max date rows only (filter for max date rows)?
How do I get the df.to_csv to write only rows with the max asOfDate? So that each symbol below will only one row?
import pandas as pd
from yahooquery import Ticker
symbols = ['AAPL','GOOG','MSFT'] #There are 75,000 symbols here.
hea... | How to write dataframe to csv for max date rows only (filter for max date rows)? | How do I get the df.to_csv to write only rows with the max asOfDate? So that each symbol below will only one row?
import pandas as pd
from yahooquery import Ticker
symbols = ['AAPL','GOOG','MSFT'] #There are 75,000 symbols here.
header = ["asOfDate","CashAndCashEquivalents","CashFinancial","CurrentAssets","TangibleBo... | [
"if asOfDate column has a date type or of it is a string with date in the format yyyy-mm-dd you can filter the dateframe for the rows you want to write\ndf[df.asOfDate == df.asOfDate.max()].to_csv('output.csv', mode='a', index=True, header=False, columns=header)\n\n"
] | [
1
] | [] | [] | [
"csv",
"dataframe",
"date",
"pandas",
"python"
] | stackoverflow_0074658643_csv_dataframe_date_pandas_python.txt |
Q:
Python: Plotting time delta
I have a DataFrame with a column of the time and a column in which I have stored a time lag. The data looks like this:
2020-04-18 14:00:00 0 days 03:00:00
2020-04-19 02:00:00 1 days 13:00:00
2020-04-28 14:00:00 ... | Python: Plotting time delta | I have a DataFrame with a column of the time and a column in which I have stored a time lag. The data looks like this:
2020-04-18 14:00:00 0 days 03:00:00
2020-04-19 02:00:00 1 days 13:00:00
2020-04-28 14:00:00 1 days 17:00:00
2020-04-29 20... | [
"In order to plot the time lag on the y-axis, you will need to convert the time lag from a timedelta object to a numerical value that can be used in the plot. One way to do this is to convert the time lag to seconds using the total_seconds method, and then plot the resulting values on the y-axis.\nHere is an exampl... | [
1
] | [] | [] | [
"matplotlib",
"python",
"timedelta"
] | stackoverflow_0074659070_matplotlib_python_timedelta.txt |
Q:
groupby aggregate product in PyTorch
I have the same problem as groupby aggregate mean in pytorch. However, I want to create the product of my tensors inside each group (or labels). Unfortunately, I couldn't find a native PyTorch function that could solve my problem, like a hypothetical scatter_prod_ for products ... | groupby aggregate product in PyTorch | I have the same problem as groupby aggregate mean in pytorch. However, I want to create the product of my tensors inside each group (or labels). Unfortunately, I couldn't find a native PyTorch function that could solve my problem, like a hypothetical scatter_prod_ for products (equivalent to scatter_add_ for sums), whi... | [
"You can use the scatter_ function to calculate the product of the tensors in each group.\nsamples = torch.Tensor([\n [0.1, 0.1], #-> group / class 1\n [0.2, 0.2], #-> group / class 2\n [0.4, 0.4], #-> group / class 2\n [0.0, 0.0] #-> group / class 0\n])\n\nlabels = torch.LongTensor([1,2,2,... | [
0
] | [] | [] | [
"python",
"pytorch",
"tensor"
] | stackoverflow_0074657919_python_pytorch_tensor.txt |
Q:
performing operation on matched columns of NumPy arrays
I am new to python and programming in general and ran into a question:
I have two NumPy arrays of the same shape: they are 2D arrays, of the dimensions 1000 x 2000.
I wish to compare the values of each column in array A with the values in array B. The importa... | performing operation on matched columns of NumPy arrays | I am new to python and programming in general and ran into a question:
I have two NumPy arrays of the same shape: they are 2D arrays, of the dimensions 1000 x 2000.
I wish to compare the values of each column in array A with the values in array B. The important part is that not every column of A should be compared to e... | [
"From the example input and output, I see that you want to do an element wise comparison, and store the values per columns. From your code you understand the 1D variant of this problem, so the question seems to be how to do it in 2D.\nSolution 1\nIn order to achieve this, we have to make the 2D problem, a 1D proble... | [
0
] | [] | [] | [
"numpy",
"numpy_ndarray",
"python",
"python_3.x"
] | stackoverflow_0074657977_numpy_numpy_ndarray_python_python_3.x.txt |
Q:
Grab specific strings within a for loop with variable nested length
I have the following telegram export JSON dataset:
import pandas as pd
df = pd.read_json("data/result.json")
>>>df.colums
Index(['name', 'type', 'id', 'messages'], dtype='object')
>>> type(df)
<class 'pandas.core.frame.DataFrame'>
# Sample out... | Grab specific strings within a for loop with variable nested length | I have the following telegram export JSON dataset:
import pandas as pd
df = pd.read_json("data/result.json")
>>>df.colums
Index(['name', 'type', 'id', 'messages'], dtype='object')
>>> type(df)
<class 'pandas.core.frame.DataFrame'>
# Sample output
sample_df = pd.DataFrame({"messages": [
{"id": 11, "from": "user3... | [
"Assuming a dataframe like the following:\ndf = pd.DataFrame({\"messages\": [\n {\"id\": 21263, \"from\": \"user3984\", \"text\": \"jajajajaja\"},\n {\"id\": 21264, \"from\": \"user837\", \"text\": ['Not sure', {'type': 'hashtag', 'text': '#confused'}]}, \n {\"id\": 21265, \"from\": \"user3984\", \"text\":... | [
1,
0
] | [] | [] | [
"for_loop",
"json",
"list",
"nested",
"python"
] | stackoverflow_0074650152_for_loop_json_list_nested_python.txt |
Q:
Try to find a sublist that doesnt occur in the range of ANY of the sublists in another list
enhancerlist=[[5,8],[10,11]]
TFlist=[[6,7],[24,56]]
I have two lists of lists. I am trying to isolate the sublists in my 'TFlist' that don't fit in the range of ANY of the sublists of enhancerlist (by range: TFlist sublist... | Try to find a sublist that doesnt occur in the range of ANY of the sublists in another list | enhancerlist=[[5,8],[10,11]]
TFlist=[[6,7],[24,56]]
I have two lists of lists. I am trying to isolate the sublists in my 'TFlist' that don't fit in the range of ANY of the sublists of enhancerlist (by range: TFlist sublist range fits inside of enhancerlist sublist range).
SO for example, TFlist[1] will not occur in th... | [
"Alternative is to use a list comprehension:\nTF_notinrange = [tf for tf in TFlist \n if not any(istart <= tf[0] <= tf[1] <= iend \n for istart, iend in enhancerlist)]\nprint(TF_notinrange)\n>>> TF_notinrange\n\nExplanation\nTake ranges of TFlist which are not contained in... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074658926_python.txt |
Q:
How do I check if a line in a CSV file is not the header row, and then append each line of the file to a variable, excluding the header?
I need to use an "if" statement to check if a line in a CSV file is not the header row. Then, I need to append each line of the CSV file to a variable called "mailing_list," excl... | How do I check if a line in a CSV file is not the header row, and then append each line of the file to a variable, excluding the header? | I need to use an "if" statement to check if a line in a CSV file is not the header row. Then, I need to append each line of the CSV file to a variable called "mailing_list," excluding the header. How should I do this? This is the CSV file and what I have so far (may not be correct).
uuid,username,email,subscribe_status... | [
"Using Sniffer class from csv.\nFrom docs:\n\nhas_header(sample)\n\n\nAnalyze the sample text (presumed to be in CSV format) and return True if the first row appears to be a series of column headers. Inspecting each column, one of two key criteria will be considered to estimate if the sample contains a header:\n\n\... | [
1
] | [] | [] | [
"append",
"csv",
"python",
"readlines"
] | stackoverflow_0074659020_append_csv_python_readlines.txt |
Q:
Install packages on EMR via bootstrap actions not working in Jupyter notebook
I have an EMR cluster using EMR-6.3.1.
I am using the Python3 Kernel.
I have a very simple bootstrap script in S3:
#!/bin/bash
sudo python3 -m pip install Cython==0.29.4 boto==2.49.0 boto3==1.18.50 numpy==1.19.5 pandas==1.3.2 pyarrow==5... | Install packages on EMR via bootstrap actions not working in Jupyter notebook | I have an EMR cluster using EMR-6.3.1.
I am using the Python3 Kernel.
I have a very simple bootstrap script in S3:
#!/bin/bash
sudo python3 -m pip install Cython==0.29.4 boto==2.49.0 boto3==1.18.50 numpy==1.19.5 pandas==1.3.2 pyarrow==5.0.0
These are the bootstrap logs
+ sudo python3 -m pip install Cython==0.29.4 bot... | [
"It looks like you are running the pip install command with sudo privileges, which is generally not recommended. The warning message is suggesting that you try running the command with the --user flag instead, which will install the packages locally for the current user instead of system-wide with root privileges.\... | [
0
] | [] | [] | [
"amazon_emr",
"python"
] | stackoverflow_0074659221_amazon_emr_python.txt |
Q:
What is IDLE stands for?
I have using idle to solve python questions
Its a very simple question
idle
enter image description here
A:
IDLE stands for Integrated Development and Learning Environment. It is a built-in development environment for writing and running Python code.
| What is IDLE stands for? | I have using idle to solve python questions
Its a very simple question
idle
enter image description here
| [
"IDLE stands for Integrated Development and Learning Environment. It is a built-in development environment for writing and running Python code.\n"
] | [
0
] | [] | [] | [
"python",
"python_idle"
] | stackoverflow_0074659121_python_python_idle.txt |
Q:
Avoid KeyError while selecting several data from several groups
I am trying to add certain values from certain Brand from certain Month by using .groupby, but I keep getting the same Error: KeyError: ('Acura', '1', '2020')
This Values Do exist in the file i am importing:
ANIO ID_MES MARCA MODELO UNI_VEH
202... | Avoid KeyError while selecting several data from several groups | I am trying to add certain values from certain Brand from certain Month by using .groupby, but I keep getting the same Error: KeyError: ('Acura', '1', '2020')
This Values Do exist in the file i am importing:
ANIO ID_MES MARCA MODELO UNI_VEH
2020 1 Acura ILX 6
2020 1 Acura Mdx 19
2020 1 Acura ... | [
"If need filter DataFrame by year, brand and months you can avoid groupby and use DataFrame.loc with mask - if scalar compare by Series.eq, if multiple values use Series.isin:\ndef sumMonthValues (year, brand):\n \n months = 10 if year == 2022 else 12\n \n mask = (df['ID_MES'].isin(range(1, months+1)) &... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074651550_pandas_python.txt |
Q:
How to select the first representative element for each group of a DataFrameGroupBy object?
I am having the following dataframe
data = [
[1000, 1, 1], [1000, 1, 1], [1000, 1, 1], [1000, 1, 2], [1000, 1, 2],
[1000, 1, 2], [2000, 0, 1], [2000, 0, 1], [2000, 1, 2],
[2000, 0, 2], [2000, 1, 2]]
df = pd.Data... | How to select the first representative element for each group of a DataFrameGroupBy object? | I am having the following dataframe
data = [
[1000, 1, 1], [1000, 1, 1], [1000, 1, 1], [1000, 1, 2], [1000, 1, 2],
[1000, 1, 2], [2000, 0, 1], [2000, 0, 1], [2000, 1, 2],
[2000, 0, 2], [2000, 1, 2]]
df = pd.DataFrame(data, columns=['route_id', 'direction_id', 'trip_id'])
Then, I group my df based on the co... | [
"To store the value of the trip_id column based on the first most popular trip_id of each unique route_id, direction_id combination, you can use the idxmax method on the groupby object to get the index of the first most popular trip_id, and then use this index to access the value of the trip_id column.\nHere is an ... | [
0,
0
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074659038_group_by_pandas_python.txt |
Q:
How to get a continuously changing user input dependent output in the same place at command line
I am designing a string based game where the real time positions of characters are represented as a string as follows:
-----A-----o-----
I am changing the position of the character "A" based upon user keyboard inpu... | How to get a continuously changing user input dependent output in the same place at command line | I am designing a string based game where the real time positions of characters are represented as a string as follows:
-----A-----o-----
I am changing the position of the character "A" based upon user keyboard inputs
eg:
updated position:
--------A--o-----
I don't want to print the string line by line as It get... | [
"You could use '\\r' in some way. Carriage return is a control character or mechanism used to reset a device's position to the beginning of a line of text. e.g.\nimport time\n\nfor i in range(100):\n time.sleep(1)\n print(i, end=\"\\r\");\n\nExample including controls\nimport time\nimport keyboard\n\n# params... | [
0,
0
] | [] | [] | [
"input",
"output",
"python",
"string"
] | stackoverflow_0074655251_input_output_python_string.txt |
Q:
How to operate times in python
I am very new to using python and now I need to add times in minutes. I mean, the data that the computer gives me is 10:23:12 , the first being the hours, then the minutes and finally the seconds. What I want to do is to have a cumulative time in minutes, that cell 1 is added with ce... | How to operate times in python | I am very new to using python and now I need to add times in minutes. I mean, the data that the computer gives me is 10:23:12 , the first being the hours, then the minutes and finally the seconds. What I want to do is to have a cumulative time in minutes, that cell 1 is added with cell 2, and cell 2 with cell 2.
In exc... | [
"You don't have to directly operate with the time. Just transform the string and do the calculations you need, for example, like this:\nn = '3:51:52' # As an example. Substitute with your actual strings.\nhours, minutes, seconds = map(int, n.split(':'))\n# Effectively, the above line does something akin to this: \... | [
0
] | [] | [] | [
"pandas",
"python",
"time"
] | stackoverflow_0074659228_pandas_python_time.txt |
Q:
Geopandas: not able to change the crs of a geopandas object
I am trying to set the crs of a geopandas object as described here.
The example file can be downloaded from here
import geopandas as gdp
df = pd.read_pickle('myShp.pickle')
I upload the screenshot to show the values of the coordinates
then if I try to c... | Geopandas: not able to change the crs of a geopandas object | I am trying to set the crs of a geopandas object as described here.
The example file can be downloaded from here
import geopandas as gdp
df = pd.read_pickle('myShp.pickle')
I upload the screenshot to show the values of the coordinates
then if I try to change the crs the values of the polygon don't change
tmp = gpd.Ge... | [
"Setting the crs like:\ngdf.crs = {'init' :'epsg:32618'}\n\ndoes not transform your data, it only sets the CRS (it basically says: \"my data is represented in this CRS\"). In most cases, the CRS is already set while reading the data with geopandas.read_file (if your file has CRS information). So you only need the a... | [
4,
0
] | [] | [] | [
"geopandas",
"python"
] | stackoverflow_0056274566_geopandas_python.txt |
Q:
Can a numpy array be printed, if it is tied to an instance of a class?
I am trying to create a Map(n) object, which is an n*n 2D array with random [0,1]s, and print it out.
How do I access the create_grid return value of my map1 instance, to be able to print it out?
Please be gentle, I am self-learning python, and... | Can a numpy array be printed, if it is tied to an instance of a class? | I am trying to create a Map(n) object, which is an n*n 2D array with random [0,1]s, and print it out.
How do I access the create_grid return value of my map1 instance, to be able to print it out?
Please be gentle, I am self-learning python, and wish to expand my knowledge.
I wish to create something like this:
map1 = M... | [
"Maybe you could just make a string representation of your class that uses numpy.np.array2string()\nimport numpy as np\n\nclass Map:\n def __init__(self, n):\n self.n = n\n self.create_grid(n)\n\n def create_grid(self, n):\n self.arr = np.random.randint(0, 2, size=(n, n))\n \n d... | [
1
] | [] | [] | [
"2d",
"arrays",
"list",
"numpy",
"python"
] | stackoverflow_0074659341_2d_arrays_list_numpy_python.txt |
Q:
Upgrade or migrate only single schema using Flask-Migrate(Alembic)
I have a multi-schema DB structure.I am using Flask-Migrate, Flask-Script and alembic to manage migrations.Is there a way to upgrade and perform migrations for only one single schema?
Thank you
A:
You have to filter the imported object to select ... | Upgrade or migrate only single schema using Flask-Migrate(Alembic) | I have a multi-schema DB structure.I am using Flask-Migrate, Flask-Script and alembic to manage migrations.Is there a way to upgrade and perform migrations for only one single schema?
Thank you
| [
"You have to filter the imported object to select only ones contained in the wanted schema with:\ndef include_name(name, type_, parent_names):\n if type_ == \"schema\":\n return name == SCHEMA_WANTED\n return True\n\nand then:\ncontext.configure(\n connection=connection,\n target_metadata=get_metad... | [
0
] | [] | [] | [
"alembic",
"flask_migrate",
"flask_script",
"python",
"sqlalchemy"
] | stackoverflow_0073899162_alembic_flask_migrate_flask_script_python_sqlalchemy.txt |
Q:
How to change depth of spectrogram to 3
I have a file that i get after downsampling and after i create spectogram from them, i get in shape of
enter image description here
And after converting them into spectogram with the help of
enter image description here
I get the shape enter image description here
and after ... | How to change depth of spectrogram to 3 | I have a file that i get after downsampling and after i create spectogram from them, i get in shape of
enter image description here
And after converting them into spectogram with the help of
enter image description here
I get the shape enter image description here
and after 1 extra dimension with the help of reshape fu... | [
"This time since it was needed to make a depth of 3. I simply concatenated same image 3 times with the help of np.concatenate function and it worked\n"
] | [
0
] | [] | [] | [
"audio_processing",
"deep_learning",
"python",
"signal_processing"
] | stackoverflow_0074499607_audio_processing_deep_learning_python_signal_processing.txt |
Q:
How can I explode a nested dictionary into a dataframe?
I have a nested dictionary as below. I'm trying to convert the below to a dataframe with the columns iid, Invnum, @type, execId, CId, AId, df, type. What’s the best way to go about it?
data = {'A': {'B1': {'iid': 'B1', 'Invnum': {'B11': {'@type': '/test_data'... | How can I explode a nested dictionary into a dataframe? | I have a nested dictionary as below. I'm trying to convert the below to a dataframe with the columns iid, Invnum, @type, execId, CId, AId, df, type. What’s the best way to go about it?
data = {'A': {'B1': {'iid': 'B1', 'Invnum': {'B11': {'@type': '/test_data', 'execId': 42, 'CId': 42, 'AId': 'BAZ'}, 'B12': {'@type': '/... | [
"As indicated in the comments, your input data is very obscure. This provides a lot of trouble for us, because we don't know what we can assume or not. For my solution I will assume at least the following, based on the example you provide:\n\nIn the dictionary there is an entry containing the iid and Invnum as keys... | [
1
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074647213_dataframe_dictionary_pandas_python_python_3.x.txt |
Q:
Combining series to create a dataframe
I have two series of stock prices (containing date, ticker, open, high, low, close) and I'd like to know how to combine them to create a dataframe just like the way Yahoo!Finance does. Is it possible?
"Join and merge" don't seem to work
A:
Use pd.concat([sr1, sr2], axis=1) ... | Combining series to create a dataframe | I have two series of stock prices (containing date, ticker, open, high, low, close) and I'd like to know how to combine them to create a dataframe just like the way Yahoo!Finance does. Is it possible?
"Join and merge" don't seem to work
| [
"Use pd.concat([sr1, sr2], axis=1) if neither one of join and merge work.\n"
] | [
3
] | [] | [] | [
"dataframe",
"pandas",
"python",
"yahoo_api",
"yahoo_finance"
] | stackoverflow_0074659398_dataframe_pandas_python_yahoo_api_yahoo_finance.txt |
Q:
How to print a specific part of an exception error
I am trying to handle an exception from an API I am using and would like to send a message to the user with a specific part of the error That is being sent. How would I separate it?
The result of printing the exception looks like this:
NoneFull details: [{'code': ... | How to print a specific part of an exception error | I am trying to handle an exception from an API I am using and would like to send a message to the user with a specific part of the error That is being sent. How would I separate it?
The result of printing the exception looks like this:
NoneFull details: [{'code': 10010, 'detail': 'Originating number listed in do-not-or... | [
"This should work because it seems that e is a list[dict] in your case:\ntry:\n pass # Your code...\nexcept api.error.PermissionError as e:\n print(e.args[0][0]['detail'])\n\nIf you added manually the [] then maybe you will have to remove one of the [0].\n"
] | [
0
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0074658914_exception_python.txt |
Q:
RuntimeError: cuDNN error: CUDNN_STATUS_NOT_INITIALIZED using pytorch
I am trying to run a simple pytorch sample code. It's works fine using CPU. But when using GPU, i get this error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/tor... | RuntimeError: cuDNN error: CUDNN_STATUS_NOT_INITIALIZED using pytorch | I am trying to run a simple pytorch sample code. It's works fine using CPU. But when using GPU, i get this error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward... | [
"There is some discussion regarding this here. I had the same issue but using cuda 11.1 resolved it for me.\nThis is the exact pip command\npip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio==0.8.0 -f https://download.pytorch.org/whl/torch_stable.html\n\n",
"In my case it actually had nothing do w... | [
19,
12,
7,
1,
1,
0
] | [] | [] | [
"gpu",
"python",
"pytorch"
] | stackoverflow_0066588715_gpu_python_pytorch.txt |
Q:
Replace values from second row onwards in a pandas pipe method
I am wondering how to replace values from second row onwards in a pipe method (connecting to the rest of steps).
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"Date": ["2020-01-01", "2021-01-01", "2022-01-01"],
"Pop":... | Replace values from second row onwards in a pandas pipe method | I am wondering how to replace values from second row onwards in a pipe method (connecting to the rest of steps).
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"Date": ["2020-01-01", "2021-01-01", "2022-01-01"],
"Pop": [90, 70, 60],
}
)
Date Pop
0 2020-01-01 90
1 202... | [
"You can also use assign like this:\ndf.assign(Pop=df.loc[[0], 'Pop'])\n\nOutput:\n Date Pop\n0 2020-01-01 90.0\n1 2021-01-01 NaN\n2 2022-01-01 NaN\n\nNote: assign works with nice column headers, if your headers have spaces or special characters you will need to use a different method.\n",
"To r... | [
3,
2
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074659122_numpy_pandas_python.txt |
Q:
Print the nth step of a Generator in an easy way
I want to know if there is a better and cleaner way of printing the 3rd step of a generator function.
Currently I have written the following code
def imparesgen():
n = 0
while n<200:
n=n+2
yield n
gen = imparesgen()
y = 0
for x in gen:
y+=1
if y =... | Print the nth step of a Generator in an easy way | I want to know if there is a better and cleaner way of printing the 3rd step of a generator function.
Currently I have written the following code
def imparesgen():
n = 0
while n<200:
n=n+2
yield n
gen = imparesgen()
y = 0
for x in gen:
y+=1
if y == 3:
print(x)
This worked, but, is there maybe a ... | [
"From Itertools recipes:\ndef nth(iterable, n, default=None):\n \"Returns the nth item or a default value\"\n return next(islice(iterable, n, None), default)\n\nApplied to your example:\nimport itertools\n\ndef imparesgen():\n n = 0\n while n<200:\n n=n+2\n yield n\n\ngen = imparesgen()\n\nprint(next(... | [
2,
0,
0
] | [
"Since a generator acts like an iterator, you can call next on it :\nthird = next(next(next(gen)))\n\nI don't think you can go much faster than that in pure-Python. But I think that without benchmarking the code, the speedup won't be noticed.\n"
] | [
-2
] | [
"generator",
"python"
] | stackoverflow_0074659302_generator_python.txt |
Q:
How can I define the ManyToManyField name in django?
I have this relationship
Class Item(models.Model):
pass
Class Category(models.Model):
items = models.ManyToManyField(Item)
I can define the field name as items for category and access it via category.items but I want to define a field name for Item too a... | How can I define the ManyToManyField name in django? | I have this relationship
Class Item(models.Model):
pass
Class Category(models.Model):
items = models.ManyToManyField(Item)
I can define the field name as items for category and access it via category.items but I want to define a field name for Item too as item.categories rather than the default item.category
Ho... | [
"The thing about many to many field is not an actual field. If you take a look at the generated schema you wouldnt find the field as a column in either of the table. What happens in the back is django creates a ItemCatagory table.\nclass ItemCatagory(models.Model):\n item = modes.ForegnKeyField(Item, related_n... | [
1,
0
] | [
"See, ManyToManyField can't make reverse relationship with related model as python is interpreted language, so it can't read model class of previous one. Instead, you can do one thing ...\n# models.py\n\nclass Item(models.Model):\n item_name = models.CharField(max_length=255, default=\"\")\n\n def __str__(sel... | [
-1
] | [
"django",
"django_models",
"many_to_many",
"python"
] | stackoverflow_0074613493_django_django_models_many_to_many_python.txt |
Q:
How to break while loop immediately after condition is met (and not run rest of code)?
I have this dice game made in python for class, I am using functions for the scoring logic (which I believe is all working as desired). I have put these functions in a while loop so that when either player reaches 100 banked sco... | How to break while loop immediately after condition is met (and not run rest of code)? | I have this dice game made in python for class, I am using functions for the scoring logic (which I believe is all working as desired). I have put these functions in a while loop so that when either player reaches 100 banked score the game ends. However, I cannot get this to work as intended.
while int(player1Score) < ... | [
"bro.\ni read your code but i can't get some points as below.\n\n\nif dice1 == '1' and dice2 == '1': #both die = 1 (banked & running = 0)\n player1Score = 0\n\n\n\nthe code above makes player1Score as zero.\nand there's no adding score code for player2Score.\nFor this reason, the while loop doesn't stop.... | [
0,
0,
0
] | [] | [] | [
"boolean_logic",
"logic",
"python"
] | stackoverflow_0074637964_boolean_logic_logic_python.txt |
Q:
Seaborn showing wrong y-axis values
The dataframe I created is as follows:
import pandas as pd
import numpy as np
import seaborn as sns
date = pd.date_range('2003-01-01', '2022-11-01', freq='MS').strftime('%Y-%m-%d').tolist()
mom = [np.nan] + list(np.repeat([0.01], 238))
cpi = [100] + list(np.repeat([np.nan], 238... | Seaborn showing wrong y-axis values | The dataframe I created is as follows:
import pandas as pd
import numpy as np
import seaborn as sns
date = pd.date_range('2003-01-01', '2022-11-01', freq='MS').strftime('%Y-%m-%d').tolist()
mom = [np.nan] + list(np.repeat([0.01], 238))
cpi = [100] + list(np.repeat([np.nan], 238))
df = pd.DataFrame(list(zip(date, mom, ... | [
"You can use matplotlib to set the axis scaling, as the difference is really subtle in your data:\nimport matplotlib.pyplot as plt\n\nax = plt.gca()\nax.set_ylim([df.yoy.min(numeric_only=True), df.yoy.max(numeric_only=True)])\n\nsns.lineplot(\n x = 'date',\n y = 'yoy',\n data = df,\n ax = ax\n)\n\nWith ... | [
0
] | [] | [] | [
"python",
"seaborn"
] | stackoverflow_0074658711_python_seaborn.txt |
Q:
Issue installing Scikit learn
I know this question has been up many times before and I've tried to follow the steps as outlined, but my scikit still won't work.
I have Python 3.11, on Windows 11, using Spyder. When trying to run the following code I get this error.
import sklearn
print(sklearn.__version__)
File "... | Issue installing Scikit learn | I know this question has been up many times before and I've tried to follow the steps as outlined, but my scikit still won't work.
I have Python 3.11, on Windows 11, using Spyder. When trying to run the following code I get this error.
import sklearn
print(sklearn.__version__)
File "C:\Program Files\Spyder\pkgs\spyde... | [
"Uninstall your current spyder installation and reinstall it with Anaconda. Your terminal environment is fundamentally different from your overall environment. As such installing sci-kit learn on your Linux distro on terminal still doesn't give you access to the library elsewhere. Anaconda is the easiest way to ins... | [
0
] | [] | [] | [
"installation",
"python",
"python_3.x",
"scikit_learn"
] | stackoverflow_0074658723_installation_python_python_3.x_scikit_learn.txt |
Q:
PYTHONPATH variable missing when using os.execlpe to restart script as root
My end goal is to have a script that can be initially launched by a non-privileged user without using sudo, but will prompt for sudo password and self-elevate to root. I've been doing this with a bash wrapper script but would like somethin... | PYTHONPATH variable missing when using os.execlpe to restart script as root | My end goal is to have a script that can be initially launched by a non-privileged user without using sudo, but will prompt for sudo password and self-elevate to root. I've been doing this with a bash wrapper script but would like something tidier that doesn't need an additional file.
Some googling found this question ... | [
"I found this very weird too, and couldn't find any direct way to pass the environment into the replaced process. But I didn't do a full system debugging either.\nWhat I found to work as a workaround is this:\npypath = os.environ.get('PYTHONPATH', \"\")\nargs = ['sudo', f\"PYTHONPATH={pypath}\", sys.executable] + s... | [
0
] | [
"You're passing the environment as arguments to your script instead of arguments to execlpe. Try this instead:\nargs = ['sudo', sys,executable] + sys.argv + [os.environ]\nos.execvpe('sudo', args, os.environ)\n\nIf you just want to inherit the environment you can even\nos.execvp('sudo', args)\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0044559046_python.txt |
Q:
local variable 'product' referenced before assignment
I am trying to create a django view which will let users to create a new product on the website.
class CreateProductView(APIView):
serializer_class = CreateProductSerializer
def post(self, request, format = None):
serializer = self.se... | local variable 'product' referenced before assignment | I am trying to create a django view which will let users to create a new product on the website.
class CreateProductView(APIView):
serializer_class = CreateProductSerializer
def post(self, request, format = None):
serializer = self.serializer_class(data=request.data)
if serializer.is_... | [
"You are trying to reference the product variable before it has been assigned when serializer.is_valid() is False.\nYou should move the response line inside the if statement, so that it is only returned if serializer.is_valid() is True and handle the response for invalid serializer with an http error for example.\n... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074659435_django_python.txt |
Q:
Get the amount of leading NaN and trailing non NaN values in pandas dataframe
I have a dataframe where the rows contain NaN values. The df contains original columns namely Heading 1 Heading 2 and Heading 3 and extra columns called Unnamed: 1 Unnamed: 2 and Unnamed: 3 as shown:
Heading 1
Heading 2
Heading 3
Unname... | Get the amount of leading NaN and trailing non NaN values in pandas dataframe | I have a dataframe where the rows contain NaN values. The df contains original columns namely Heading 1 Heading 2 and Heading 3 and extra columns called Unnamed: 1 Unnamed: 2 and Unnamed: 3 as shown:
Heading 1
Heading 2
Heading 3
Unnamed: 1
Unnamed: 2
Unnamed: 3
NaN
34
24
45
NaN
NaN
NaN
NaN
24
45
11
NaN
NaN... | [
"To iterate through each row in a DataFrame and count the number of NaN values in the original columns and the number of non-NaN values in the extra columns, you can do the following:\nimport pandas as pd\n\n# Define the dataframe\ndf = pd.DataFrame(\n {\n \"Heading 1\": [np.nan, np.nan, 5, 5, np.nan, np.... | [
0,
0,
0
] | [] | [] | [
"data_cleaning",
"data_preprocessing",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074659310_data_cleaning_data_preprocessing_dataframe_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.